python: [Errno 10054] An existing connection was forcibly closed by the remote host
For me this problem arised while trying to connect to the SAP Hana database. When I got this error,
OperationalError: Lost connection to HANA server (ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))
I tried to run the code for connection(mentioned below), which created that error, again and it worked.
import pyhdb
connection = pyhdb.connect(host="example.com",port=30015,user="user",password="secret")
cursor = connection.cursor()
cursor.execute("SELECT 'Hello Python World' FROM DUMMY")
cursor.fetchone()
connection.close()
It was because the server refused to connect. It might require you to wait for a while and try again. Try closing the Hana Studio by logging off and then logging in again. Keep running the code for a number of times.
Update data on a page without refreshing
In general, if you don't know how something works, look for an example which you can learn from.
For this problem, consider this DEMO
You can see loading content with AJAX is very easily accomplished with jQuery:
$(function(){
// don't cache ajax or content won't be fresh
$.ajaxSetup ({
cache: false
});
var ajax_load = "<img src='http://automobiles.honda.com/images/current-offers/small-loading.gif' alt='loading...' />";
// load() functions
var loadUrl = "http://fiddle.jshell.net/deborah/pkmvD/show/";
$("#loadbasic").click(function(){
$("#result").html(ajax_load).load(loadUrl);
});
// end
});
Try to understand how this works and then try replicating it. Good luck.
You can find the corresponding tutorial HERE
Update
Right now the following event starts the ajax load
function:
$("#loadbasic").click(function(){
$("#result").html(ajax_load).load(loadUrl);
});
You can also do this periodically: How to fire AJAX request Periodically?
(function worker() {
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 5000);
}
});
})();
I made a demo of this implementation for you HERE. In this demo, every 2 seconds (setTimeout(worker, 2000);
) the content is updated.
You can also just load the data immediately:
$("#result").html(ajax_load).load(loadUrl);
Which has THIS corresponding demo.
Should you use rgba(0, 0, 0, 0) or rgba(255, 255, 255, 0) for transparency in CSS?
There a small difference when u use rgba(255,255,255,a),background color becomes more and more lighter as the value of 'a' increase from 0.0 to 1.0. Where as when use rgba(0,0,0,a), the background color becomes more and more darker as the value of 'a' increases from 0.0 to 1.0.
Having said that, its clear that both (255,255,255,0) and (0,0,0,0) make background
transparent.
(255,255,255,1) would make the background completely white where as (0,0,0,1) would make background completely black.
How to print_r $_POST array?
$_POST is already an array, so you don't need to wrap array() around it.
Try this instead:
<?php
for ($i=0;$i<count($_POST['id']);$i++) {
echo "<p>".$_POST['id'][$i]."</p>";
echo "<p>".$_POST['value'][$i]."</p>";
echo "<hr />";
}
?>
NOTE: This works because your id
and value
arrays are symmetrical. If they had different numbers of elements then you'd need to take a different approach.
Keystore change passwords
[How can I] Change the password, so I can share it with others and let them sign
Using keytool:
keytool -storepasswd -keystore /path/to/keystore
Enter keystore password: changeit
New keystore password: new-password
Re-enter new keystore password: new-password
How to fetch the row count for all tables in a SQL SERVER database
This is my favorite solution for SQL 2008 , which puts the results into a "TEST" temp table that I can use to sort and get the results that I need :
SET NOCOUNT ON
DBCC UPDATEUSAGE(0)
DROP TABLE #t;
CREATE TABLE #t
(
[name] NVARCHAR(128),
[rows] CHAR(11),
reserved VARCHAR(18),
data VARCHAR(18),
index_size VARCHAR(18),
unused VARCHAR(18)
) ;
INSERT #t EXEC sp_msForEachTable 'EXEC sp_spaceused ''?'''
SELECT * INTO TEST FROM #t;
DROP TABLE #t;
SELECT name, [rows], reserved, data, index_size, unused FROM TEST \
WHERE ([rows] > 0) AND (name LIKE 'XXX%')
How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?
Sorry, but I think the accepted answer is an overkill. All you need to do is this:
public class ElmahHandledErrorLoggerFilter : IExceptionFilter
{
public void OnException (ExceptionContext context)
{
// Log only handled exceptions, because all other will be caught by ELMAH anyway.
if (context.ExceptionHandled)
ErrorSignal.FromCurrentContext().Raise(context.Exception);
}
}
and then register it (order is important) in Global.asax.cs:
public static void RegisterGlobalFilters (GlobalFilterCollection filters)
{
filters.Add(new ElmahHandledErrorLoggerFilter());
filters.Add(new HandleErrorAttribute());
}
Angular get object from array by Id
CASE - 1
Using array.filter()
We can get an array of objects which will match with our condition.
see the working example.
_x000D_
_x000D_
var questions = [
{id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
{id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
{id: 3, question: "1 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
{id: 3, question: "2 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
{id: 3, question: "3 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
{id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
{id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
{id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
{id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
{id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
{id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
{id: 10, question: "1 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
{id: 10, question: "2 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
{id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
{id: 12, question: "Do you feel a sense of peace and contentment in your home? ", category: "Home Environment", subs: []},
{id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
{id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
{id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
];
function filter(){
console.clear();
var filter_id = document.getElementById("filter").value;
var filter_array = questions.filter(x => x.id == filter_id);
console.log(filter_array);
}
_x000D_
button {
background: #0095ff;
color: white;
border: none;
border-radius: 3px;
padding: 8px;
cursor: pointer;
}
input {
padding: 8px;
}
_x000D_
<div>
<label for="filter"></label>
<input id="filter" type="number" name="filter" placeholder="Enter id which you want to filter">
<button onclick="filter()">Filter</button>
</div>
_x000D_
_x000D_
_x000D_
CASE - 2
Using array.find()
we can get first matched item and break the iteration.
_x000D_
_x000D_
var questions = [
{id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
{id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
{id: 3, question: "1 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
{id: 3, question: "2 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
{id: 3, question: "3 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
{id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
{id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
{id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
{id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
{id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
{id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
{id: 10, question: "1 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
{id: 10, question: "2 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
{id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
{id: 12, question: "Do you feel a sense of peace and contentment in your home? ", category: "Home Environment", subs: []},
{id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
{id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
{id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
];
function find(){
console.clear();
var find_id = document.getElementById("find").value;
var find_object = questions.find(x => x.id == find_id);
console.log(find_object);
}
_x000D_
button {
background: #0095ff;
color: white;
border: none;
border-radius: 3px;
padding: 8px;
cursor: pointer;
}
input {
padding: 8px;
width: 200px;
}
_x000D_
<div>
<label for="find"></label>
<input id="find" type="number" name="find" placeholder="Enter id which you want to find">
<button onclick="find()">Find</button>
</div>
_x000D_
_x000D_
_x000D_
How to set up a Web API controller for multipart/form-data
Here's another answer for the ASP.Net Core solution to this problem...
On the Angular side, I took this code example...
https://stackblitz.com/edit/angular-drag-n-drop-directive
... and modified it to call an HTTP Post endpoint:
prepareFilesList(files: Array<any>) {
const formData = new FormData();
for (var i = 0; i < files.length; i++) {
formData.append("file[]", files[i]);
}
let URL = "https://localhost:44353/api/Users";
this.http.post(URL, formData).subscribe(
data => { console.log(data); },
error => { console.log(error); }
);
With this in place, here's the code I needed in the ASP.Net Core WebAPI controller:
[HttpPost]
public ActionResult Post()
{
try
{
var files = Request.Form.Files;
foreach (IFormFile file in files)
{
if (file.Length == 0)
continue;
string tempFilename = Path.Combine(Path.GetTempPath(), file.FileName);
System.Diagnostics.Trace.WriteLine($"Saved file to: {tempFilename}");
using (var fileStream = new FileStream(tempFilename, FileMode.Create))
{
file.CopyTo(fileStream);
}
}
return new OkObjectResult("Yes");
}
catch (Exception ex)
{
return new BadRequestObjectResult(ex.Message);
}
}
Shockingly simple, but I had to piece together examples from several (almost-correct) sources to get this to work properly.
Disable Rails SQL logging in console
In case someone wants to actually knock out SQL statement logging (without changing logging level, and while keeping the logging from their AR models):
The line that writes to the log (in Rails 3.2.16, anyway) is the call to debug
in lib/active_record/log_subscriber.rb:50
.
That debug method is defined by ActiveSupport::LogSubscriber
.
So we can knock out the logging by overwriting it like so:
module ActiveSupport
class LogSubscriber
def debug(*args, &block)
end
end
end
Linq to Entities - SQL "IN" clause
I also tried to work with an SQL-IN-like thing - querying against an Entity Data Model. My approach is a string builder to compose a big OR-expression. That's terribly ugly, but I'm afraid it's the only way to go right now.
Now well, that looks like this:
Queue<Guid> productIds = new Queue<Guid>(Products.Select(p => p.Key));
if(productIds.Count > 0)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}.ProductId = Guid\'{1}\'", entities.Products.Name, productIds.Dequeue());
while(productIds.Count > 0)
{
sb.AppendFormat(" OR {0}.ProductId = Guid\'{1}\'",
entities.Products.Name, productIds.Dequeue());
}
}
Working with GUIDs in this context: As you can see above, there is always the word "GUID" before the GUID ifself in the query string fragments. If you don't add this, ObjectQuery<T>.Where
throws the following exception:
The argument types 'Edm.Guid' and
'Edm.String' are incompatible for this
operation., near equals expression,
line 6, column 14.
Found this in MSDN Forums, might be helpful to have in mind.
Matthias
... looking forward for the next version of .NET and Entity Framework, when everything get's better. :)
How to sum array of numbers in Ruby?
array.reduce(0, :+)
While equivalent to array.inject(0, :+)
, the term reduce is entering a more common vernacular with the rise of MapReduce programming models.
inject, reduce, fold, accumulate, and compress are all synonymous as a class of folding functions. I find consistency across your code base most important, but since various communities tend to prefer one word over another, it’s nonetheless useful to know the alternatives.
To emphasize the map-reduce verbiage, here’s a version that is a little bit more forgiving on what ends up in that array.
array.map(&:to_i).reduce(0, :+)
Some additional relevant reading:
How to add new column to MYSQL table?
You should look into normalizing your database to avoid creating columns at runtime.
Make 3 tables:
- assessment
- question
- assessment_question (columns assessmentId, questionId)
Put questions and assessments in their respective tables and link them together through assessment_question using foreign keys.
Android: How to rotate a bitmap on a center point
matrix.reset();
matrix.setTranslate( anchor.x, anchor.y );
matrix.postRotate((float) rotation , 0,0);
matrix.postTranslate(positionOfAnchor.x, positionOfAnchor.x);
c.drawBitmap(bitmap, matrix, null);
How to add a downloaded .box file to Vagrant?
You can point to the folder where vagrant and copy the box file to same location. Then after you may run as follows
vagrant box add my-box name-of-the-box.box
vagrant init my-box
vagrant up
Just to check status
vagrant status
What is the difference between pull and clone in git?
git clone
means you are making a copy of the repository in your system.
git fork
means you are copying the repository to your Github account.
git pull
means you are fetching the last modified repository.
git push
means you are returning the repository after modifying it.
In layman's term:
git clone
is downloading and git pull
is refreshing.
How to convert index of a pandas dataframe into a column?
To provide a bit more clarity, let's look at a DataFrame with two levels in its index (a MultiIndex).
index = pd.MultiIndex.from_product([['TX', 'FL', 'CA'],
['North', 'South']],
names=['State', 'Direction'])
df = pd.DataFrame(index=index,
data=np.random.randint(0, 10, (6,4)),
columns=list('abcd'))
The reset_index
method, called with the default parameters, converts all index levels to columns and uses a simple RangeIndex
as new index.
df.reset_index()
Use the level
parameter to control which index levels are converted into columns. If possible, use the level name, which is more explicit. If there are no level names, you can refer to each level by its integer location, which begin at 0 from the outside. You can use a scalar value here or a list of all the indexes you would like to reset.
df.reset_index(level='State') # same as df.reset_index(level=0)
In the rare event that you want to preserve the index and turn the index into a column, you can do the following:
# for a single level
df.assign(State=df.index.get_level_values('State'))
# for all levels
df.assign(**df.index.to_frame())
#1071 - Specified key was too long; max key length is 1000 bytes
This error means that length of index index
is more then 1000 bytes. MySQL and storage engines may have this restriction. I have got similar error on MySQL 5.5 - 'Specified key was too long; max key length is 3072 bytes' when ran this script:
CREATE TABLE IF NOT EXISTS test_table1 (
column1 varchar(500) NOT NULL,
column2 varchar(500) NOT NULL,
column3 varchar(500) NOT NULL,
column4 varchar(500) NOT NULL,
column5 varchar(500) NOT NULL,
column6 varchar(500) NOT NULL,
KEY `index` (column1, column2, column3, column4, column5, column6)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
UTF8 is multi-bytes, and key length is calculated in this way - 500 * 3 * 6 = 9000 bytes.
But note, next query works!
CREATE TABLE IF NOT EXISTS test_table1 (
column1 varchar(500) NOT NULL,
column2 varchar(500) NOT NULL,
column3 varchar(500) NOT NULL,
column4 varchar(500) NOT NULL,
column5 varchar(500) NOT NULL,
column6 varchar(500) NOT NULL,
KEY `index` (column1, column2, column3, column4, column5, column6)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
...because I used CHARSET=latin1, in this case key length is 500 * 6 = 3000 bytes.
How can I remove a pytz timezone from a datetime object?
To remove a timezone (tzinfo) from a datetime object:
# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)
If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.
# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')
# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime
# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)
Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime
object to insert into the database. The solution is to convert your datetime.datetime
object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime
objects where one is timezone aware and another is timezone naive.
##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')
arrowDt = arrowObj.to("utc").datetime
# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)
# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()
# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3
# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True
How can I convert a string to an int in Python?
def addition(a, b):
return a + b
def subtraction(a, b):
return a - b
def multiplication(a, b):
return a * b
def division(a, b):
return a / b
keepProgramRunning = True
print "Welcome to the Calculator!"
while keepProgramRunning:
print "Please choose what you'd like to do:"
print "0: Addition"
print "1: Subtraction"
print "2: Multiplication"
print "3: Division"
print "4: Quit Application"
#Capture the menu choice.
choice = raw_input()
if choice == "0":
numberA = input("Enter your first number: ")
numberB = input("Enter your second number: ")
print "Your result is: " + str(addition(numberA, numberB)) + "\n"
elif choice == "1":
numberA = input("Enter your first number: ")
numberB = input("Enter your second number: ")
print "Your result is: " + str(subtraction(numberA, numberB)) + "\n"
elif choice == "2":
numberA = input("Enter your first number: ")
numberB = input("Enter your second number: ")
print "Your result is: " + str(multiplication(numberA, numberB)) + "\n"
elif choice == "3":
numberA = input("Enter your first number: ")
numberB = input("Enter your second number: ")
print "Your result is: " + str(division(numberA, numberB)) + "\n"
elif choice == "4":
print "Bye!"
keepProgramRunning = False
else:
print "Please choose a valid option."
print "\n"
Create a file if it doesn't exist
Here's a quick two-liner that I use to quickly create a file if it doesn't exists.
if not os.path.exists(filename):
open(filename, 'w').close()
Action Image MVC3 Razor
You can use Url.Content
which works for all links as it translates the tilde ~
to the root uri.
<a href="@Url.Action("Edit", new { id=MyId })">
<img src="@Url.Content("~/Content/Images/Image.bmp")", alt="Edit" />
</a>
Jquery function return value
I'm not entirely sure of the general purpose of the function, but you could always do this:
function getMachine(color, qty) {
var retval;
$("#getMachine li").each(function() {
var thisArray = $(this).text().split("~");
if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
retval = thisArray[3];
return false;
}
});
return retval;
}
var retval = getMachine(color, qty);
How to set delay in vbscript
A lot of the answers here assume that you're running your VBScript in the Windows Scripting Host (usually wscript.exe
or cscript.exe
). If you're getting errors like 'Variable is undefined: "WScript"' then you're probably not.
The WScript object is only available if you're running under the Windows Scripting Host, if you're running under another script host, such as Internet Explorer's (and you might be without realising it if you're in something like an HTA) it's not automatically available.
Microsoft's Hey, Scripting Guy! Blog has an article that goes into just this topic How Can I Temporarily Pause a Script in an HTA? in which they use a VBScript setTimeout
to create a timer to simulate a Sleep without needing to use CPU hogging loops, etc.
The code used is this:
<script language = "VBScript">
Dim dtmStartTime
Sub Test
dtmStartTime = Now
idTimer = window.setTimeout("PausedSection", 5000, "VBScript")
End Sub
Sub PausedSection
Msgbox dtmStartTime & vbCrLf & Now
window.clearTimeout(idTimer)
End Sub
</script>
<body>
<input id=runbutton type="button" value="Run Button" onClick="Test">
</body>
See the linked blog post for the full explanation, but essentially when the button is clicked it creates a timer that fires 5,000 milliseconds from now, and when it fires runs the VBScript sub-routine called "PausedSection" which clears the timer, and runs whatever code you want it to.
Open a PDF using VBA in Excel
Use Shell "program file path file path you want to open"
.
Example:
Shell "c:\windows\system32\mspaint.exe c:users\admin\x.jpg"
How to change font-color for disabled input?
This works for making disabled select options act as headers. It doesnt remove the default text shadow of the :disabled option but it does remove the hover effect. In IE you wont get the font color but at least the text-shadow is gone. Here is the html and css:
_x000D_
_x000D_
select option.disabled:disabled{color: #5C3333;background-color: #fff;font-weight: bold;}_x000D_
select option.disabled:hover{color: #5C3333 !important;background-color: #fff;}_x000D_
select option:hover{color: #fde8c4;background-color: #5C3333;}
_x000D_
<select>_x000D_
<option class="disabled" disabled>Header1</option>_x000D_
<option>Item1</option>_x000D_
<option>Item1</option>_x000D_
<option>Item1</option>_x000D_
<option class="disabled" disabled>Header2</option>_x000D_
<option>Item2</option>_x000D_
<option>Item2</option>_x000D_
<option>Item2</option>_x000D_
<option class="disabled" disabled>Header3</option>_x000D_
<option>Item3</option>_x000D_
<option>Item3</option>_x000D_
<option>Item3</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_
PostgreSQL JOIN data from 3 tables
Something like:
select t1.name, t2.image_id, t3.path
from table1 t1 inner join table2 t2 on t1.person_id = t2.person_id
inner join table3 t3 on t2.image_id=t3.image_id
Java - Find shortest path between 2 points in a distance weighted map
Estimated sanjan:
The idea behind Dijkstra's Algorithm is to explore all the nodes of the graph in an ordered way. The algorithm stores a priority queue where the nodes are ordered according to the cost from the start, and in each iteration of the algorithm the following operations are performed:
- Extract from the queue the node with the lowest cost from the start, N
- Obtain its neighbors (N') and their associated cost, which is cost(N) + cost(N, N')
- Insert in queue the neighbor nodes N', with the priority given by their cost
It's true that the algorithm calculates the cost of the path between the start (A in your case) and all the rest of the nodes, but you can stop the exploration of the algorithm when it reaches the goal (Z in your example). At this point you know the cost between A and Z, and the path connecting them.
I recommend you to use a library which implements this algorithm instead of coding your own. In Java, you might take a look to the Hipster library, which has a very friendly way to generate the graph and start using the search algorithms.
Here you have an example of how to define the graph and start using Dijstra with Hipster.
// Create a simple weighted directed graph with Hipster where
// vertices are Strings and edge values are just doubles
HipsterDirectedGraph<String,Double> graph = GraphBuilder.create()
.connect("A").to("B").withEdge(4d)
.connect("A").to("C").withEdge(2d)
.connect("B").to("C").withEdge(5d)
.connect("B").to("D").withEdge(10d)
.connect("C").to("E").withEdge(3d)
.connect("D").to("F").withEdge(11d)
.connect("E").to("D").withEdge(4d)
.buildDirectedGraph();
// Create the search problem. For graph problems, just use
// the GraphSearchProblem util class to generate the problem with ease.
SearchProblem p = GraphSearchProblem
.startingFrom("A")
.in(graph)
.takeCostsFromEdges()
.build();
// Search the shortest path from "A" to "F"
System.out.println(Hipster.createDijkstra(p).search("F"));
You only have to substitute the definition of the graph for your own, and then instantiate the algorithm as in the example.
I hope this helps!
sed command with -i option failing on Mac, but works on Linux
Your Mac does indeed run a BASH shell, but this is more a question of which implementation of sed you are dealing with. On a Mac sed comes from BSD and is subtly different from the sed you might find on a typical Linux box. I suggest you man sed
.
Named parameters in JDBC
JDBC does not support named parameters. Unless you are bound to using plain JDBC (which causes pain, let me tell you that) I would suggest to use Springs Excellent JDBCTemplate which can be used without the whole IoC Container.
NamedParameterJDBCTemplate supports named parameters, you can use them like that:
NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
MapSqlParameterSource paramSource = new MapSqlParameterSource();
paramSource.addValue("name", name);
paramSource.addValue("city", city);
jdbcTemplate.queryForRowSet("SELECT * FROM customers WHERE name = :name AND city = :city", paramSource);
How to check if a Docker image with a specific tag exist locally?
for specific tag name
$ docker images --filter reference='<REPOSITORY>:TAG'
for "like clause" tagname:my_image_tag --> start my_ima*
$ docker images --filter reference='<REPOSITORY>:my_ima*'
if you want to someting "the image" for example delete all images tag started "my_ima" try this
docker rmi -f $(docker images -q --filter reference='myreponame:my_ima*')
jQuery: get parent tr for selected radio button
Try this.
You don't need to prefix attribute name by @
in jQuery selector. Use closest()
method to get the closest parent element matching the selector.
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
You can simplify your method like this
function getSelectedRowGuid() {
return GetRowGuid(
$("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}
closest()
- Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.
how to clear the screen in python
If you mean the screen where you have that interpreter prompt >>>
you can do CTRL+L on Bash shell can help. Windows does not have equivalent. You can do
import os
os.system('cls') # on windows
or
os.system('clear') # on linux / os x
Multiple rows to one comma-separated value in Sql Server
Test Data
DECLARE @Table1 TABLE(ID INT, Value INT)
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400)
Query
SELECT ID
,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
FROM @Table1
WHERE ID = t.ID
FOR XML PATH(''), TYPE)
.value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM @Table1 t
GROUP BY ID
Result Set
+--------------------------+
¦ ID ¦ List_Output ¦
¦----+---------------------¦
¦ 1 ¦ 100, 200, 300, 400 ¦
+--------------------------+
SQL Server 2017 and Later Versions
If you are working on SQL Server 2017 or later versions, you can use built-in SQL Server Function STRING_AGG to create the comma delimited list:
DECLARE @Table1 TABLE(ID INT, Value INT);
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400);
SELECT ID , STRING_AGG([Value], ', ') AS List_Output
FROM @Table1
GROUP BY ID;
Result Set
+--------------------------+
¦ ID ¦ List_Output ¦
¦----+---------------------¦
¦ 1 ¦ 100, 200, 300, 400 ¦
+--------------------------+
What does from __future__ import absolute_import actually do?
The changelog is sloppily worded. from __future__ import absolute_import
does not care about whether something is part of the standard library, and import string
will not always give you the standard-library module with absolute imports on.
from __future__ import absolute_import
means that if you import string
, Python will always look for a top-level string
module, rather than current_package.string
. However, it does not affect the logic Python uses to decide what file is the string
module. When you do
python pkg/script.py
pkg/script.py
doesn't look like part of a package to Python. Following the normal procedures, the pkg
directory is added to the path, and all .py
files in the pkg
directory look like top-level modules. import string
finds pkg/string.py
not because it's doing a relative import, but because pkg/string.py
appears to be the top-level module string
. The fact that this isn't the standard-library string
module doesn't come up.
To run the file as part of the pkg
package, you could do
python -m pkg.script
In this case, the pkg
directory will not be added to the path. However, the current directory will be added to the path.
You can also add some boilerplate to pkg/script.py
to make Python treat it as part of the pkg
package even when run as a file:
if __name__ == '__main__' and __package__ is None:
__package__ = 'pkg'
However, this won't affect sys.path
. You'll need some additional handling to remove the pkg
directory from the path, and if pkg
's parent directory isn't on the path, you'll need to stick that on the path too.
Delete all records in a table of MYSQL in phpMyAdmin
- Visit phpmyadmin
- Select your database and click on structure
- In front of your table, you can see Empty, click on it to clear all the entries from the selected table.
Or you can do the same using sql query:
Click on SQL present along side Structure
TRUNCATE tablename; //offers better performance, but used only when all entries need to be cleared
or
DELETE FROM tablename; //returns the number of rows deleted
Refer to DELETE and TRUNCATE for detailed documentaion
ValidateAntiForgeryToken purpose, explanation and example
In ASP.Net Core anti forgery token is automatically added to forms, so you don't need to add @Html.AntiForgeryToken()
if you use razor form element or if you use IHtmlHelper.BeginForm and if the form's method isn't GET.
It will generate input element for your form similar to this:
<input name="__RequestVerificationToken" type="hidden"
value="CfDJ8HSQ_cdnkvBPo-jales205VCq9ISkg9BilG0VXAiNm3Fl5Lyu_JGpQDA4_CLNvty28w43AL8zjeR86fNALdsR3queTfAogif9ut-Zd-fwo8SAYuT0wmZ5eZUYClvpLfYm4LLIVy6VllbD54UxJ8W6FA">
And when user submits form this token is verified on server side if validation is enabled.
[ValidateAntiForgeryToken]
attribute can be used against actions. Requests made to actions that have this filter applied are blocked unless the request includes a valid antiforgery token.
[AutoValidateAntiforgeryToken]
attribute can be used against controllers. This attribute works identically to the ValidateAntiForgeryToken attribute, except that it doesn't require tokens for requests made using the following HTTP methods:
GET HEAD OPTIONS TRACE
Additional information:
docs.microsoft.com/aspnet/core/security/anti-request-forgery
Reverse of JSON.stringify?
You need to JSON.parse()
the string.
_x000D_
_x000D_
var str = '{"hello":"world"}';
try {
var obj = JSON.parse(str); // this is how you parse a string into JSON
document.body.innerHTML += obj.hello;
} catch (ex) {
console.error(ex);
}
_x000D_
_x000D_
_x000D_
Regex to validate date format dd/mm/yyyy
For those who look at these and get completely confused, here is an excerpt from my script. Unfortunately, all it does is match valid numbers in a date time input, and 31st Feb will be marked as valid, but as so many have said, regex really isn't the best tool to do this test.
To match a date in the format 'yyyy-MM-dd hh:mm' (Or indeed in whatever order you please)
var dateerrors = false;
var yearReg = '(201[4-9]|202[0-9])'; ///< Allows a number between 2014 and 2029
var monthReg = '(0[1-9]|1[0-2])'; ///< Allows a number between 00 and 12
var dayReg = '(0[1-9]|1[0-9]|2[0-9]|3[0-1])'; ///< Allows a number between 00 and 31
var hourReg = '([0-1][0-9]|2[0-3])'; ///< Allows a number between 00 and 24
var minReg = '([0-5][0-9])'; ///< Allows a number between 00 and 59
var reg = new RegExp('^' + yearReg + '-' + monthReg + '-' + dayReg + ' ' + hourReg + ':' + minReg + '$', 'g');
$('input').filter(function () {return this.id.match(/myhtml_element_with_id_\d+_datetime/);}).each(function (e) {
if (e > 0) {
// Don't test the first input. This will use the default
var val = $(this).val();
if (val && !val.trim().match(reg)) {
dateerrors = true;
return false;
}
}
});
if (dateerrors) {
alert('You must enter a validate date in the format "yyyy-mm-dd HH:MM", e.g. 2019-12-31 19:30');
return false;
}
The above script starts off by building a regex object. It then finds all of the inputs whose id's match a certain pattern and then loops through these. I don't test the first input I find (if (e > 0)
).
A bit of explanation:
var reg = new RegExp('^' + yearReg + '-' + monthReg + '-' + dayReg + ' ' + hourReg + ':' + minReg + '$', 'g');
^
means start of match, whereas $
means end of match.
return this.id.match(/myhtml_element_with_id_\d+_datetime/);
\d+
means match a single or a contiguous sequence of integers, so myhtml_element_with_id_56_datetime
and myhtml_element_with_id_2_datetime
will match, but myhtml_element_with_id_5a_datetime
will not
How do I set default values for functions parameters in Matlab?
After becoming aware of ASSIGNIN (thanks to this answer by b3) and EVALIN I wrote two functions to finally obtain a very simple calling structure:
setParameterDefault('fTrue', inline('0'));
Here's the listing:
function setParameterDefault(pname, defval)
% setParameterDefault(pname, defval)
% Author: Tobias Kienzler (https://stackoverflow.com/users/321973)
% sets the parameter NAMED pname to the value defval if it is undefined or
% empty
if ~isParameterDefined('pname')
error('paramDef:noPname', 'No parameter name defined!');
elseif ~isvarname(pname)
error('paramDef:pnameNotChar', 'pname is not a valid varname!');
elseif ~isParameterDefined('defval')
error('paramDef:noDefval', ['No default value for ' pname ' defined!']);
end;
% isParameterNotDefined copy&pasted since evalin can't handle caller's
% caller...
if ~evalin('caller', ['exist(''' pname ''', ''var'') && ~isempty(' pname ')'])
callername = evalin('caller', 'mfilename');
warnMsg = ['Setting ' pname ' to default value'];
if isscalar(defval) || ischar(defval) || isvector(defval)
warnMsg = [warnMsg ' (' num2str(defval) ')'];
end;
warnMsg = [warnMsg '!'];
warning([callername ':paramDef:assigning'], warnMsg);
assignin('caller', pname, defval);
end
and
function b = isParameterDefined(pname)
% b = isParameterDefined(pname)
% Author: Tobias Kienzler (https://stackoverflow.com/users/321973)
% returns true if a parameter NAMED pname exists in the caller's workspace
% and if it is not empty
b = evalin('caller', ['exist(''' pname ''', ''var'') && ~isempty(' pname ')']) ;
How do I register a .NET DLL file in the GAC?
In case on windows 7 gacutil.exe (to put assembly in GAC) and sn.exe(To ensure uniqueness of assembly) resides at C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin
Then go to the path of gacutil as shown below execute the below command after replacing path of your assembly
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin>gacutil /i "replace with path of your assembly to be put into GAC"
Your password does not satisfy the current policy requirements
For MySql 8 you can use following script:
SET GLOBAL validate_password.LENGTH = 4;
SET GLOBAL validate_password.policy = 0;
SET GLOBAL validate_password.mixed_case_count = 0;
SET GLOBAL validate_password.number_count = 0;
SET GLOBAL validate_password.special_char_count = 0;
SET GLOBAL validate_password.check_user_name = 0;
ALTER USER 'user'@'localhost' IDENTIFIED BY 'pass';
FLUSH PRIVILEGES;
Regex for remove everything after | (with | )
In a .txt
file opened with Notepad++,
press Ctrl-F
go in the tab "Replace"
write the regex pattern \|.+
in the space Find what
and let the space Replace with blank
Then tick the choice matches newlines after the choice Regular expression
and press two times on the Replace button
Django - makemigrations - No changes detected
I know this is an old question but I fought with this same issue all day and my solution was a simple one.
I had my directory structure something along the lines of...
apps/
app/
__init__.py
app_sub1/
__init__.py
models.py
app_sub2/
__init__.py
models.py
app_sub3/
__init__.py
models.py
app2/
__init__.py
app2_sub1/
__init__.py
models.py
app2_sub2/
__init__.py
models.py
app2_sub3/
__init__.py
models.py
main_app/
__init__.py
models.py
And since all the other models up until the one I had a problem with were being imported somewhere else that ended up importing from main_app
which was registered in the INSTALLED_APPS
, I just got lucky that they all worked.
But since I only added each app
to INSTALLED_APPS
and not the app_sub*
when I finally added a new models file that wasn't imported ANYWHERE else, Django totally ignored it.
My fix was adding a models.py
file to the base directory of each app
like this...
apps/
app/
__init__.py
models.py <<<<<<<<<<--------------------------
app_sub1/
__init__.py
models.py
app_sub2/
__init__.py
models.py
app_sub3/
__init__.py
models.py
app2/
__init__.py
models.py <<<<<<<<<<--------------------------
app2_sub1/
__init__.py
models.py
app2_sub2/
__init__.py
models.py
app2_sub3/
__init__.py
models.py
main_app/
__init__.py
models.py
and then add from apps.app.app_sub1 import *
and so on to each of the app
level models.py
files.
Bleh... this took me SO long to figure out and I couldn't find the solution anywhere... I even went to page 2 of the google results.
Hope this helps someone!
Why doesn't the height of a container element increase if it contains floated elements?
You are encountering the float bug (though I'm not sure if it's technically a bug due to how many browsers exhibit this behaviour). Here is what is happening:
Under normal circumstances, assuming that no explicit height has been set, a block level element such as a div will set its height based on its content. The bottom of the parent div will extend beyond the last element. Unfortunately, floating an element stops the parent from taking the floated element into account when determining its height. This means that if your last element is floated, it will not "stretch" the parent in the same way a normal element would.
Clearing
There are two common ways to fix this. The first is to add a "clearing" element; that is, another element below the floated one that will force the parent to stretch. So add the following html as the last child:
<div style="clear:both"></div>
It shouldn't be visible, and by using clear:both, you make sure that it won't sit next to the floated element, but after it.
Overflow:
The second method, which is preferred by most people (I think) is to change the CSS of the parent element so that the overflow is anything but "visible". So setting the overflow to "hidden" will force the parent to stretch beyond the bottom of the floated child. This is only true if you haven't set a height on the parent, of course.
Like I said, the second method is preferred as it doesn't require you to go and add semantically meaningless elements to your markup, but there are times when you need the overflow
to be visible, in which case adding a clearing element is more than acceptable.
Hibernate show real SQL
select this_.code from true.employee this_ where this_.code=?
is what will be sent to your database.
this_
is an alias for that instance of the employee
table.
Use dynamic variable names in JavaScript
2019
TL;DR
eval
operator can run string expression in the context it called and return variables from that context;
literal object
theoretically can do that by write:{[varName]}
, but it blocked by definition.
So I come across this question and everyone here just play around without bringing a real solution. but @Axel Heider has a good approaching.
The solution is eval
.
almost most forgotten operator. ( think most one is with()
)
eval
operator can dynamically run expression in the context it called. and return the result of that expression. we can use that to dynamically return a variable's value in function's context.
example:
function exmaple1(){
var a = 1, b = 2, default = 3;
var name = 'a';
return eval(name)
}
example1() // return 1
function example2(option){
var a = 1, b = 2, defaultValue = 3;
switch(option){
case 'a': name = 'a'; break;
case 'b': name = 'b'; break;
default: name = 'defaultValue';
}
return eval (name);
}
example2('a') // return 1
example2('b') // return 2
example2() // return 3
Note that I always write explicitly the expression eval
will run.
To avoid unnecessary surprises in the code. eval
is very strong
But I'm sure you know that already
BTW, if it was legal we could use literal object
to capture the variable name and value, but we can’t combine computed property names and property value shorthand, sadly, is invalid
functopn example( varName ){
var var1 = 'foo', var2 ='bar'
var capture = {[varName]}
}
example('var1') //trow 'Uncaught SyntaxError: Unexpected token }`
'import' and 'export' may only appear at the top level
I got this error after upgrading to webpack 4.29.x. It turned out that webpack 4.29.x triggered npm's peerDependency bug. And according to them, the bug is not going to get fixed soon. Here's the workaround from sokra
- add
"acorn": "^6.0.5"
to your application package.json.
- Switch to
yarn
. It doesn't have this bug.
npm update acorn --depth 20
npm dedupe
(works only in some cases)
rm package-lock.json
npm i
(works only in some cases)
- update all other packages that depend on an older version for acorn (works only in some cases)
- lock webpack at
4.28.4
in your package.json
Update
According to comment below, this bug doesn't exist anymore after 4.36.0
seek() function?
Regarding seek()
there's not too much to worry about.
First of all, it is useful when operating over an open file.
It's important to note that its syntax is as follows:
fp.seek(offset, from_what)
where fp
is the file pointer you're working with; offset
means how many positions you will move; from_what
defines your point of reference:
- 0: means your reference point is the beginning of the file
- 1: means your reference point is the current file position
- 2: means your reference point is the end of the file
if omitted, from_what
defaults to 0.
Never forget that when managing files, there'll always be a position inside that file where you are currently working on. When just open, that position is the beginning of the file, but as you work with it, you may advance.
seek
will be useful to you when you need to walk
along that open file, just as a path you are traveling into.
How can I link to a specific glibc version?
In my opinion, the laziest solution (especially if you don't rely on latest bleeding edge C/C++ features, or latest compiler features) wasn't mentioned yet, so here it is:
Just build on the system with the oldest GLIBC you still want to support.
This is actually pretty easy to do nowadays with technologies like chroot, or KVM/Virtualbox, or docker, even if you don't really want to use such an old distro directly on any pc. In detail, to make a maximum portable binary of your software I recommend following these steps:
Just pick your poison of sandbox/virtualization/... whatever, and use it to get yourself a virtual older Ubuntu LTS and compile with the gcc/g++ it has in there by default. That automatically limits your GLIBC to the one available in that environment.
Avoid depending on external libs outside of foundational ones: like, you should dynamically link ground-level system stuff like glibc, libGL, libxcb/X11/wayland things, libasound/libpulseaudio, possibly GTK+ if you use that, but otherwise preferrably statically link external libs/ship them along if you can. Especially mostly self-contained libs like image loaders, multimedia decoders, etc can cause less breakage on other distros (breakage can be caused e.g. if only present somewhere in a different major version) if you statically ship them.
With that approach you get an old-GLIBC-compatible binary without any manual symbol tweaks, without doing a fully static binary (that may break for more complex programs because glibc hates that, and which may cause licensing issues for you), and without setting up any custom toolchain, any custom glibc copy, or whatever.
OpenCV with Network Cameras
#include <stdio.h>
#include "opencv.hpp"
int main(){
CvCapture *camera=cvCaptureFromFile("http://username:pass@cam_address/axis-cgi/mjpg/video.cgi?resolution=640x480&req_fps=30&.mjpg");
if (camera==NULL)
printf("camera is null\n");
else
printf("camera is not null");
cvNamedWindow("img");
while (cvWaitKey(10)!=atoi("q")){
double t1=(double)cvGetTickCount();
IplImage *img=cvQueryFrame(camera);
double t2=(double)cvGetTickCount();
printf("time: %gms fps: %.2g\n",(t2-t1)/(cvGetTickFrequency()*1000.), 1000./((t2-t1)/(cvGetTickFrequency()*1000.)));
cvShowImage("img",img);
}
cvReleaseCapture(&camera);
}
If REST applications are supposed to be stateless, how do you manage sessions?
When you develop a RESTful service, in order to be logged in you will need your user to be authenticated. A possible option would be to send the username and password each time you intend to do a user action. In this case the server will not store session-data at all.
Another option is to generate a session-id on the server and send it to the client, so the client will be able to send session-id to the server and authenticate with that. This is much much safer than sending username and password each time, since if somebody gets their hand on that data, then he/she can impersonate the user until the username and password is changed. You may say that even the session id can be stolen and the user will be impersonated in that case and you are right. However, in this case impersonating the user will only be possible while the session id is valid.
If the RESTful API expects username and password in order to change username and password, then even if somebody impersonated the user using the session id, the hacker will not be able to lock out the real user.
A session-id could be generated by one-way-locking (encryption) of something which identifies the user and adding the time to the session id, this way the session's expiry time could be defined.
The server may or may not store session ids. Of course, if the server stores the session id, then it would violate the criteria defined in the question. However, it is only important to make sure that the session id can be validated for the given user, which does not necessitate storing the session id. Imagine a way that you have a one-way-encryption of email, user id and some user-specific private data, like favorite color, this would be the first level and somehow adding the username date to the encrypted string and apply a two-way encryption. As a result when a session id is received, the second level could be decrypted to be able to determine which username the user claims to be and whether the session time is right. If this is valid, then the first level of encryption could be validated by doing that encryption again and checking whether it matches the string. You do not need to store session data in order to achieve that.
The network path was not found
You will also get this exact error if attempting to access your remote/prod db from localhost and you've forgotten that this particular hosting company requires VPN logon in order to access the db (do i feel silly).
What are rvalues, lvalues, xvalues, glvalues, and prvalues?
I guess this document might serve as a not so short introduction : n3055
The whole massacre began with the move semantics. Once we have expressions that can be moved and not copied, suddenly easy to grasp rules demanded distinction between expressions that can be moved, and in which direction.
From what I guess based on the draft, the r/l value distinction stays the same, only in the context of moving things get messy.
Are they needed? Probably not if we wish to forfeit the new features. But to allow better optimization we should probably embrace them.
Quoting n3055:
- An lvalue (so-called, historically,
because lvalues could appear on the
left-hand side of an assignment
expression) designates a function or
an object. [Example: If
E
is an
expression of pointer type, then *E
is an lvalue expression referring to
the object or function to which E
points. As another example, the
result of calling a function whose
return type is an lvalue reference is
an lvalue.]
- An xvalue (an
“eXpiring” value) also refers to an
object, usually near the end of its
lifetime (so that its resources may
be moved, for example). An xvalue is
the result of certain kinds of
expressions involving rvalue
references. [Example: The
result of calling a function whose
return type is an rvalue reference is
an xvalue.]
- A glvalue (“generalized” lvalue) is an lvalue
or an xvalue.
- An rvalue (so-called,
historically, because rvalues could
appear on the right-hand side of an
assignment expression) is an xvalue,
a temporary object or
subobject thereof, or a value that is
not associated with an object.
- A
prvalue (“pure” rvalue) is an rvalue
that is not an xvalue. [Example: The
result of calling a function whose
return type is not a reference is a
prvalue]
The document in question is a great reference for this question, because it shows the exact changes in the standard that have happened as a result of the introduction of the new nomenclature.
REST API - file (ie images) processing - best practices
OP here (I am answering this question after two years, the post made by Daniel Cerecedo was not bad at a time, but the web services are developing very fast)
After three years of full-time software development (with focus also on software architecture, project management and microservice architecture) I definitely choose the second way (but with one general endpoint) as the best one.
If you have a special endpoint for images, it gives you much more power over handling those images.
We have the same REST API (Node.js) for both - mobile apps (iOS/android) and frontend (using React). This is 2017, therefore you don't want to store images locally, you want to upload them to some cloud storage (Google cloud, s3, cloudinary, ...), therefore you want some general handling over them.
Our typical flow is, that as soon as you select an image, it starts uploading on background (usually POST on /images endpoint), returning you the ID after uploading. This is really user-friendly, because user choose an image and then typically proceed with some other fields (i.e. address, name, ...), therefore when he hits "send" button, the image is usually already uploaded. He does not wait and watching the screen saying "uploading...".
The same goes for getting images. Especially thanks to mobile phones and limited mobile data, you don't want to send original images, you want to send resized images, so they do not take that much bandwidth (and to make your mobile apps faster, you often don't want to resize it at all, you want the image that fits perfectly into your view). For this reason, good apps are using something like cloudinary (or we do have our own image server for resizing).
Also, if the data are not private, then you send back to app/frontend just URL and it downloads it from cloud storage directly, which is huge saving of bandwidth and processing time for your server. In our bigger apps there are a lot of terabytes downloaded every month, you don't want to handle that directly on each of your REST API server, which is focused on CRUD operation. You want to handle that at one place (our Imageserver, which have caching etc.) or let cloud services handle all of it.
Cons : The only "cons" which you should think of is "not assigned images". User select images and continue with filling other fields, but then he says "nah" and turn off the app or tab, but meanwhile you successfully uploaded the image. This means you have uploaded an image which is not assigned anywhere.
There are several ways of handling this. The most easiest one is "I don't care", which is a relevant one, if this is not happening very often or you even have desire to store every image user send you (for any reason) and you don't want any deletion.
Another one is easy too - you have CRON and i.e. every week and you delete all unassigned images older than one week.
What are static factory methods?
One of the advantages that stems from Static factory is that that API can return objects without making their classes public. This lead to very compact API. In java this is achieved by Collections class which hides around 32 classes which makes it collection API very compact.
How to represent multiple conditions in a shell if statement?
Classic technique (escape metacharacters):
if [ \( "$g" -eq 1 -a "$c" = "123" \) -o \( "$g" -eq 2 -a "$c" = "456" \) ]
then echo abc
else echo efg
fi
I've enclosed the references to $g
in double quotes; that's good practice, in general. Strictly, the parentheses aren't needed because the precedence of -a
and -o
makes it correct even without them.
Note that the -a
and -o
operators are part of the POSIX specification for test
, aka [
, mainly for backwards compatibility (since they were a part of test
in 7th Edition UNIX, for example), but they are explicitly marked as 'obsolescent' by POSIX. Bash (see conditional expressions) seems to preempt the classic and POSIX meanings for -a
and -o
with its own alternative operators that take arguments.
With some care, you can use the more modern [[
operator, but be aware that the versions in Bash and Korn Shell (for example) need not be identical.
for g in 1 2 3
do
for c in 123 456 789
do
if [[ ( "$g" -eq 1 && "$c" = "123" ) || ( "$g" -eq 2 && "$c" = "456" ) ]]
then echo "g = $g; c = $c; true"
else echo "g = $g; c = $c; false"
fi
done
done
Example run, using Bash 3.2.57 on Mac OS X:
g = 1; c = 123; true
g = 1; c = 456; false
g = 1; c = 789; false
g = 2; c = 123; false
g = 2; c = 456; true
g = 2; c = 789; false
g = 3; c = 123; false
g = 3; c = 456; false
g = 3; c = 789; false
You don't need to quote the variables in [[
as you do with [
because it is not a separate command in the same way that [
is.
Isn't it a classic question?
I would have thought so. However, there is another alternative, namely:
if [ "$g" -eq 1 -a "$c" = "123" ] || [ "$g" -eq 2 -a "$c" = "456" ]
then echo abc
else echo efg
fi
Indeed, if you read the 'portable shell' guidelines for the autoconf
tool or related packages, this notation — using '||
' and '&&
' — is what they recommend. I suppose you could even go so far as:
if [ "$g" -eq 1 ] && [ "$c" = "123" ]
then echo abc
elif [ "$g" -eq 2 ] && [ "$c" = "456" ]
then echo abc
else echo efg
fi
Where the actions are as trivial as echoing, this isn't bad. When the action block to be repeated is multiple lines, the repetition is too painful and one of the earlier versions is preferable — or you need to wrap the actions into a function that is invoked in the different then
blocks.
Calendar Recurring/Repeating Events - Best Storage Method
I developed an esoteric programming language just for this case. The best part about it is that it is schema less and platform independent. You just have to write a selector program, for your schedule, syntax of which is constrained by the set of rules described here -
https://github.com/tusharmath/sheql/wiki/Rules
The rules are extendible and you can add any sort of customization based on the kind of repetition logic you want to perform, without worrying about schema migrations etc.
This is a completely different approach and might have some disadvantages of its own.
Add a fragment to the URL without causing a redirect?
Try this
var URL = "scratch.mit.edu/projects";
var mainURL = window.location.pathname;
if (mainURL == URL) {
mainURL += ( mainURL.match( /[\?]/g ) ? '&' : '#' ) + '_bypasssharerestrictions_';
console.log(mainURL)
}
Exploring Docker container's file system
If you are using the AUFS storage driver, you can use my docker-layer script to find any container's filesystem root (mnt) and readwrite layer :
# docker-layer musing_wiles
rw layer : /var/lib/docker/aufs/diff/c83338693ff190945b2374dea210974b7213bc0916163cc30e16f6ccf1e4b03f
mnt : /var/lib/docker/aufs/mnt/c83338693ff190945b2374dea210974b7213bc0916163cc30e16f6ccf1e4b03f
Edit 2018-03-28 :
docker-layer has been replaced by docker-backup
Binding a Button's visibility to a bool value in ViewModel
In View:
<Button
Height="50" Width="50"
Style="{StaticResource MyButtonStyle}"
Command="{Binding SmallDisp}" CommandParameter="{Binding}"
Cursor="Hand" Visibility="{Binding Path=AdvancedFormat}"/>
In view Model:
public _advancedFormat = Visibility.visible (whatever you start with)
public Visibility AdvancedFormat
{
get{return _advancedFormat;}
set{
_advancedFormat = value;
//raise property changed here
}
You will need to have a property changed event
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
PropertyChanged.Raise(this, e);
}
protected void OnPropertyChanged(string propertyName)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
This is how they use Model-view-viewmodel
But since you want it binded to a boolean, You will need some converter.
Another way is to set a boolean outside and when that button is clicked then set the property_advancedFormat to your desired visibility.
Numpy AttributeError: 'float' object has no attribute 'exp'
Probably there's something wrong with the input values for X and/or T. The function from the question works ok:
import numpy as np
from math import e
def sigmoid(X, T):
return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))
X = np.array([[1, 2, 3], [5, 0, 0]])
T = np.array([[1, 2], [1, 1], [4, 4]])
print(X.dot(T))
# Just to see if values are ok
print([1. / (1. + e ** el) for el in [-5, -10, -15, -16]])
print()
print(sigmoid(X, T))
Result:
[[15 16]
[ 5 10]]
[0.9933071490757153, 0.9999546021312976, 0.999999694097773, 0.9999998874648379]
[[ 0.99999969 0.99999989]
[ 0.99330715 0.9999546 ]]
Probably it's the dtype of your input arrays. Changing X to:
X = np.array([[1, 2, 3], [5, 0, 0]], dtype=object)
Gives:
Traceback (most recent call last):
File "/[...]/stackoverflow_sigmoid.py", line 24, in <module>
print sigmoid(X, T)
File "/[...]/stackoverflow_sigmoid.py", line 14, in sigmoid
return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))
AttributeError: exp
Create SQL identity as primary key?
This is similar to the scripts we generate on our team. Create the table first, then apply pk/fk and other constraints.
CREATE TABLE [dbo].[ImagenesUsuario] (
[idImagen] [int] IDENTITY (1, 1) NOT NULL
)
ALTER TABLE [dbo].[ImagenesUsuario] ADD
CONSTRAINT [PK_ImagenesUsuario] PRIMARY KEY CLUSTERED
(
[idImagen]
) ON [PRIMARY]
Is there an "exists" function for jQuery?
There is an oddity known as short circuit conditioning. Not many are making this feature known so allow me to explain! <3
//you can check if it isnt defined or if its falsy by using OR
console.log( $(selector) || 'this value doesnt exist' )
//or run the selector if its true, and ONLY true
console.log( $(selector) && 'this selector is defined, now lemme do somethin!' )
//sometimes I do the following, and see how similar it is to SWITCH
console.log(
({ //return something only if its in the method name
'string':'THIS is a string',
'function':'THIS is a function',
'number':'THIS is a number',
'boolean':'THIS is a boolean'
})[typeof $(selector)]||
//skips to this value if object above is undefined
'typeof THIS is not defined in your search')
The last bit allows me to see what kind of input my typeof has, and runs in that list. If there is a value outside of my list, I use the OR (||)
operator to skip and nullify. This has the same performance as a Switch Case
and is considered somewhat concise. Test Performance of the conditionals and uses of logical operators.
Side note: The Object-Function kinda has to be rewritten >.<' But this test I built was made to look into concise and expressive conditioning.
Resources:
Logical AND (with short circuit evaluation)
How to use z-index in svg elements?
The clean, fast, and easy solutions posted as of the date of this answer are unsatisfactory. They are constructed over the flawed statement that SVG documents lack z order. Libraries are not necessary either. One line of code can perform most operations to manipulate the z order of objects or groups of objects that might be required in the development of an app that moves 2D objects around in an x-y-z space.
Z Order Definitely Exists in SVG Document Fragments
What is called an SVG document fragment is a tree of elements derived from the base node type SVGElement. The root node of an SVG document fragment is an SVGSVGElement, which corresponds to an HTML5 <svg> tag. The SVGGElement corresponds to the <g> tag and permits aggregating children.
Having a z-index attribute on the SVGElement as in CSS would defeat the SVG rendering model. Sections 3.3 and 3.4 of W3C SVG Recommendation v1.1 2nd Edition state that SVG document fragments (trees of offspring from an SVGSVGElement) are rendered using what is called a depth first search of the tree. That scheme is a z order in every sense of the term.
Z order is actually a computer vision shortcut to avoid the need for true 3D rendering with the complexities and computing demands of ray tracing. The linear equation for the implicit z-index of elements in an SVG document fragment.
z-index = z-index_of_svg_tag + depth_first_tree_index / tree_node_qty
This is important because if you want to move a circle that was below a square to above it, you simply insert the square before the circle. This can be done easily in JavaScript.
Supporting Methods
SVGElement instances have two methods that support simple and easy z order manipulation.
- parent.removeChild(child)
- parent.insertBefore(child, childRef)
The Correct Answer That Doesn't Create a Mess
Because the SVGGElement (<g> tag) can be removed and inserted just as easily as a SVGCircleElement or any other shape, image layers typical of Adobe products and other graphics tools can be implemented with ease using the SVGGElement. This JavaScript is essentially a Move Below command.
parent.insertBefore(parent.removeChild(gRobot), gDoorway)
If the layer of a robot drawn as children of SVGGElement gRobot was before the doorway drawn as children of SVGGElement gDoorway, the robot is now behind the doorway because the z order of the doorway is now one plus the z order of the robot.
A Move Above command is almost as easy.
parent.insertBefore(parent.removeChild(gRobot), gDoorway.nextSibling())
Just think a=a and b=b to remember this.
insert after = move above
insert before = move below
Leaving the DOM in a State Consistent With the View
The reason this answer is correct is because it is minimal and complete and, like the internals of Adobe products or other well designed graphics editors, leaves the internal representation in a state that is consistent with the view created by rendering.
Alternative But Limited Approach
Another approach commonly used is to use CSS z-index in conjunction with multiple SVG document fragments (SVG tags) with mostly transparent backgrounds in all but the bottom one. Again, this defeats the elegance of the SVG rendering model, making it difficult to move objects up or down in the z order.
NOTES:
- (https://www.w3.org/TR/SVG/render.html v 1.1, 2nd Edition, 16 August 2011)
3.3 Rendering Order Elements in an SVG document fragment have an implicit drawing order, with the first elements in the SVG document
fragment getting "painted" first. Subsequent elements are painted on
top of previously painted elements.
3.4 How groups are rendered Grouping elements such as the ‘g’ element (see container elements) have the effect of producing a temporary
separate canvas initialized to transparent black onto which child
elements are painted. Upon the completion of the group, any filter
effects specified for the group are applied to create a modified
temporary canvas. The modified temporary canvas is composited into the
background, taking into account any group-level masking and opacity
settings on the group.
Iterating over ResultSet and adding its value in an ArrayList
If I've understood your problem correctly, there are two possible problems here:
resultset
is null
- I assume that this can't be the case as if it was you'd get an exception in your while loop and nothing would be output.
- The second problem is that
resultset.getString(i++)
will get columns 1,2,3 and so on from each subsequent row.
I think that the second point is probably your problem here.
Lets say you only had 1 row returned, as follows:
Col 1, Col 2, Col 3
A , B, C
Your code as it stands would only get A - it wouldn't get the rest of the columns.
I suggest you change your code as follows:
ResultSet resultset = ...;
ArrayList<String> arrayList = new ArrayList<String>();
while (resultset.next()) {
int i = 1;
while(i <= numberOfColumns) {
arrayList.add(resultset.getString(i++));
}
System.out.println(resultset.getString("Col 1"));
System.out.println(resultset.getString("Col 2"));
System.out.println(resultset.getString("Col 3"));
System.out.println(resultset.getString("Col n"));
}
Edit:
To get the number of columns:
ResultSetMetaData metadata = resultset.getMetaData();
int numberOfColumns = metadata.getColumnCount();
How to make program go back to the top of the code instead of closing
Use an infinite loop:
while True:
print('Hello world!')
This certainly can apply to your start()
function as well; you can exit the loop with either break
, or use return
to exit the function altogether, which also terminates the loop:
def start():
print ("Welcome to the converter toolkit made by Alan.")
while True:
op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")
if op == "1":
f1 = input ("Please enter your fahrenheit temperature: ")
f1 = int(f1)
a1 = (f1 - 32) / 1.8
a1 = str(a1)
print (a1+" celsius")
elif op == "2":
m1 = input ("Please input your the amount of meters you wish to convert: ")
m1 = int(m1)
m2 = (m1 * 100)
m2 = str(m2)
print (m2+" m")
if op == "3":
mb1 = input ("Please input the amount of megabytes you want to convert")
mb1 = int(mb1)
mb2 = (mb1 / 1024)
mb3 = (mb2 / 1024)
mb3 = str(mb3)
print (mb3+" GB")
else:
print ("Sorry, that was an invalid command!")
If you were to add an option to quit as well, that could be:
if op.lower() in {'q', 'quit', 'e', 'exit'}:
print("Goodbye!")
return
for example.
What Does 'zoom' do in CSS?
As Joshua M pointed out, the zoom function isn't supported only in Firefox, but you can simply fix this as shown:
div.zoom {
zoom: 2; /* all browsers */
-moz-transform: scale(2); /* Firefox */
}
Failed to start mongod.service: Unit mongod.service not found
Well.... My answer may be considered naive but in fact it has been the only way MongoDB has work in my case, Ubuntu 19.10. I tried to run the commands from the most voted comments and none worked, when running:
mongod --repair
I got this alert:
With some research I found out that running the DB in another port could be a solution, then:
mongod --port 27018
And it works great for me every time. Long answer but wanted to give context before giving such a simple solution.
(If I'm doing it wrong or doesn't seem logical, plz tell me! Relevant for me)
What is an attribute in Java?
A class is an element in object oriented programming that aggregates attributes(fields) - which can be public accessible or not - and methods(functions) - which also can be public or private and usually writes/reads those attributes.
so you can have a class like Array
with a public attribute length
and a public method sort()
.
How do I obtain a list of all schemas in a Sql Server database
Try this query here:
SELECT * FROM sys.schemas
This will give you the name and schema_id for all defines schemas in the database you execute this in.
I don't really know what you mean by querying the "schema API" - these sys.
catalog views (in the sys
schema) are your best bet for any system information about databases and objects in those databases.
Get the last element of a std::string
*(myString.end() - 1)
maybe? That's not exactly elegant either.
A python-esque myString.at(-1)
would be asking too much of an already-bloated class.
How do I convert array of Objects into one Object in JavaScript?
A clean way to do this using modern JavaScript is as follows:
const array = [
{ name: "something", value: "something" },
{ name: "somethingElse", value: "something else" },
];
const newObject = Object.assign({}, ...array.map(item => ({ [item.name]: item.value })));
// >> { something: "something", somethingElse: "something else" }
Byte[] to ASCII
Encoding.GetString Method (Byte[]) convert bytes to a string.
When overridden in a derived class, decodes all the bytes in the specified byte array into a string.
Namespace: System.Text
Assembly: mscorlib (in mscorlib.dll)
Syntax
public virtual string GetString(byte[] bytes)
Parameters
bytes
Type: System.Byte[]
The byte array containing the sequence of bytes to decode.
Return Value
Type: System.String
A String containing the results of decoding the specified sequence of bytes.
Exceptions
ArgumentException - The byte array contains invalid Unicode code points.
ArgumentNullException - bytes is null.
DecoderFallbackException - A fallback occurred (see Character Encoding in the .NET Framework for complete explanation) or DecoderFallback is set to DecoderExceptionFallback.
Remarks
If the data to be converted is
available only in sequential blocks
(such as data read from a stream) or
if the amount of data is so large that
it needs to be divided into smaller
blocks, the application should use the
Decoder or the Encoder provided by the
GetDecoder method or the GetEncoder
method, respectively, of a derived
class.
See the Remarks under
Encoding.GetChars for more discussion
of decoding techniques and
considerations.
Converting a String to a List of Words?
Try this:
import re
mystr = 'This is a string, with words!'
wordList = re.sub("[^\w]", " ", mystr).split()
How it works:
From the docs :
re.sub(pattern, repl, string, count=0, flags=0)
Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function.
so in our case :
pattern is any non-alphanumeric character.
[\w] means any alphanumeric character and is equal to the character set
[a-zA-Z0-9_]
a to z, A to Z , 0 to 9 and underscore.
so we match any non-alphanumeric character and replace it with a space .
and then we split() it which splits string by space and converts it to a list
so 'hello-world'
becomes 'hello world'
with re.sub
and then ['hello' , 'world']
after split()
let me know if any doubts come up.
Is it possible to send an array with the Postman Chrome extension?
You need to suffix your variable name with []
like this:
If that doesn't work, try not putting indexes in brackets:
my_array[] value1
my_array[] value2
Note:
If you are using the postman packaged app, you can send an array by selecting raw
/ json
(instead of form-data
). Also, make sure to set Content-Type
as application/json
in Headers
tab.
Here is example for raw data {"user_ids": ["123" "233"]}
, don't forget the quotes!
If you are using the postman REST client you have to use the method I described above because passing data as raw (json) won't work. There is a bug in the postman REST client (At least I get the bug when I use 0.8.4.6
).
add commas to a number in jQuery
Another way to do it:
function addCommas(n){
var s = "",
r;
while (n) {
r = n % 1000;
s = r + s;
n = (n - r)/1000;
s = (n ? "," : "") + s;
}
return s;
}
alert(addCommas(12345678));
Is ini_set('max_execution_time', 0) a bad idea?
Reason is to have some value other than zero.
General practice to have it short globally and long for long working scripts like parsers, crawlers, dumpers, exporting & importing scripts etc.
- You can halt server, corrupt work of other people by memory
consuming script without even knowing it.
- You will not be seeing mistakes
where something, let's say, infinite loop happened, and it will be harder to diagnose.
- Such site may be easily DoSed by single user, when requesting pages with long execution time
SQL conditional SELECT
You want the CASE
statement:
SELECT
CASE
WHEN @SelectField1 = 1 THEN Field1
WHEN @SelectField2 = 1 THEN Field2
ELSE NULL
END AS NewField
FROM Table
EDIT: My example is for combining the two fields into one field, depending on the parameters supplied. It is a one-or-neither solution (not both). If you want the possibility of having both fields in the output, use Quassnoi's solution.
How to make modal dialog in WPF?
Given a Window object myWindow, myWindow.Show() will open it modelessly and myWindow.ShowDialog() will open it modally. However, even the latter doesn't block, from what I remember.
What is the difference between ports 465 and 587?
Port 465:
IANA has reassigned a new service to this port, and it should no longer be used for SMTP communications.
However, because it was once recognized by IANA as valid, there may be legacy systems that are only capable of using this connection method. Typically, you will use this port only if your application demands it. A quick Google search, and you'll find many consumer ISP articles that suggest port 465 as the recommended setup. Hopefully this ends soon! It is not RFC compliant.
Port 587:
This is the default mail submission port. When a mail client or server is submitting an email to be routed by a proper mail server, it should always use this port.
Everyone should consider using this port as default, unless you're explicitly blocked by your upstream network or hosting provider. This port, coupled with TLS encryption, will ensure that email is submitted securely and following the guidelines set out by the IETF.
Port 25:
This port continues to be used primarily for SMTP relaying. SMTP relaying is the transmittal of email from email server to email server.
In most cases, modern SMTP clients (Outlook, Mail, Thunderbird, etc) shouldn't use this port. It is traditionally blocked, by residential ISPs and Cloud Hosting Providers, to curb the amount of spam that is relayed from compromised computers or servers. Unless you're specifically managing a mail server, you should have no traffic traversing this port on your computer or server.
Trying to fire the onload event on script tag
You should set the src
attribute after the onload
event, f.ex:
el.onload = function() { //...
el.src = script;
You should also append the script to the DOM before attaching the onload
event:
$body.append(el);
el.onload = function() { //...
el.src = script;
Remember that you need to check readystate
for IE support. If you are using jQuery, you can also try the getScript()
method: http://api.jquery.com/jQuery.getScript/
How to save a bitmap on internal storage
To Save your bitmap in sdcard use the following code
Store Image
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
To Get the Path for Image Storage
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
EDIT
From Your comments i have edited the onclick view in this the button1 and button2 functions will be executed separately.
public onClick(View v){
switch(v.getId()){
case R.id.button1:
//Your button 1 function
break;
case R.id. button2:
//Your button 2 function
break;
}
}
How can I set selected option selected in vue.js 2?
Handling the errors
You are binding properties to nothing. :required
in
<select class="form-control" v-model="selected" :required @change="changeLocation">
and :selected
in
<option :selected>Choose Province</option>
If you set the code like so, your errors should be gone:
<template>
<select class="form-control" v-model="selected" :required @change="changeLocation">
<option>Choose Province</option>
<option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
</select>
</template>
Getting the select tags to have a default value
you would now need to have a data
property called selected
so that v-model works. So,
{
data () {
return {
selected: "Choose Province"
}
}
}
If that seems like too much work, you can also do it like:
<template>
<select class="form-control" :required="true" @change="changeLocation">
<option :selected="true">Choose Province</option>
<option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
</select>
</template>
When to use which method?
You can use the v-model
approach if your default value depends on some data property.
You can go for the second method if your default selected value happens to be the first option
.
You can also handle it programmatically by doing so:
<select class="form-control" :required="true">
<option
v-for="option in options"
v-bind:value="option.id"
:selected="option == '<the default value you want>'"
>{{ option }}</option>
</select>
bootstrap 4 file input doesn't show the file name
When you have multiple files, an idea is to show only the first file and the number of the hidden file names.
$('.custom-file input').change(function() {
var $el = $(this),
files = $el[0].files,
label = files[0].name;
if (files.length > 1) {
label = label + " and " + String(files.length - 1) + " more files"
}
$el.next('.custom-file-label').html(label);
});
How to redirect to Login page when Session is expired in Java web application?
When the use logs in, put its username in the session:
`session.setAttribute("USER", username);`
At the beginning of each page you can do this:
<%
String username = (String)session.getAttribute("USER");
if(username==null)
// if session is expired, forward it to login page
%>
<jsp:forward page="Login.jsp" />
<% { } %>
Use Excel pivot table as data source for another Pivot Table
In a new sheet (where you want to create a new pivot table) press the key combination (Alt+D+P). In the list of data source options choose "Microsoft Excel list of database". Click Next and select the pivot table that you want to use as a source (select starting with the actual headers of the fields). I assume that this range is rather static and if you refresh the source pivot and it changes it's size you would have to re-size the range as well. Hope this helps.
How do I align views at the bottom of the screen?
Use the below code. Align the button to buttom. It's working.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btn_back"
android:layout_width="100dp"
android:layout_height="80dp"
android:text="Back" />
<TextView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.97"
android:gravity="center"
android:text="Payment Page" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"/>
</LinearLayout>
</LinearLayout>
how to access iFrame parent page using jquery?
in parent window put :
<script>
function ifDoneChildFrame(val)
{
$('#parentPrice').html(val);
}
</script>
and in iframe src file put :
<script>window.parent.ifDoneChildFrame('Your value here');</script>
How to download image using requests
Here is a more user-friendly answer that still uses streaming.
Just define these functions and call getImage()
. It will use the same file name as the url and write to the current directory by default, but both can be changed.
import requests
from StringIO import StringIO
from PIL import Image
def createFilename(url, name, folder):
dotSplit = url.split('.')
if name == None:
# use the same as the url
slashSplit = dotSplit[-2].split('/')
name = slashSplit[-1]
ext = dotSplit[-1]
file = '{}{}.{}'.format(folder, name, ext)
return file
def getImage(url, name=None, folder='./'):
file = createFilename(url, name, folder)
with open(file, 'wb') as f:
r = requests.get(url, stream=True)
for block in r.iter_content(1024):
if not block:
break
f.write(block)
def getImageFast(url, name=None, folder='./'):
file = createFilename(url, name, folder)
r = requests.get(url)
i = Image.open(StringIO(r.content))
i.save(file)
if __name__ == '__main__':
# Uses Less Memory
getImage('http://www.example.com/image.jpg')
# Faster
getImageFast('http://www.example.com/image.jpg')
The request
guts of getImage()
are based on the answer here and the guts of getImageFast()
are based on the answer above.
Redirect From Action Filter Attribute
This works for me (asp.net core 2.1)
using JustRide.Web.Controllers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace MyProject.Web.Filters
{
public class IsAuthenticatedAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (context.HttpContext.User.Identity.IsAuthenticated)
context.Result = new RedirectToActionResult(nameof(AccountController.Index), "Account", null);
}
}
}
[AllowAnonymous, IsAuthenticated]
public IActionResult Index()
{
return View();
}
Where can I get a virtual machine online?
koding.com has a free VM running Ubuntu. The specs are pretty good, 1 gig memory for example. They have a terminal online you can access through their website, or use SSH. The VM will go to sleep approximately 20 minutes after you log out. The reason is to discourage users from running live production code on the VM. The VM resides behind a proxy. Running web servers that only speak HTTP (port 80) should work just fine, but I think you'll get into a lot of trouble whenever you want to work directly with other ports. Many mind-like alternatives offer similar setups. Good luck!
I had the same idea as you but given all restrictions everybody keep imposing everywhere I feel that I must go out and pay for a VPS.
Use images instead of radio buttons
Here is very simple example
_x000D_
_x000D_
input[type="radio"]{_x000D_
display:none;_x000D_
}_x000D_
_x000D_
input[type="radio"] + label_x000D_
{_x000D_
background-image:url(http://www.clker.com/cliparts/c/q/l/t/l/B/radiobutton-unchecked-sm-md.png);_x000D_
background-size: 100px 100px;_x000D_
height: 100px;_x000D_
width: 100px;_x000D_
display:inline-block;_x000D_
padding: 0 0 0 0px;_x000D_
cursor:pointer;_x000D_
}_x000D_
_x000D_
input[type="radio"]:checked + label_x000D_
{_x000D_
background-image:url(http://www.clker.com/cliparts/M/2/V/6/F/u/radiobutton-checked-sm-md.png);_x000D_
}
_x000D_
<div>_x000D_
<input type="radio" id="shipadd1" value=1 name="address" />_x000D_
<label for="shipadd1"></label>_x000D_
value 1_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
<input type="radio" id="shipadd2" value=2 name="address" />_x000D_
<label for="shipadd2"></label>_x000D_
value 2_x000D_
</div>
_x000D_
_x000D_
_x000D_
Demo: http://jsfiddle.net/La8wQ/2471/
This example based on this trick: https://css-tricks.com/the-checkbox-hack/
I tested it on: chrome, firefox, safari
Read String line by line
There is also Scanner
. You can use it just like the BufferedReader
:
Scanner scanner = new Scanner(myString);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
// process the line
}
scanner.close();
I think that this is a bit cleaner approach that both of the suggested ones.
Delete all the records
When the table is very large, it's better to delete table itself with drop table TableName
and recreate it, if one has create table query; rather than deleting records one by one, using delete from
statement because that can be time consuming.
Object cannot be cast from DBNull to other types
I suspect that the line
DataTO.Id = Convert.ToInt64(dataAccCom.GetParameterValue(IDbCmd, "op_Id"));
is causing the problem. Is it possible that the op_Id
value is being set to null by the stored procedure?
To Guard against it use the Convert.IsDBNull
method. For example:
if (!Convert.IsDBNull(dataAccCom.GetParameterValue(IDbCmd, "op_Id"))
{
DataTO.Id = Convert.ToInt64(dataAccCom.GetParameterValue(IDbCmd, "op_Id"));
}
else
{
DataTO.Id = ...some default value or perform some error case management
}
What is the best way to auto-generate INSERT statements for a SQL Server table?
My contribution to the problem, a Powershell INSERT script generator that lets you script multiple tables without having to use the cumbersome SSMS GUI. Great for rapidly persisting "seed" data into source control.
- Save the below script as "filename.ps1".
- Make your own modifications to the areas under "CUSTOMIZE ME".
- You can add the list of tables to script in any order.
- You can open the script in Powershell ISE and hit the Play button, or simply execute the script in the Powershell command prompt.
By default, the INSERT script generated will be "SeedData.sql" under the same folder as the script.
You will need the SQL Server Management Objects assemblies installed, which should be there if you have SSMS installed.
Add-Type -AssemblyName ("Microsoft.SqlServer.Smo, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91")
Add-Type -AssemblyName ("Microsoft.SqlServer.ConnectionInfo, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91")
#CUSTOMIZE ME
$outputFile = ".\SeedData.sql"
$connectionString = "Data Source=.;Initial Catalog=mydb;Integrated Security=True;"
$sqlConnection = new-object System.Data.SqlClient.SqlConnection($connectionString)
$conn = new-object Microsoft.SqlServer.Management.Common.ServerConnection($sqlConnection)
$srv = new-object Microsoft.SqlServer.Management.Smo.Server($conn)
$db = $srv.Databases[$srv.ConnectionContext.DatabaseName]
$scr = New-Object Microsoft.SqlServer.Management.Smo.Scripter $srv
$scr.Options.FileName = $outputFile
$scr.Options.AppendToFile = $false
$scr.Options.ScriptSchema = $false
$scr.Options.ScriptData = $true
$scr.Options.NoCommandTerminator = $true
$tables = New-Object Microsoft.SqlServer.Management.Smo.UrnCollection
#CUSTOMIZE ME
$tables.Add($db.Tables["Category"].Urn)
$tables.Add($db.Tables["Product"].Urn)
$tables.Add($db.Tables["Vendor"].Urn)
[void]$scr.EnumScript($tables)
$sqlConnection.Close()
How to connect to SQL Server database from JavaScript in the browser?
I dont think you can connect to SQL server from client side javascripts. You need to pick up some server side language to build web applications which can interact with your database and use javascript only to make your user interface better to interact with.
you can pick up any server side scripting language based on your language preference :
- PHP
- ASP.Net
- Ruby On Rails
convert a JavaScript string variable to decimal/money
You can also use the Number
constructor/function (no need for a radix and usable for both integers and floats):
Number('09'); /=> 9
Number('09.0987'); /=> 9.0987
Alternatively like Andy E said in the comments you can use +
for conversion
+'09'; /=> 9
+'09.0987'; /=> 9.0987
Bootstrap Alert Auto Close
C# Controller:
var result = await _roleManager.CreateAsync(identityRole);
if (result.Succeeded == true)
TempData["roleCreateAlert"] = "Added record successfully";
Razor Page:
@if (TempData["roleCreateAlert"] != null)
{
<div class="alert alert-success">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<p>@TempData["roleCreateAlert"]</p>
</div>
}
Any Alert Auto Close:
<script type="text/javascript">
$(".alert").delay(5000).slideUp(200, function () {
$(this).alert('close');
});
</script>
Setting the default active profile in Spring-boot
We to faced similar issue while setting spring.profiles.active
in java.
This is what we figured out in the end, after trying four different ways of providing spring.profiles.active
.
In java-8
$ java --spring.profiles.active=dev -jar my-service.jar
Gives unrecognized --spring.profiles.active option.
$ java -jar my-service.jar --spring.profiles.active=dev
# This works fine
$ java -Dspring.profiles.active=dev -jar my-service.jar
# This works fine
$ java -jar my-service.jar -Dspring.profiles.active=dev
# This doesn't works
In java-11
$ java --spring.profiles.active=dev -jar my-service.jar
Gives unrecognized --spring.profiles.active option.
$ java -jar my-service.jar --spring.profiles.active=dev
# This doesn't works
$ java -Dspring.profiles.active=dev -jar my-service.jar
# This works fine
$ java -jar my-service.jar -Dspring.profiles.active=dev
# This doesn't works
NOTE: If you're specifying spring.profiles.active
in your application.properties
file then make sure you provide spring.config.location
or spring.config.additional-location
option to java accordingly as mentioned above.
What's the yield keyword in JavaScript?
To give a complete answer: yield
is working similar to return
, but in a generator.
As for the commonly given example, this works as follows:
function *squareGen(x) {
var i;
for (i = 0; i < x; i++) {
yield i*i;
}
}
var gen = squareGen(3);
console.log(gen.next().value); // prints 0
console.log(gen.next().value); // prints 1
console.log(gen.next().value); // prints 4
But theres also a second purpose of the yield keyword. It can be used to send values to the generator.
To clarify, a small example:
function *sendStuff() {
y = yield (0);
yield y*y;
}
var gen = sendStuff();
console.log(gen.next().value); // prints 0
console.log(gen.next(2).value); // prints 4
This works, as the value 2
is assigned to y
, by sending it to the generator, after it stopped at the first yield (which returned 0
).
This enables us to to some really funky stuff. (look up coroutine)
How to code a very simple login system with java
import java.<span class="q39pbqr9" id="q39pbqr9_9">net</span>.*;
import java.io.*;
<span class="q39pbqr9" id="q39pbqr9_1">public class</span> A
{
static String user = "user";
static String pass = "pass";
static String param_user = "username";
static String param_pass = "password";
static String content = "";
static String action = "action_url";
static String urlName = "url_name";
public static void main(String[] args)
{
try
{
user = URLEncoder.encode(user, "UTF-8");
pass = URLEncoder.encode(pass, "UTF-8");
content = "action=" + action +"&" + param_user +"=" + user + "&" + param_pass + "=" + pass;
URL url = new URL(urlName);
HttpURLConnection urlConnection = (HttpURLConnection)(url.openConnection());
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestMethod("POST");
DataOutputStream dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());
dataOutputStream.writeBytes(content);
dataOutputStream.flush();
dataOutputStream.close();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String responeLine;
StringBuilder response = new StringBuilder();
while ((responeLine = bufferedReader.readLine()) != null)
{
response.append(responeLine);
}
System.out.println(response);
}catch(Exception ex){ex.printStackTrace();}
}
Difference between thread's context class loader and normal classloader
This does not answer the original question, but as the question is highly ranked and linked for any ContextClassLoader
query, I think it is important to answer the related question of when the context class loader should be used. Short answer: never use the context class loader! But set it to getClass().getClassLoader()
when you have to call a method that is missing a ClassLoader
parameter.
When code from one class asks to load another class, the correct class loader to use is the same class loader as the caller class (i.e., getClass().getClassLoader()
). This is the way things work 99.9% of the time because this is what the JVM does itself the first time you construct an instance of a new class, invoke a static method, or access a static field.
When you want to create a class using reflection (such as when deserializing or loading a configurable named class), the library that does the reflection should always ask the application which class loader to use, by receiving the ClassLoader
as a parameter from the application. The application (which knows all the classes that need constructing) should pass it getClass().getClassLoader()
.
Any other way to obtain a class loader is incorrect. If a library uses hacks such as Thread.getContextClassLoader()
, sun.misc.VM.latestUserDefinedLoader()
, or sun.reflect.Reflection.getCallerClass()
it is a bug caused by a deficiency in the API. Basically, Thread.getContextClassLoader()
exists only because whoever designed the ObjectInputStream
API forgot to accept the ClassLoader
as a parameter, and this mistake has haunted the Java community to this day.
That said, many many JDK classes use one of a few hacks to guess some class loader to use. Some use the ContextClassLoader
(which fails when you run different apps on a shared thread pool, or when you leave the ContextClassLoader null
), some walk the stack (which fails when the direct caller of the class is itself a library), some use the system class loader (which is fine, as long as it is documented to only use classes in the CLASSPATH
) or bootstrap class loader, and some use an unpredictable combination of the above techniques (which only makes things more confusing). This has resulted in much weeping and gnashing of teeth.
When using such an API, first, try to find an overload of the method that accepts the class loader as a parameter. If there is no sensible method, then try setting the ContextClassLoader
before the API call (and resetting it afterwards):
ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
// call some API that uses reflection without taking ClassLoader param
} finally {
Thread.currentThread().setContextClassLoader(originalClassLoader);
}
How to split() a delimited string to a List<String>
This will read a csv file and it includes a csv line splitter that handles double quotes and it can read even if excel has it open.
public List<Dictionary<string, string>> LoadCsvAsDictionary(string path)
{
var result = new List<Dictionary<string, string>>();
var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
System.IO.StreamReader file = new System.IO.StreamReader(fs);
string line;
int n = 0;
List<string> columns = null;
while ((line = file.ReadLine()) != null)
{
var values = SplitCsv(line);
if (n == 0)
{
columns = values;
}
else
{
var dict = new Dictionary<string, string>();
for (int i = 0; i < columns.Count; i++)
if (i < values.Count)
dict.Add(columns[i], values[i]);
result.Add(dict);
}
n++;
}
file.Close();
return result;
}
private List<string> SplitCsv(string csv)
{
var values = new List<string>();
int last = -1;
bool inQuotes = false;
int n = 0;
while (n < csv.Length)
{
switch (csv[n])
{
case '"':
inQuotes = !inQuotes;
break;
case ',':
if (!inQuotes)
{
values.Add(csv.Substring(last + 1, (n - last)).Trim(' ', ','));
last = n;
}
break;
}
n++;
}
if (last != csv.Length - 1)
values.Add(csv.Substring(last + 1).Trim());
return values;
}
jQuery UI 1.10: dialog and zIndex option
You don't tell it, but you are using jQuery UI 1.10.
In jQuery UI 1.10 the zIndex
option is removed:
Removed zIndex option
Similar to the stack option, the zIndex option is unnecessary with a
proper stacking implementation. The z-index is defined in CSS and
stacking is now controlled by ensuring the focused dialog is the last
"stacking" element in its parent.
you have to use pure css to set the dialog "on the top":
.ui-dialog { z-index: 1000 !important ;}
you need the key !important
to override the default styling of the element; this affects all your dialogs if you need to set it only for a dialog use the dialogClass
option and style it.
If you need a modal dialog set the modal: true
option see the docs:
If set to true, the dialog will have modal behavior; other items on
the page will be disabled, i.e., cannot be interacted with. Modal
dialogs create an overlay below the dialog but above other page
elements.
You need to set the modal overlay with an higher z-index to do so use:
.ui-front { z-index: 1000 !important; }
for this element too.
How to use java.Set
The first thing you need to study is the java.util.Set
API.
Here's a small example of how to use its methods:
Set<Integer> numbers = new TreeSet<Integer>();
numbers.add(2);
numbers.add(5);
System.out.println(numbers); // "[2, 5]"
System.out.println(numbers.contains(7)); // "false"
System.out.println(numbers.add(5)); // "false"
System.out.println(numbers.size()); // "2"
int sum = 0;
for (int n : numbers) {
sum += n;
}
System.out.println("Sum = " + sum); // "Sum = 7"
numbers.addAll(Arrays.asList(1,2,3,4,5));
System.out.println(numbers); // "[1, 2, 3, 4, 5]"
numbers.removeAll(Arrays.asList(4,5,6,7));
System.out.println(numbers); // "[1, 2, 3]"
numbers.retainAll(Arrays.asList(2,3,4,5));
System.out.println(numbers); // "[2, 3]"
Once you're familiar with the API, you can use it to contain more interesting objects. If you haven't familiarized yourself with the equals
and hashCode
contract, already, now is a good time to start.
In a nutshell:
@Override
both or none; never just one. (very important, because it must satisfied property: a.equals(b) == true --> a.hashCode() == b.hashCode()
- Be careful with writing
boolean equals(Thing other)
instead; this is not a proper @Override
.
- For non-null references
x, y, z
, equals
must be:
- reflexive:
x.equals(x)
.
- symmetric:
x.equals(y)
if and only if y.equals(x)
- transitive: if
x.equals(y) && y.equals(z)
, then x.equals(z)
- consistent:
x.equals(y)
must not change unless the objects have mutated
x.equals(null) == false
- The general contract for
hashCode
is:
- consistent: return the same number unless mutation happened
- consistent with
equals
: if x.equals(y)
, then x.hashCode() == y.hashCode()
- strictly speaking, object inequality does not require hash code inequality
- but hash code inequality necessarily requires object inequality
- What counts as mutation should be consistent between
equals
and hashCode
.
Next, you may want to impose an ordering of your objects. You can do this by making your type implements Comparable
, or by providing a separate Comparator
.
Having either makes it easy to sort your objects (Arrays.sort
, Collections.sort(List)
). It also allows you to use SortedSet
, such as TreeSet
.
Further readings on stackoverflow:
Column name or number of supplied values does not match table definition
for inserts it is always better to specify the column names see the following
DECLARE @Table TABLE(
Val1 VARCHAR(MAX)
)
INSERT INTO @Table SELECT '1'
works fine, changing the table def to causes the error
DECLARE @Table TABLE(
Val1 VARCHAR(MAX),
Val2 VARCHAR(MAX)
)
INSERT INTO @Table SELECT '1'
Msg 213, Level 16, State 1, Line 6
Insert Error: Column name or number of
supplied values does not match table
definition.
But changing the above to
DECLARE @Table TABLE(
Val1 VARCHAR(MAX),
Val2 VARCHAR(MAX)
)
INSERT INTO @Table (Val1) SELECT '1'
works. You need to be more specific with the columns specified
supply the structures and we can have a look
With ng-bind-html-unsafe removed, how do I inject HTML?
For me, the simplest and most flexible solution is:
<div ng-bind-html="to_trusted(preview_data.preview.embed.html)"></div>
And add function to your controller:
$scope.to_trusted = function(html_code) {
return $sce.trustAsHtml(html_code);
}
Don't forget add $sce
to your controller's initialization.
How to use setprecision in C++
The answer above is absolutely correct. Here is a Turbo C++ version of it.
#include <iomanip.h>
#include <iostream.h>
void main()
{
double num1 = 3.12345678;
cout << setiosflags(fixed) << setiosflags(showpoint);
cout << setprecision(2);
cout << num1 << endl;
}
For fixed
and showpoint
, I think the setiosflags
function should be used.
Fastest way to add an Item to an Array
For those who didn't know what next, just add new module file and put @jor code (with my little hacked, supporting 'nothing' array) below.
Module ArrayExtension
<Extension()> _
Public Sub Add(Of T)(ByRef arr As T(), item As T)
If arr IsNot Nothing Then
Array.Resize(arr, arr.Length + 1)
arr(arr.Length - 1) = item
Else
ReDim arr(0)
arr(0) = item
End If
End Sub
End Module
Pip freeze vs. pip list
pip list
shows ALL installed packages.
pip freeze
shows packages YOU installed via pip
(or pipenv
if using that tool) command in a requirements format.
Remark below that setuptools, pip, wheel are installed when pipenv shell
creates my virtual envelope. These packages were NOT installed by me using pip
:
test1 % pipenv shell
Creating a virtualenv for this project…
Pipfile: /Users/terrence/Development/Python/Projects/test1/Pipfile
Using /usr/local/Cellar/pipenv/2018.11.26_3/libexec/bin/python3.8 (3.8.1) to create virtualenv…
? Creating virtual environment...
<SNIP>
Installing setuptools, pip, wheel...
done.
? Successfully created virtual environment!
<SNIP>
Now review & compare the output of the respective commands where I've only installed cool-lib and sampleproject (of which peppercorn is a dependency):
test1 % pip freeze <== Packages I'VE installed w/ pip
-e git+https://github.com/gdamjan/hello-world-python-package.git@10<snip>71#egg=cool_lib
peppercorn==0.6
sampleproject==1.3.1
test1 % pip list <== All packages, incl. ones I've NOT installed w/ pip
Package Version Location
------------- ------- --------------------------------------------------------------------------
cool-lib 0.1 /Users/terrence/.local/share/virtualenvs/test1-y2Zgz1D2/src/cool-lib <== Installed w/ `pip` command
peppercorn 0.6 <== Dependency of "sampleproject"
pip 20.0.2
sampleproject 1.3.1 <== Installed w/ `pip` command
setuptools 45.1.0
wheel 0.34.2
What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?
__PRETTY_FUNCTION__
handles C++ features: classes, namespaces, templates and overload
main.cpp
#include <iostream>
namespace N {
class C {
public:
template <class T>
static void f(int i) {
(void)i;
std::cout << "__func__ " << __func__ << std::endl
<< "__FUNCTION__ " << __FUNCTION__ << std::endl
<< "__PRETTY_FUNCTION__ " << __PRETTY_FUNCTION__ << std::endl;
}
template <class T>
static void f(double f) {
(void)f;
std::cout << "__PRETTY_FUNCTION__ " << __PRETTY_FUNCTION__ << std::endl;
}
};
}
int main() {
N::C::f<char>(1);
N::C::f<void>(1.0);
}
Compile and run:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out
Output:
__func__ f
__FUNCTION__ f
__PRETTY_FUNCTION__ static void N::C::f(int) [with T = char]
__PRETTY_FUNCTION__ static void N::C::f(double) [with T = void]
You may also be interested in stack traces with function names: print call stack in C or C++
Tested in Ubuntu 19.04, GCC 8.3.0.
C++20 std::source_location::function_name
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1208r5.pdf went into C++20, so we have yet another way to do it.
The documentation says:
constexpr const char* function_name() const noexcept;
6 Returns: If this object represents a position in the body of a function,
returns an implementation-defined NTBS that should correspond to the
function name. Otherwise, returns an empty string.
where NTBS means "Null Terminated Byte String".
I'll give it a try when support arrives to GCC, GCC 9.1.0 with g++-9 -std=c++2a
still doesn't support it.
https://en.cppreference.com/w/cpp/utility/source_location claims usage will be like:
#include <iostream>
#include <string_view>
#include <source_location>
void log(std::string_view message,
const std::source_location& location std::source_location::current()
) {
std::cout << "info:"
<< location.file_name() << ":"
<< location.line() << ":"
<< location.function_name() << " "
<< message << '\n';
}
int main() {
log("Hello world!");
}
Possible output:
info:main.cpp:16:main Hello world!
so note how this returns the caller information, and is therefore perfect for usage in logging, see also: Is there a way to get function name inside a C++ function?
CSS: background-color only inside the margin
I needed something similar, and came up with using the :before (or :after) pseudoclasses:
#mydiv {
background-color: #fbb;
margin-top: 100px;
position: relative;
}
#mydiv:before {
content: "";
background-color: #bfb;
top: -100px;
height: 100px;
width: 100%;
position: absolute;
}
JSFiddle
Fastest way to check if a string is JSON in PHP?
You must validate your input to make sure the string you pass is not empty and is, in fact, a string. An empty string is not valid JSON.
function is_json($string) {
return !empty($string) && is_string($string) && is_array(json_decode($string, true)) && json_last_error() == 0;
}
I think in PHP it's more important to determine if the JSON object even has data, because to use the data you will need to call json_encode()
or json_decode()
. I suggest denying empty JSON objects so you aren't unnecessarily running encodes and decodes on empty data.
function has_json_data($string) {
$array = json_decode($string, true);
return !empty($string) && is_string($string) && is_array($array) && !empty($array) && json_last_error() == 0;
}
How to run Java program in command prompt
A very general command prompt how to for java is
javac mainjava.java
java mainjava
You'll very often see people doing
javac *.java
java mainjava
As for the subclass problem that's probably occurring because a path is missing from your class path, the -c flag I believe is used to set that.
Lowercase and Uppercase with jQuery
I think you want to lowercase the checked value? Try:
var jIsHasKids = $('#chkIsHasKids:checked').val().toLowerCase();
or you want to check it, then get its value as lowercase:
var jIsHasKids = $('#chkIsHasKids').attr("checked", true).val().toLowerCase();
split string only on first instance - java
This works:
public class Split
{
public static void main(String...args)
{
String a = "%abcdef&Ghijk%xyz";
String b[] = a.split("%", 2);
System.out.println("Value = "+b[1]);
}
}
How to deal with SQL column names that look like SQL keywords?
In MySQL, alternatively to using back quotes (`), you can use the UI to alter column names. Right click the table > Alter table > Edit the column name that contains sql keyword > Commit.
select [from] from <table>
As a note, the above does not work in MySQL
How can I get the current user's username in Bash?
On the command line, enter
whoami
or
echo "$USER"
To save these values to a variable, do
myvariable=$(whoami)
or
myvariable=$USER
Of course, you don't need to make a variable since that is what the $USER
variable is for.
Import CSV file as a pandas DataFrame
To read a CSV file as a pandas DataFrame, you'll need to use pd.read_csv
.
But this isn't where the story ends; data exists in many different formats and is stored in different ways so you will often need to pass additional parameters to read_csv
to ensure your data is read in properly.
Here's a table listing common scenarios encountered with CSV files along with the appropriate argument you will need to use. You will usually need all or some combination of the arguments below to read in your data.
+-------------------------------------------------------------------------------------------------------------------------------------------------+
¦ Scenario ¦ Argument ¦ Example ¦
+----------------------------------------------------------+-----------------------------+--------------------------------------------------------¦
¦ Read CSV with different separator¹ ¦ sep/delimiter ¦ read_csv(..., sep=';') ¦
¦ Read CSV with tab/whitespace separator ¦ delim_whitespace ¦ read_csv(..., delim_whitespace=True) ¦
¦ Fix UnicodeDecodeError while reading² ¦ encoding ¦ read_csv(..., encoding='latin-1') ¦
¦ Read CSV without headers³ ¦ header and names ¦ read_csv(..., header=False, names=['x', 'y', 'z']) ¦
¦ Specify which column to set as the index4 ¦ index_col ¦ read_csv(..., index_col=[0]) ¦
¦ Read subset of columns ¦ usecols ¦ read_csv(..., usecols=['x', 'y']) ¦
¦ Numeric data is in European format (eg., 1.234,56) ¦ thousands and decimal ¦ read_csv(..., thousands='.', decimal=',') ¦
+-------------------------------------------------------------------------------------------------------------------------------------------------+
Footnotes
By default, read_csv
uses a C parser engine for performance. The C parser can only handle single character separators. If your CSV has
a multi-character separator, you will need to modify your code to use
the 'python'
engine. You can also pass regular expressions:
df = pd.read_csv(..., sep=r'\s*\|\s*', engine='python')
UnicodeDecodeError
occurs when the data was stored in one encoding format but read in a different, incompatible one. Most common
encoding schemes are 'utf-8'
and 'latin-1'
, your data is likely to
fit into one of these.
header=False
specifies that the first row in the CSV is a data row rather than a header row, and the names=[...]
allows you to
specify a list of column names to assign to the DataFrame when it is
created.
"Unnamed: 0" occurs when a DataFrame with an un-named index is saved to CSV and then re-read after. Instead of having to fix the
issue while reading, you can also fix the issue when writing by using
df.to_csv(..., index=False)
There are other arguments I've not mentioned here, but these are the ones you'll encounter most frequently.
Getting the difference between two repositories
Meld can compare directories:
meld directory1 directory2
Just use the directories of the two git repos and you will get a nice graphical comparison:
When you click on one of the blue items, you can see what changed.
PowerShell To Set Folder Permissions
In case you had to deal with a lot of subfolders contatining subfolders and other recursive stuff. Small improvment of @Mike L'Angelo:
$mypath = "path_to_folder"
$myacl = Get-Acl $mypath
$myaclentry = "username","FullControl","Allow"
$myaccessrule = New-Object System.Security.AccessControl.FileSystemAccessRule($myaclentry)
$myacl.SetAccessRule($myaccessrule)
Get-ChildItem -Path "$mypath" -Recurse -Force | Set-Acl -AclObject $myacl -Verbose
Verbosity is optional in the last line
How to create id with AUTO_INCREMENT on Oracle?
FUNCTION GETUNIQUEID_2 RETURN VARCHAR2
AS
v_curr_id NUMBER;
v_inc NUMBER;
v_next_val NUMBER;
pragma autonomous_transaction;
begin
CREATE SEQUENCE sequnce
START WITH YYMMDD0000000001
INCREMENT BY 1
NOCACHE
select sequence.nextval into v_curr_id from dual;
if(substr(v_curr_id,0,6)= to_char(sysdate,'yymmdd')) then
v_next_val := to_number(to_char(SYSDATE+1, 'yymmdd') || '0000000000');
v_inc := v_next_val - v_curr_id;
execute immediate ' alter sequence sequence increment by ' || v_inc ;
select sequence.nextval into v_curr_id from dual;
execute immediate ' alter sequence sequence increment by 1';
else
dbms_output.put_line('exception : file not found');
end if;
RETURN 'ID'||v_curr_id;
END;
Method to Add new or update existing item in Dictionary
Could there be any problem if i replace Method-1 by Method-2?
No, just use map[key] = value
. The two options are equivalent.
Regarding Dictionary<>
vs. Hashtable
: When you start Reflector, you see that the indexer setters of both classes call this.Insert(key, value, add: false);
and the add
parameter is responsible for throwing an exception, when inserting a duplicate key. So the behavior is the same for both classes.
What in layman's terms is a Recursive Function using PHP
If you add a certain value (say, "1") to Anthony Forloney's example, everything would be clear:
function fact(1) {
if (1 === 0) { // our base case
return 1;
}
else {
return 1 * fact(1-1); // <--calling itself.
}
}
original:
function fact($n) {
if ($n === 0) { // our base case
return 1;
}
else {
return $n * fact($n-1); // <--calling itself.
}
}
SQL Server: how to create a stored procedure
To Create SQL server Store procedure in SQL server management studio
- Expand your database
- Expand programmatically
- Right-click on Stored-procedure and Select "new Stored Procedure"
Now, Write your Store procedure, for example, it can be something like below
USE DatabaseName;
GO
CREATE PROCEDURE ProcedureName
@LastName nvarchar(50),
@FirstName nvarchar(50)
AS
SET NOCOUNT ON;
//Your SQL query here, like
Select FirstName, LastName, Department
FROM HumanResources.vEmployeeDepartmentHistory
WHERE FirstName = @FirstName AND LastName = @LastName
GO
Where, DatabaseName = name of your database
ProcedureName = name of SP
InputValue = your input parameter value (@LastName and @FirstName) and type = parameter type example nvarchar(50) etc.
Source: Stored procedure in sql server (With Example)
To Execute the above stored procedure you can use sample query as below
EXECUTE ProcedureName @FirstName = N'Pilar', @LastName = N'Ackerman';
Calling stored procedure with return value
This is a very short sample of returning a single value from a procedure:
SQL:
CREATE PROCEDURE [dbo].[MakeDouble] @InpVal int AS BEGIN
SELECT @InpVal * 2; RETURN 0;
END
C#-code:
int inpVal = 11;
string retVal = "?";
using (var sqlCon = new SqlConnection(
"Data Source = . ; Initial Catalog = SampleDb; Integrated Security = True;"))
{
sqlCon.Open();
retVal = new SqlCommand("Exec dbo.MakeDouble " + inpVal + ";",
sqlCon).ExecuteScalar().ToString();
sqlCon.Close();
}
Debug.Print(inpVal + " * 2 = " + retVal);
//> 11 * 2 = 22
How do you specifically order ggplot2 x axis instead of alphabetical order?
The accepted answer offers a solution which requires changing of the underlying data frame. This is not necessary. One can also simply factorise within the aes()
call directly or create a vector for that instead.
This is certainly not much different than user Drew Steen's answer, but with the important difference of not changing the original data frame.
level_order <- c('virginica', 'versicolor', 'setosa') #this vector might be useful for other plots/analyses
ggplot(iris, aes(x = factor(Species, level = level_order), y = Petal.Width)) + geom_col()
or
level_order <- factor(iris$Species, level = c('virginica', 'versicolor', 'setosa'))
ggplot(iris, aes(x = level_order, y = Petal.Width)) + geom_col()
or
directly in the aes()
call without a pre-created vector:
ggplot(iris, aes(x = factor(Species, level = c('virginica', 'versicolor', 'setosa')), y = Petal.Width)) + geom_col()
Changing image on hover with CSS/HTML
The problem with all the previous answers is that the hover image isn't loaded with the page so when the browser calls it, it takes time to load and the whole thing doesn't look really good.
What I do is that I put the original image and the hover image in 1 element and hide the hover image at first. Then at hover in I display the hover image and hide the old one, and at hover out I do the opposite.
HTML:
<span id="bellLogo" onmouseover="hvr(this, 'in')" onmouseleave="hvr(this, 'out')">
<img src="stylesheets/images/bell.png" class=bell col="g">
<img src="stylesheets/images/bell_hover.png" class=bell style="display:none" col="b">
</span>
JavaScript/jQuery:
function hvr(dom, action)
{
if (action == 'in')
{
$(dom).find("[col=g]").css("display", "none");
$(dom).find("[col=b]").css("display", "inline-block");
}
else
{
$(dom).find("[col=b]").css("display", "none");
$(dom).find("[col=g]").css("display", "inline-block");
}
}
This to me is the easiest and most efficient way to do it.
How to enable TLS 1.2 support in an Android application (running on Android 4.1 JB)
As the OP said, TLS v1.1 and v1.2 protocols are supported in API level 16+, but are not enabled by default, we just need to enable it.
Example here uses HttpsUrlConnection
, not HttpUrlConnection
. Follow https://blog.dev-area.net/2015/08/13/android-4-1-enable-tls-1-1-and-tls-1-2/, we can create a factory
class MyFactory extends SSLSocketFactory {
private javax.net.ssl.SSLSocketFactory internalSSLSocketFactory;
public MyFactory() throws KeyManagementException, NoSuchAlgorithmException {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, null, null);
internalSSLSocketFactory = context.getSocketFactory();
}
@Override
public String[] getDefaultCipherSuites() {
return internalSSLSocketFactory.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return internalSSLSocketFactory.getSupportedCipherSuites();
}
@Override
public Socket createSocket() throws IOException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket());
}
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(s, host, port, autoClose));
}
@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port));
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port, localHost, localPort));
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port));
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(address, port, localAddress, localPort));
}
private Socket enableTLSOnSocket(Socket socket) {
if(socket != null && (socket instanceof SSLSocket)) {
((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2"});
}
return socket;
}
}
No matter which Networking library you use, make sure ((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2"});
gets called so the Socket has enabled TLS protocols.
Now, you can use that in HttpsUrlConnection
class MyHttpRequestTask extends AsyncTask<String,Integer,String> {
@Override
protected String doInBackground(String... params) {
String my_url = params[0];
try {
URL url = new URL(my_url);
HttpsURLConnection httpURLConnection = (HttpsURLConnection) url.openConnection();
httpURLConnection.setSSLSocketFactory(new MyFactory());
// setting the Request Method Type
httpURLConnection.setRequestMethod("GET");
// adding the headers for request
httpURLConnection.setRequestProperty("Content-Type", "application/json");
String result = readStream(httpURLConnection.getInputStream());
Log.e("My Networking", "We have data" + result.toString());
}catch (Exception e){
e.printStackTrace();
Log.e("My Networking", "Oh no, error occurred " + e.toString());
}
return null;
}
private static String readStream(InputStream is) throws IOException {
final BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("US-ASCII")));
StringBuilder total = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
total.append(line);
}
if (reader != null) {
reader.close();
}
return total.toString();
}
}
For example
new MyHttpRequestTask().execute(myUrl);
Also, remember to bump minSdkVersion
in build.gradle to 16
minSdkVersion 16
Groovy executing shell commands
// a wrapper closure around executing a string
// can take either a string or a list of strings (for arguments with spaces)
// prints all output, complains and halts on error
def runCommand = { strList ->
assert ( strList instanceof String ||
( strList instanceof List && strList.each{ it instanceof String } ) \
)
def proc = strList.execute()
proc.in.eachLine { line -> println line }
proc.out.close()
proc.waitFor()
print "[INFO] ( "
if(strList instanceof List) {
strList.each { print "${it} " }
} else {
print strList
}
println " )"
if (proc.exitValue()) {
println "gave the following error: "
println "[ERROR] ${proc.getErrorStream()}"
}
assert !proc.exitValue()
}
getString Outside of a Context or Activity
BTW, one of the reason of symbol not found error may be that your IDE imported android.R; class instead of yours one. Just change import android.R; to import your.namespace.R;
So 2 basic things to get string visible in the different class:
//make sure you are importing the right R class
import your.namespace.R;
//don't forget about the context
public void some_method(Context context) {
context.getString(R.string.YOUR_STRING);
}
Stop a youtube video with jquery?
1.include
<script type="text/javascript" src="http://www.youtube.com/player_api"></script>
2.add your youtube iframe.
<iframe id="player" src="http://www.youtube.com/embed/YOURID?rel=0&wmode=Opaque&enablejsapi=1" frameborder="0"></iframe>
3.magic time.
<script>
var player;
function onYouTubePlayerAPIReady() {player = new YT.Player('player');}
//so on jquery event or whatever call the play or stop on the video.
//to play player.playVideo();
//to stop player.stopVideo();
</script>
Border in shape xml
If you want make a border in a shape xml. You need to use:
For the external border,you need to use:
<stroke/>
For the internal background,you need to use:
<solid/>
If you want to set corners,you need to use:
<corners/>
If you want a padding betwen border and the internal elements,you need to use:
<padding/>
Here is a shape xml example using the above items. It works for me
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="2dp" android:color="#D0CFCC" />
<solid android:color="#F8F7F5" />
<corners android:radius="10dp" />
<padding android:left="2dp" android:top="2dp" android:right="2dp" android:bottom="2dp" />
</shape>