How to detect orientation change?
override func viewDidLoad() {
NotificationCenter.default.addObserver(self, selector: #selector(MyController.rotated), name: UIDevice.orientationDidChangeNotification, object: nil)
//...
}
@objc
private func rotated() {
if UIDevice.current.orientation.isLandscape {
} else if UIDevice.current.orientation.isPortrait {
}
//or you can check orientation separately UIDevice.current.orientation
//portrait, portraitUpsideDown, landscapeLeft, landscapeRight...
}
warning: implicit declaration of function
Don't forget, if any functions that are called in your function and their prototypes must be situated above your function in the code otherwise the compiler might not find them before it attempts to compile your function. This will generate the error in question.
isset in jQuery?
if (($("#one").length > 0)){
alert('yes');
}
if (($("#two").length > 0)){
alert('yes');
}
if (($("#three").length > 0)){
alert('yes');
}
if (($("#four")).length == 0){
alert('no');
}
This is what you need :)
Implement Stack using Two Queues
Here is very simple solution which uses one Queue and gives functionality like Stack.
public class CustomStack<T>
{
Queue<T> que = new Queue<T>();
public void push(T t) // STACK = LIFO / QUEUE = FIFO
{
if( que.Count == 0)
{
que.Enqueue(t);
}
else
{
que.Enqueue(t);
for (int i = 0; i < que.Count-1; i++)
{
var data = que.Dequeue();
que.Enqueue(data);
}
}
}
public void pop()
{
Console.WriteLine("\nStack Implementation:");
foreach (var item in que)
{
Console.Write("\n" + item.ToString() + "\t");
}
var data = que.Dequeue();
Console.Write("\n Dequeing :" + data);
}
public void top()
{
Console.Write("\n Top :" + que.Peek());
}
}
So in the above class named "CustomStack" what I am doing is just checking the queue for empty , if empty then insert one and from then on wards insert and then remove insert. By this logic first will come last.
Example : In queue I inserted 1 and now trying to insert 2. Second time remove 1 and again insert so it becomes in reverse order.
Thank you.
http post - how to send Authorization header?
I had the same issue. This is my solution using angular documentation and firebase Token:
getService() {
const accessToken=this.afAuth.auth.currentUser.getToken().then(res=>{
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': res
})
};
return this.http.get('Url',httpOptions)
.subscribe(res => console.log(res));
}); }}
Place API key in Headers or URL
passing api key in parameters makes it difficult for clients to keep their APIkeys secret, they tend to leak keys on a regular basis.
A better approach is to pass it in header of request url.you can set user-key header in your code .
For testing your request Url you can use Postman app in google chrome by setting user-key header to your api-key.
Best Practice to Use HttpClient in Multithreaded Environment
With HttpClient 4.5 you can do this:
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(new PoolingHttpClientConnectionManager()).build();
Note that this one implements Closeable (for shutting down of the connection manager).
Python string.replace regular expression
re.sub
is definitely what you are looking for. And so you know, you don't need the anchors and the wildcards.
re.sub(r"(?i)interfaceOpDataFile", "interfaceOpDataFile %s" % filein, line)
will do the same thing--matching the first substring that looks like "interfaceOpDataFile" and replacing it.
Exit/save edit to sudoers file? Putty SSH
To make changes to sudo from putty/bash:
- Type visudo and press enter.
- Navigate to the place you wish to edit using the up and down arrow keys.
- Press insert to go into editing mode.
- Make your changes - for example: user ALL=(ALL) ALL.
- Note - it matters whether you use tabs or spaces when making changes.
- Once your changes are done press esc to exit editing mode.
- Now type :wq to save and press enter.
- You should now be back at bash.
- Now you can press ctrl + D to exit the session if you wish.
Null check in an enhanced for loop
The "||" or the "??" comes in handy here
Best choice and IE compatible is the ||
for (Object object : someList || []) {
// undefined and null gets defaulted to an empty array []
}
Nullish coalescing operator: Not IE compatible
for (Object object : someList ?? []) {
// undefined and null gets defaulted to an empty array []
}
rand() between 0 and 1
This is entirely implementation specific, but it appears that in the C++ environment you're working in, RAND_MAX
is equal to INT_MAX
.
Because of this, RAND_MAX + 1
exhibits undefined (overflow) behavior, and becomes INT_MIN
. While your initial statement was dividing (random # between 0 and INT_MAX
)/(INT_MAX
) and generating a value 0 <= r < 1
, now it's dividing (random # between 0 and INT_MAX
)/(INT_MIN
), generating a value -1 < r <= 0
In order to generate a random number 1 <= r < 2
, you would want
r = ((double) rand() / (RAND_MAX)) + 1
bash: npm: command not found?
Debian:
cd /tmp/
wget https://deb.nodesource.com/setup_8.x
echo 'deb https://deb.nodesource.com/node_8.x stretch main' > /etc/apt/sources.list.d/nodesource.list
wget -qO - https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add -
apt update
apt install nodejs
node -v
npm -v
Check if element found in array c++
Here is a simple generic C++11 function contains
which works for both arrays and containers:
using namespace std;
template<class C, typename T>
bool contains(C&& c, T e) { return find(begin(c), end(c), e) != end(c); };
Simple usage contains(arr, el)
is somewhat similar to in
keyword semantics in Python.
Here is a complete demo:
#include <algorithm>
#include <array>
#include <string>
#include <vector>
#include <iostream>
template<typename C, typename T>
bool contains(C&& c, T e) {
return std::find(std::begin(c), std::end(c), e) != std::end(c);
};
template<typename C, typename T>
void check(C&& c, T e) {
std::cout << e << (contains(c,e) ? "" : " not") << " found\n";
}
int main() {
int a[] = { 10, 15, 20 };
std::array<int, 3> b { 10, 10, 10 };
std::vector<int> v { 10, 20, 30 };
std::string s { "Hello, Stack Overflow" };
check(a, 10);
check(b, 15);
check(v, 20);
check(s, 'Z');
return 0;
}
Output:
10 found
15 not found
20 found
Z not found
MySQL InnoDB not releasing disk space after deleting data rows from table
Year back i also faced same problem on mysql5.7 version and ibdata1 occupied 150 Gb.
so i added undo tablespaces
Take Mysqldump backup
Stop mysql service
Remove all data from data dir
Add below undo tablespace parameter in current my.cnf
#undo tablespace
innodb_undo_directory = /var/lib/mysql/
innodb_rollback_segments = 128
innodb_undo_tablespaces = 3
innodb_undo_logs = 128
innodb_max_undo_log_size=1G
innodb_undo_log_truncate = ON
Start mysql service
store mysqldump backup
Problem resolved !!
How to upload a file to directory in S3 bucket using boto
You should mention the content type as well to omit the file accessing issue.
import os
image='fly.png'
s3_filestore_path = 'images/fly.png'
filename, file_extension = os.path.splitext(image)
content_type_dict={".png":"image/png",".html":"text/html",
".css":"text/css",".js":"application/javascript",
".jpg":"image/png",".gif":"image/gif",
".jpeg":"image/jpeg"}
content_type=content_type_dict[file_extension]
s3 = boto3.client('s3', config=boto3.session.Config(signature_version='s3v4'),
region_name='ap-south-1',
aws_access_key_id=S3_KEY,
aws_secret_access_key=S3_SECRET)
s3.put_object(Body=image, Bucket=S3_BUCKET, Key=s3_filestore_path, ContentType=content_type)
How do I create a timeline chart which shows multiple events? Eg. Metallica Band members timeline on wiki
As mentioned in the earlier comment, stacked bar chart does the trick, though the data needs to be setup differently.(See image below)
Duration column = End - Start
- Once done, plot your stacked bar chart using the entire data.
- Mark start and end range to no fill.
- Right click on the X Axis and change Axis options manually. (This did cause me some issues, till I realized I couldn't manipulate them to enter dates, :) yeah I am newbie, excel masters! :))
What is compiler, linker, loader?
compiler changes checks your source code for errors and changes it into object code.this is the code that operating system runs.
You often don't write a whole program in single file so linker links all your object code files.
your program wont get executed unless it is in main memory
Check if Key Exists in NameValueCollection
I am using this collection, when I worked in small elements collection.
Where elements lot, I think need use "Dictionary".
My code:
NameValueCollection ProdIdes;
string prodId = _cfg.ProdIdes[key];
if (string.IsNullOrEmpty(prodId))
{
......
}
Or may be use this:
string prodId = _cfg.ProdIdes[key] !=null ? "found" : "not found";
Authorize attribute in ASP.NET MVC
The tag in web.config is based on paths, whereas MVC works with controller actions and routes.
It is an architectural decision that might not make a lot of difference if you just want to prevent users that aren't logged in but makes a lot of difference when you try to apply authorization based in Roles and in cases that you want custom handling of types of Unauthorized.
The first case is covered from the answer of BobRock.
The user should have at least one of the following Roles to access the Controller or the Action
[Authorize(Roles = "Admin, Super User")]
The user should have both these roles in order to be able to access the Controller or Action
[Authorize(Roles = "Super User")]
[Authorize(Roles = "Admin")]
The users that can access the Controller or the Action are Betty and Johnny
[Authorize(Users = "Betty, Johnny")]
In ASP.NET Core you can use Claims and Policy principles for authorization through [Authorize]
.
options.AddPolicy("ElevatedRights", policy =>
policy.RequireRole("Administrator", "PowerUser", "BackupAdministrator"));
[Authorize(Policy = "ElevatedRights")]
The second comes very handy in bigger applications where Authorization might need to be implemented with different restrictions, process and handling according to the case. For this reason we can Extend the AuthorizeAttribute and implement different authorization alternatives for our project.
public class CustomAuthorizeAttribute: AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{ }
}
The "correct-completed" way to do authorization in ASP.NET MVC is using the [Authorize]
attribute.
How to use Boost in Visual Studio 2010
In addition, there is something I find very useful. Use environment variables for your boost paths. (How to set environment variables in windows, link at bottom for 7,8,10) The BOOST_ROOT variable seems to be common place anymore and is set to the root path where you unzip boost.
Then in Properties, c++, general, Additional Include Directories use $(BOOST_ROOT)
. Then if/when you move to a newer version of the boost library you can update your environment variable to point to this newer version. As more of your projects, use boost you will not have to update the 'Additional Include Directories' for all of them.
You may also create a BOOST_LIB variable and point it to where the libs are staged. So likewise for the Linker->Additional Library Directories, you won't have to update projects. I have some old stuff built with vs10 and new stuff with vs14 so built both flavors of the boost lib to the same folder. So if I move a project from vs10 to vs14 I don't have to change the boost paths.
NOTE: If you change an environment variable it will not suddenly work in an open VS project. VS loads variables on startup. So you will have to close VS and reopen it.
Plot yerr/xerr as shaded region rather than error bars
Ignoring the smooth interpolation between points in your example graph (that would require doing some manual interpolation, or just have a higher resolution of your data), you can use pyplot.fill_between()
:
from matplotlib import pyplot as plt
import numpy as np
x = np.linspace(0, 30, 30)
y = np.sin(x/6*np.pi)
error = np.random.normal(0.1, 0.02, size=y.shape)
y += np.random.normal(0, 0.1, size=y.shape)
plt.plot(x, y, 'k-')
plt.fill_between(x, y-error, y+error)
plt.show()
See also the matplotlib examples.
How to install a specific version of Node on Ubuntu?
Chris Lea has 0.8.23 in his ppa repo.
This package let you add a repository to apt-get: (You can also do this manually)
sudo apt-get install software-properties-common
Add Chris Lea's repository:
sudo apt-add-repository ppa:chris-lea/node.js-legacy
Update apt-get:
sudo apt-get update
Install Node.js:
sudo apt-get install nodejs=0.8.23-1chl1~precise1
I think (feel free to edit) the version number is optional if you only add node.js-legacy. If you add both legacy and ppa/chris-lea/node.js you most likely need to add the version.
How to add a ScrollBar to a Stackpanel
It works like this:
<ScrollViewer VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Disabled" Width="340" HorizontalAlignment="Left" Margin="12,0,0,0">
<StackPanel Name="stackPanel1" Width="311">
</StackPanel>
</ScrollViewer>
TextBox tb = new TextBox();
tb.TextChanged += new TextChangedEventHandler(TextBox_TextChanged);
stackPanel1.Children.Add(tb);
If/else else if in Jquery for a condition
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<form name="myform">
Enter your name
<input type="text" name="inputbox" id='textBox' value="" />
<input type="button" name="button" class="member" value="Click1" />
<input type="button" name="button" value="Click2" onClick="testResults()" />
</form>
<script>
function testResults(n) {
var answer = $("#textBox").val();
if (answer == 2) {
alert("Good !");
} else if (answer == 3) {
alert("very Good !");
} else if (answer == 4) {
alert("better !");
} else if (answer == 5) {
alert("best !");
} else {
alert('wrong');
}
}
$(document).on('click', '.member', function () {
var answer = $("#textBox").val();
if (answer == 2) {
alert("Good !");
} else if (answer == 3) {
alert("very Good !");
} else if (answer == 4) {
alert("better !");
} else if (answer == 5) {
alert("best !");
} else {
alert('wrong');
}
});
</script>
How to remove element from ArrayList by checking its value?
Snippet to remove a element from any arraylist based on the matching condition is as follows:
List<String> nameList = new ArrayList<>();
nameList.add("Arafath");
nameList.add("Anjani");
nameList.add("Rakesh");
Iterator<String> myItr = nameList.iterator();
while (myItr.hasNext()) {
String name = myItr.next();
System.out.println("Next name is: " + name);
if (name.equalsIgnoreCase("rakesh")) {
myItr.remove();
}
}
Sending mail attachment using Java
Using Spring Framework , you can add many attachments :
package com.mkyong.common;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailParseException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
public class MailMail
{
private JavaMailSender mailSender;
private SimpleMailMessage simpleMailMessage;
public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {
this.simpleMailMessage = simpleMailMessage;
}
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void sendMail(String dear, String content) {
MimeMessage message = mailSender.createMimeMessage();
try{
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(simpleMailMessage.getFrom());
helper.setTo(simpleMailMessage.getTo());
helper.setSubject(simpleMailMessage.getSubject());
helper.setText(String.format(
simpleMailMessage.getText(), dear, content));
FileSystemResource file = new FileSystemResource("/home/abdennour/Documents/cv.pdf");
helper.addAttachment(file.getFilename(), file);
}catch (MessagingException e) {
throw new MailParseException(e);
}
mailSender.send(message);
}
}
To know how to configure your project to deal with this code , complete reading this tutorial .
Enum Naming Convention - Plural
The situation never really applies to plural.
An enum
shows an attribute of something or another. I'll give an example:
enum Humour
{
Irony,
Sarcasm,
Slapstick,
Nothing
}
You can have one type, but try think of it in the multiple, rather than plural:
Humour.Irony | Humour.Sarcasm
Rather than
Humours { Irony, Sarcasm }
You have a sense of humour, you don't have a sense of humours.
Scanner method to get a char
You can use the Console API (which made its appearance in Java 6) as follows:
Console cons = System.console();
if(cons != null) {
char c = (char) cons.reader().read(); // Checking for EOF omitted
...
}
If you just need a single line you don't even need to go through the reader object:
String s = cons.readLine();
What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?
There is probably another table with a foreign key referencing the primary key you are trying to change.
To find out which table caused the error you can run SHOW ENGINE INNODB
STATUS
and then look at the LATEST FOREIGN KEY ERROR
section
Use SHOW CREATE TABLE categories to show the name of constraint.
Most probably it will be categories_ibfk_1
Use the name to drop the foreign key first and the column then:
ALTER TABLE categories DROP FOREIGN KEY categories_ibfk_1;
ALTER TABLE categories DROP COLUMN assets_id;
Do while loop in SQL Server 2008
I seem to recall reading this article more than once, and the answer is only close to what I need.
Usually when I think I'm going to need a DO WHILE
in T-SQL it's because I'm iterating a cursor, and I'm looking largely for optimal clarity (vs. optimal speed). In T-SQL that seems to fit a WHILE TRUE
/ IF BREAK
.
If that's the scenario that brought you here, this snippet may save you a moment. Otherwise, welcome back, me. Now I can be certain I've been here more than once. :)
DECLARE Id INT, @Title VARCHAR(50)
DECLARE Iterator CURSOR FORWARD_ONLY FOR
SELECT Id, Title FROM dbo.SourceTable
OPEN Iterator
WHILE 1=1 BEGIN
FETCH NEXT FROM @InputTable INTO @Id, @Title
IF @@FETCH_STATUS < 0 BREAK
PRINT 'Do something with ' + @Title
END
CLOSE Iterator
DEALLOCATE Iterator
Unfortunately, T-SQL doesn't seem to offer a cleaner way to singly-define the loop operation, than this infinite loop.
Getting path relative to the current working directory?
Thanks to the other answers here and after some experimentation I've created some very useful extension methods:
public static string GetRelativePathFrom(this FileSystemInfo to, FileSystemInfo from)
{
return from.GetRelativePathTo(to);
}
public static string GetRelativePathTo(this FileSystemInfo from, FileSystemInfo to)
{
Func<FileSystemInfo, string> getPath = fsi =>
{
var d = fsi as DirectoryInfo;
return d == null ? fsi.FullName : d.FullName.TrimEnd('\\') + "\\";
};
var fromPath = getPath(from);
var toPath = getPath(to);
var fromUri = new Uri(fromPath);
var toUri = new Uri(toPath);
var relativeUri = fromUri.MakeRelativeUri(toUri);
var relativePath = Uri.UnescapeDataString(relativeUri.ToString());
return relativePath.Replace('/', Path.DirectorySeparatorChar);
}
Important points:
- Use
FileInfo
and DirectoryInfo
as method parameters so there is no ambiguity as to what is being worked with. Uri.MakeRelativeUri
expects directories to end with a trailing slash.
DirectoryInfo.FullName
doesn't normalize the trailing slash. It outputs whatever path was used in the constructor. This extension method takes care of that for you.
What is the python keyword "with" used for?
In python the with
keyword is used when working with unmanaged resources (like file streams). It is similar to the using
statement in VB.NET and C#. It allows you to ensure that a resource is "cleaned up" when the code that uses it finishes running, even if exceptions are thrown. It provides 'syntactic sugar' for try/finally
blocks.
From Python Docs:
The with
statement clarifies code that previously would use try...finally
blocks to ensure that clean-up code is executed. In this section, I’ll discuss the statement as it will commonly be used. In the next section, I’ll examine the implementation details and show how to write objects for use with this statement.
The with
statement is a control-flow structure whose basic structure is:
with expression [as variable]:
with-block
The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has __enter__()
and __exit__()
methods).
Update fixed VB callout per Scott Wisniewski's comment. I was indeed confusing with
with using
.
Remove leading or trailing spaces in an entire column of data
Quite often the issue is a non-breaking space - CHAR(160)
- especially from Web text sources -that CLEAN
can't remove, so I would go a step further than this and try a formula like this which replaces any non-breaking spaces with a standard one
=TRIM(CLEAN(SUBSTITUTE(A1,CHAR(160)," ")))
Ron de Bruin has an excellent post on tips for cleaning data here
You can also remove the CHAR(160)
directly without a workaround formula by
- Edit .... Replace your selected data,
- in Find What hold
ALT
and type 0160
using the numeric keypad
- Leave Replace With as blank and select Replace All
How to loop through file names returned by find?
You can store your find
output in array if you wish to use the output later as:
array=($(find . -name "*.txt"))
Now to print the each element in new line, you can either use for
loop iterating to all the elements of array, or you can use printf statement.
for i in ${array[@]};do echo $i; done
or
printf '%s\n' "${array[@]}"
You can also use:
for file in "`find . -name "*.txt"`"; do echo "$file"; done
This will print each filename in newline
To only print the find
output in list form, you can use either of the following:
find . -name "*.txt" -print 2>/dev/null
or
find . -name "*.txt" -print | grep -v 'Permission denied'
This will remove error messages and only give the filename as output in new line.
If you wish to do something with the filenames, storing it in array is good, else there is no need to consume that space and you can directly print the output from find
.
Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'
For me changing compile to implementation fixed it
Before
compile 'androidx.recyclerview:recyclerview:1.0.0'
compile 'androidx.cardview:cardview:1.0.0'
//Retrofit Dependencies
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
After
implementation 'androidx.recyclerview:recyclerview:1.0.0'
implementation 'androidx.cardview:cardview:1.0.0'
//Retrofit Dependencies
implementation 'com.squareup.retrofit2:retrofit:2.1.0'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
Append lines to a file using a StreamWriter
I assume you are executing all of the above code each time you write something to the file. Each time the stream for the file is opened, its seek pointer is positioned at the beginning so all writes end up overwriting what was there before.
You can solve the problem in two ways: either with the convenient
file2 = new StreamWriter("c:/file.txt", true);
or by explicitly repositioning the stream pointer yourself:
file2 = new StreamWriter("c:/file.txt");
file2.BaseStream.Seek(0, SeekOrigin.End);
Where's my invalid character (ORA-00911)
If you use the string literal exactly as you have shown us, the problem is the ;
character at the end. You may not include that in the query string in the JDBC calls.
As you are inserting only a single row, a regular INSERT
should be just fine even when inserting multiple rows. Using a batched statement is probable more efficient anywy. No need for INSERT ALL
. Additionally you don't need the temporary clob and all that. You can simplify your method to something like this (assuming I got the parameters right):
String query1 = "select substr(to_char(max_data),1,4) as year, " +
"substr(to_char(max_data),5,6) as month, max_data " +
"from dss_fin_user.acq_dashboard_src_load_success " +
"where source = 'CHQ PeopleSoft FS'";
String query2 = ".....";
String sql = "insert into domo_queries (clob_column) values (?)";
PreparedStatement pstmt = con.prepareStatement(sql);
StringReader reader = new StringReader(query1);
pstmt.setCharacterStream(1, reader, query1.length());
pstmt.addBatch();
reader = new StringReader(query2);
pstmt.setCharacterStream(1, reader, query2.length());
pstmt.addBatch();
pstmt.executeBatch();
con.commit();
How to build and fill pandas dataframe from for loop?
I may be wrong, but I think the accepted answer by @amit has a bug.
from pandas import DataFrame as df
x = [1,2,3]
y = [7,8,9,10]
# this gives me a syntax error at 'for' (Python 3.7)
d1 = df[[a, "A", b, "B"] for a in x for b in y]
# this works
d2 = df([a, "A", b, "B"] for a in x for b in y)
# and if you want to add the column names on the fly
# note the additional parentheses
d3 = df(([a, "A", b, "B"] for a in x for b in y), columns = ("l","m","n","o"))
Attempted to read or write protected memory. This is often an indication that other memory is corrupt
Verifiable code should not be able to corrupt memory, so there's something unsafe going on. Are you using any unsafe code anywhere, such as in buffer processing? Also, the stuff about PInvoke may not be irrelevant, as PInvoke involves a transition to unmanaged code and associated marshaling.
My best recommendation is to attach to a crashed instance and use WinDBG and SOS to dig deeper into what's happening at the time of the crash. This is not for the faint of heart, but at this point you may need to break out more powerful tools to determine what, exactly, is going wrong.
Selenium wait until document is ready
In Java it will like below :-
private static boolean isloadComplete(WebDriver driver)
{
return ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("loaded")
|| ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete");
}
mysqldump with create database line
By default mysqldump
always creates the CREATE DATABASE IF NOT EXISTS db_name;
statement at the beginning of the dump file.
[EDIT] Few things about the mysqldump
file and it's options:
--all-databases
, -A
Dump all tables in all databases. This is the same as using the --databases
option and naming all the databases on the command line.
--add-drop-database
Add a DROP DATABASE
statement before each CREATE DATABASE
statement. This option is typically used in conjunction with the --all-databases
or --databases
option because no CREATE DATABASE
statements are written unless one of those options is specified.
--databases
, -B
Dump several databases. Normally, mysqldump
treats the first name argument on the command line as a database name and following names as table names. With this option, it treats all name arguments as database names. CREATE DATABASE
and USE
statements are included in the output before each new database.
--no-create-db
, -n
This option suppresses the CREATE DATABASE
statements that are otherwise included in the output if the --databases
or --all-databases
option is given.
Some time ago, there was similar question actually asking about not having such statement on the beginning of the file (for XML file). Link to that question is here.
So to answer your question:
- if you have one database to dump, you should have the
--add-drop-database
option in your mysqldump
statement.
- if you have multiple databases to dump, you should use the option
--databases
or --all-databases
and the CREATE DATABASE
syntax will be added
automatically
More information at MySQL Reference Manual
How to delete mysql database through shell command
If you are tired of typing your password, create a (chmod 600) file ~/.my.cnf
, and put in it:
[client]
user = "you"
password = "your-password"
For the sake of conversation:
echo 'DROP DATABASE foo;' | mysql
Javascript switch vs. if...else if...else
- If there is a difference, it'll never be large enough to be noticed.
- N/A
- No, they all function identically.
Basically, use whatever makes the code most readable. There are definitely places where one or the other constructs makes for cleaner, more readable and more maintainable. This is far more important that perhaps saving a few nanoseconds in JavaScript code.
Finding length of char array
sizeof
returns the size of the type of the variable in bytes. So in your case it's returning the size of your char[7]
which is 7 * sizeof(char)
. Since sizeof(char) = 1
, the result is 7.
Expanding this to another example:
int intArr[5];
printf("sizeof(intArr)=%u", sizeof(intArr));
would yield 5 * sizeof(int)
, so you'd get the result "20" (At least on a regular 32bit platform. On others sizeof(int)
might differ)
To return to your problem:
It seems like, that what you want to know is the length of the string which is contained
inside your array and not the total array size.
By definition C-Strings have to be terminated with a trailing '\0' (0-Byte).
So to get the appropriate length of the string contained within your array, you have
to first terminate the string, so that you can tell when it's finished. Otherwise there would be now way to know.
All standard functions build upon this definition, so if you call strlen
to retrieve
the str ing len gth, it will iterate through the given array until it finds the first 0-byte, which in your case would be the very first element.
Another thing you might need to know that only because you don't fill the remaining elements of your char[7]
with a value, they actually do contain random undefined values.
Hope that helped.
How to check if a database exists in SQL Server?
TRY THIS
IF EXISTS
(
SELECT name FROM master.dbo.sysdatabases
WHERE name = N'New_Database'
)
BEGIN
SELECT 'Database Name already Exist' AS Message
END
ELSE
BEGIN
CREATE DATABASE [New_Database]
SELECT 'New Database is Created'
END
How do the major C# DI/IoC frameworks compare?
I came across another performance comparison(latest update 10 April 2014). It compares the following:
Here is a quick summary from the post:
Conclusion
Ninject is definitely the slowest container.
MEF, LinFu and Spring.NET are faster than Ninject, but still pretty
slow. AutoFac, Catel and Windsor come next, followed by StructureMap,
Unity and LightCore. A disadvantage of Spring.NET is, that can only be
configured with XML.
SimpleInjector, Hiro, Funq, Munq and Dynamo offer the best
performance, they are extremely fast. Give them a try!
Especially Simple Injector seems to be a good choice. It's very fast, has a good
documentation and also supports advanced scenarios like interception
and generic decorators.
You can also try using the Common Service Selector Library and hopefully try multiple options and see what works best for you.
Some informtion about Common Service Selector Library from the site:
The library provides an abstraction over IoC containers and service
locators. Using the library allows an application to indirectly access
the capabilities without relying on hard references. The hope is that
using this library, third-party applications and frameworks can begin
to leverage IoC/Service Location without tying themselves down to a
specific implementation.
Update
13.09.2011: Funq and Munq were added to the list of contestants. The charts were also updated, and Spring.NET was removed due to it's poor performance.
04.11.2011: "added Simple Injector, the performance is the best of all contestants".
Internet Explorer cache location
If you want to find the folder in a platform independent way, you should query the registry key:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Cache
Number of times a particular character appears in a string
function for sql server:
CREATE function NTSGetCinC(@Cadena nvarchar(4000), @UnChar nvarchar(100))
Returns int
as
begin
declare @t1 int
declare @t2 int
declare @t3 int
set @t1 = len(@Cadena)
set @t2 = len(replace(@Cadena,@UnChar,''))
set @t3 = len(@UnChar)
return (@t1 - @t2) / @t3
end
Code for visual basic and others:
Public Function NTSCuentaChars(Texto As String, CharAContar As String) As Long
NTSCuentaChars = (Len(Texto) - Len(Replace(Texto, CharAContar, ""))) / Len(CharAContar)
End Function
IIS7 URL Redirection from root to sub directory
I could not get this working with the accepted answer, mainly because I did not know where to enter that code. I looked everywhere for some explanation of the URL Rewrite tool that made sense, but could not find any. I ended up using the HTTP Redirect tool in IIS.
- Choose your site
- Click HTTP Redirect in the IIS section (Make sure the Role Service is installed)
- Check "Redirect requests to this destination"
- Enter where you want to redirect. In your case "wwww.mysite.com/menu_1/MainScreen.aspx"
- In Redirect Behavior, I found I had to check "Only redirect requests to content in this directory (not subdirectories), or it would go into a loop. See what works for you.
Hope this helps.
CASE statement in SQLite query
The syntax is wrong in this clause (and similar ones)
CASE lkey WHEN lkey > 5 THEN
lkey + 2
ELSE
lkey
END
It's either
CASE WHEN [condition] THEN [expression] ELSE [expression] END
or
CASE [expression] WHEN [value] THEN [expression] ELSE [expression] END
So in your case it would read:
CASE WHEN lkey > 5 THEN
lkey + 2
ELSE
lkey
END
Check out the documentation (The CASE expression):
http://www.sqlite.org/lang_expr.html
Get file content from URL?
Depending on your PHP configuration, this may be a easy as using:
$jsonData = json_decode(file_get_contents('https://chart.googleapis.com/chart?cht=p3&chs=250x100&chd=t:60,40&chl=Hello|World&chof=json'));
However, if allow_url_fopen
isn't enabled on your system, you could read the data via CURL as follows:
<?php
$curlSession = curl_init();
curl_setopt($curlSession, CURLOPT_URL, 'https://chart.googleapis.com/chart?cht=p3&chs=250x100&chd=t:60,40&chl=Hello|World&chof=json');
curl_setopt($curlSession, CURLOPT_BINARYTRANSFER, true);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);
$jsonData = json_decode(curl_exec($curlSession));
curl_close($curlSession);
?>
Incidentally, if you just want the raw JSON data, then simply remove the json_decode
.
Progress Bar with HTML and CSS
If you wish to have a progress bar without adding some code PACE can be an awesome tool for you.
Just include pace.js and a CSS theme of your choice, and you get a beautiful progress indicator for your page load and AJAX navigation. Best thing with PACE is the auto detection of progress.
It contains various themes and color schemes as well.
Worth a try.
How to destroy an object?
A handy post explaining several mis-understandings about this:
Don't Call The Destructor explicitly
This covers several misconceptions about how the destructor works. Calling it explicitly will not actually destroy your variable, according to the PHP5 doc:
PHP 5 introduces a destructor concept similar to that of other
object-oriented languages, such as C++. The destructor method will be
called as soon as there are no other references to a particular
object, or in any order during the shutdown sequence.
The post above does state that setting the variable to null can work in some cases, as long as nothing else is pointing to the allocated memory.
OWIN Startup Class Missing
In our project, we didn't need the OWIN functionality, so we removed all the owin references from the initial ASP.NET MVC template project. The problem occured after removing the OWIN startup class.
The problem was the extra owin dll's in my bin folder. When I deleted them, the problem was resolved. You should delete them by deleting the bin folder. Clean Solution does not delete these dlls.
Somehow, IIS still executes the OWIN dll's when they are in the bin folder.
Limit number of characters allowed in form input text field
<input type="text" name="MobileNumber" id="MobileNumber" maxlength="10" onkeypress="checkNumber(event);" placeholder="MobileNumber">
<script>
function checkNumber(key) {
console.log(key);
var inputNumber = document.querySelector("#MobileNumber").value;
if(key.key >= 0 && key.key <= 9) {
inputNumber += key.key;
}
else {
key.preventDefault();
}
}
</script>
XCOPY switch to create specified directory if it doesn't exist?
I tried this on the command line using
D:\>xcopy myfile.dat xcopytest\test\
and the target directory was properly created.
If not you can create the target dir using the mkdir
command with cmd
's command extensions enabled like
cmd /x /c mkdir "$(SolutionDir)Prism4Demo.Shell\$(OutDir)Modules\"
('/x' enables command extensions in case they're not enabled by default on your system, I'm not that familiar with cmd
)
use
cmd /?
mkdir /?
xcopy /?
for further information :)
Java Date cut off time information
It really annoyed me that the new "improved" calendar constructor doesn't take an int for milliseconds like the "awful" old Date one.
I then got really cross and wrote this:
long stuffYou = startTime.getTimeInMillis() % 1000;
startTime.setTimeInMillis(startTime.getTimeInMillis() - stuffYou);
I didn't use the word "stuff" at the time, but
then I discovered the happiness of this:
startTime.set(Calendar.MILLISECOND, 0);
But I'm still quite cross about it.
Can the :not() pseudo-class have multiple arguments?
Starting from CSS Selectors 4 using multiple arguments in the :not
selector becomes possible (see here).
In CSS3, the :not selector only allows 1 selector as an argument. In level 4 selectors, it can take a selector list as an argument.
Example:
/* In this example, all p elements will be red, except for
the first child and the ones with the class special. */
p:not(:first-child, .special) {
color: red;
}
Unfortunately, browser support is limited. For now, it only works in Safari.
aspx page to redirect to a new page
Darin's answer works great. It creates a 302 redirect. Here's the code modified so that it creates a permanent 301 redirect:
<%@ Page Language="C#" %>
<script runat="server">
protected override void OnLoad(EventArgs e)
{
Response.RedirectPermanent("new.aspx");
base.OnLoad(e);
}
</script>
How to "fadeOut" & "remove" a div in jQuery?
If you're using it in several different places, you should turn it into a plugin.
jQuery.fn.fadeOutAndRemove = function(speed){
$(this).fadeOut(speed,function(){
$(this).remove();
})
}
And then:
// Somewhere in the program code.
$('div').fadeOutAndRemove('fast');
Swift - Remove " character from string
If you are getting the output Optional(5) when trying to print the value of 5 in an optional Int or String, you should unwrap the value first:
if value != nil
{ print(value)
}
or you can use this:
if let value = text {
print(value)
}
or in simple just 1 line answer:
print(value ?? "")
The last line will check if variable 'value' has any value assigned to it, if not it will print empty string
First char to upper case
Regular Expressions (abbreviated "regex" or "reg-ex") is a string that defines a search pattern.
What replaceFirst()
does is it uses the regular expression provided in the parameters and replaces the first result from the search with whatever you pass in as the other parameter.
What you want to do is convert the string to an array using the String
class' charAt()
method, and then use Character.toUpperCase()
to change the character to upper case (obviously). Your code would look like this:
char first = Character.toUpperCase(userIdea.charAt(0));
betterIdea = first + userIdea.substring(1);
Or, if you feel comfortable with more complex, one-lined java code:
betterIdea = Character.toUpperCase(userIdea.charAt(0)) + userIdea.substring(1);
Both of these do the same thing, which is converting the first character of userIdea
to an upper case character.
Image Greyscale with CSS & re-color on mouse-over?
Answered here: Convert an image to grayscale in HTML/CSS
You don't even need to use two images which sounds like a pain or an image manipulation library, you can do it with cross browser support (current versions) and just use CSS. This is a progressive enhancement approach which just falls back to color versions on older browsers:
img {
filter: url(filters.svg#grayscale);
/* Firefox 3.5+ */
filter: gray;
/* IE6-9 */
-webkit-filter: grayscale(1);
/* Google Chrome & Safari 6+ */
}
img:hover {
filter: none;
-webkit-filter: none;
}
and filters.svg file like this:
<svg xmlns="http://www.w3.org/2000/svg">
<filter id="grayscale">
<feColorMatrix type="matrix" values="0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0" />
</filter>
</svg>
Creating a SearchView that looks like the material design guidelines
Here's my attempt at doing this:
Step 1: Create a style named SearchViewStyle
<style name="SearchViewStyle" parent="Widget.AppCompat.SearchView">
<!-- Gets rid of the search icon -->
<item name="searchIcon">@drawable/search</item>
<!-- Gets rid of the "underline" in the text -->
<item name="queryBackground">@null</item>
<!-- Gets rid of the search icon when the SearchView is expanded -->
<item name="searchHintIcon">@null</item>
<!-- The hint text that appears when the user has not typed anything -->
<item name="queryHint">@string/search_hint</item>
</style>
Step 2: Create a layout named simple_search_view_item.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.SearchView
android:layout_gravity="end"
android:layout_height="wrap_content"
android:layout_width="match_parent"
style="@style/SearchViewStyle"
xmlns:android="http://schemas.android.com/apk/res/android" />
Step 3: Create a menu item for this search view
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
app:actionLayout="@layout/simple_search_view_item"
android:title="@string/search"
android:icon="@drawable/search"
app:showAsAction="always" />
</menu>
Step 4: Inflate the menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_searchable_activity, menu);
return true;
}
Result:
The only thing I wasn't able to do was to make it fill the entire width of the Toolbar
. If someone could help me do that then that'd be golden.
jQuery show/hide not working
Demo
_x000D_
_x000D_
$( '.expand' ).click(function() {_x000D_
$( '.img_display_content' ).toggle();_x000D_
});
_x000D_
.wrap {_x000D_
margin-left:auto;_x000D_
margin-right:auto;_x000D_
width:40%;_x000D_
}_x000D_
_x000D_
.img_display_header {_x000D_
height:20px;_x000D_
background-color:#CCC;_x000D_
display:block;_x000D_
border:#333 solid 1px;_x000D_
margin-bottom: 2px;_x000D_
}_x000D_
_x000D_
.expand {_x000D_
float:right;_x000D_
height: 100%;_x000D_
padding-right:5px;_x000D_
cursor:pointer;_x000D_
}_x000D_
_x000D_
.img_display_content {_x000D_
width: 100%;_x000D_
height:100px; _x000D_
background-color:#0F3;_x000D_
margin-top: -2px;_x000D_
display:none;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="wrap">_x000D_
<div class="img_display_header">_x000D_
<div class="expand">+</div>_x000D_
</div>_x000D_
<div class="img_display_content"></div>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
http://api.jquery.com/toggle/
"Display or hide the matched elements."
This is much shorter in code than using show() and hide() methods.
Why use a ReentrantLock if one can use synchronized(this)?
Synchronized locks does not offer any mechanism of waiting queue in which after the execution of one thread any thread running in parallel can acquire the lock. Due to which the thread which is there in the system and running for a longer period of time never gets chance to access the shared resource thus leading to starvation.
Reentrant locks are very much flexible and has a fairness policy in which if a thread is waiting for a longer time and after the completion of the currently executing thread we can make sure that the longer waiting thread gets the chance of accessing the shared resource hereby decreasing the throughput of the system and making it more time consuming.
How do I pass a URL with multiple parameters into a URL?
In your example parts of your passed-in URL are not URL encoded (for example the colon should be %3A, the forward slashes should be %2F). It looks like you have encoded the parameters to your parameter URL, but not the parameter URL itself. Try encoding it as well. You can use encodeURIComponent
.
How do I pass multiple parameters in Objective-C?
Objective-C doesn't have named parameters, so everything on the left side of a colon is part of the method name. For example,
getBusStops: forTime:
is the name of the method. The name is broken up so it can be more descriptive. You could simply name your method
getBusStops: :
but that doesn't tell you much about the second parameter.
jQuery Validation plugin: validate check box
You had several issues with your code.
1) Missing a closing brace, }
, within your rules
.
2) In this case, there is no reason to use a function for the required
rule. By default, the plugin can handle checkbox
and radio
inputs just fine, so using true
is enough. However, this will simply do the same logic as in your original function and verify that at least one is checked.
3) If you also want only a maximum of two to be checked, then you'll need to apply the maxlength
rule.
4) The messages
option was missing the rule specification. It will work, but the one custom message would apply to all rules on the same field.
5) If a name
attribute contains brackets, you must enclose it within quotes.
DEMO: http://jsfiddle.net/K6Wvk/
$(document).ready(function () {
$('#formid').validate({ // initialize the plugin
rules: {
'test[]': {
required: true,
maxlength: 2
}
},
messages: {
'test[]': {
required: "You must check at least 1 box",
maxlength: "Check no more than {0} boxes"
}
}
});
});
Detect if a Form Control option button is selected in VBA
If you are using a Form Control
, you can get the same property as ActiveX
by using OLEFormat.Object
property of the Shape Object
. Better yet assign it in a variable declared as OptionButton to get the Intellisense kick in.
Dim opt As OptionButton
With Sheets("Sheet1") ' Try to be always explicit
Set opt = .Shapes("Option Button 1").OLEFormat.Object ' Form Control
Debug.Pring opt.Value ' returns 1 (true) or -4146 (false)
End With
But then again, you really don't need to know the value.
If you use Form Control
, you associate a Macro
or sub routine with it which is executed when it is selected. So you just need to set up a sub routine that identifies which button is clicked and then execute a corresponding action for it.
For example you have 2 Form Control
Option Buttons.
Sub CheckOptions()
Select Case Application.Caller
Case "Option Button 1"
' Action for option button 1
Case "Option Button 2"
' Action for option button 2
End Select
End Sub
In above code, you have only one sub routine assigned to both option buttons.
Then you test which called the sub routine by checking Application.Caller
.
This way, no need to check whether the option button value is true or false.
Android: Cancel Async Task
I had a similar problem - essentially I was getting a NPE in an async task after the user had destroyed the activity. After researching the problem on Stack Overflow, I adopted the following solution:
volatile boolean running;
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
running=true;
...
}
public void onDestroy() {
super.onDestroy();
running=false;
...
}
Then, I check "if running" periodically in my async code. I have stress tested this and I am now unable to "break" my activity. This works perfectly and has the advantage of being simpler than some of the solutions I have seen on SO.
How to set null to a GUID property
Choose your poison - if you can't change the type of the property to be nullable then you're going to have to use a "magic" value to represent NULL. Guid.Empty
seems as good as any unless you have some specific reason for not wanting to use it. A second choice would be Guid.Parse("ffffffff-ffff-ffff-ffff-ffffffffffff")
but that's a lot uglier IMHO.
Hibernate Criteria Restrictions AND / OR combination
For the new Criteria since version Hibernate 5.2:
CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<SomeClass> criteriaQuery = criteriaBuilder.createQuery(SomeClass.class);
Root<SomeClass> root = criteriaQuery.from(SomeClass.class);
Path<Object> expressionA = root.get("A");
Path<Object> expressionB = root.get("B");
Predicate predicateAEqualX = criteriaBuilder.equal(expressionA, "X");
Predicate predicateBInXY = expressionB.in("X",Y);
Predicate predicateLeft = criteriaBuilder.and(predicateAEqualX, predicateBInXY);
Predicate predicateAEqualY = criteriaBuilder.equal(expressionA, Y);
Predicate predicateBEqualZ = criteriaBuilder.equal(expressionB, "Z");
Predicate predicateRight = criteriaBuilder.and(predicateAEqualY, predicateBEqualZ);
Predicate predicateResult = criteriaBuilder.or(predicateLeft, predicateRight);
criteriaQuery
.select(root)
.where(predicateResult);
List<SomeClass> list = getSession()
.createQuery(criteriaQuery)
.getResultList();
making a paragraph in html contain a text from a file
You can do something like that in pure html using an <object>
tag:
<div><object data="file.txt"></object></div>
This method has some limitations though, like, it won't fit size of the block to the content - you have to specify width
and height
manually. And styles won't be applied to the text.
How to add jQuery code into HTML Page
I would recommend to call the script like this
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="/js/my.js"></script>
</body>
The js and css files must be treat differently
Put jquery
as the first before other JS scripts
at the bottom of <BODY>
tag
- The problem caused is that they block parallel downloads. The
HTTP/1.1 specification
suggests that browsers download no more than two components in parallel per hostname.
- So select 2 (two) most important scripts on your page like analytic and pixel script on the
<head>
tags and let the rest including the jquery
to be called on the bottom <body>
tag.
Put CSS style
on top of <HEAD>
tag after the other more priority tags
- Moving style sheets to the document
HEAD
makes pages appear to be loading faster. This is because putting style sheets in the HEAD
allows the page to render progressively.
- So for
css
sheets, it is better to put them all on the <head>
tag but let the style that shall be immediately rendered to be put in <style>
tags inside <HEAD>
and the rest in <body>
.
You may also find other suggestion when you test your page like on Google PageSpeed Insight
How do I fetch only one branch of a remote Git repository?
One way to do it:
in .git/config fetch for the remote repo should be set to fetch any branch:
[remote "origin"]
fetch = +refs/heads/*:refs/remotes/origin/*
to fetch the remote branch:
git fetch origin branch-name
to create a local branch 'branch-name' set up to track remote branch 'branch-name' from origin.
git checkout -b branch-name origin/branch-name
to list all branches
git branch -a
JavaScript validation for empty input field
_x000D_
_x000D_
<script type="text/javascript">_x000D_
function validateForm() {_x000D_
var a = document.forms["Form"]["answer_a"].value;_x000D_
var b = document.forms["Form"]["answer_b"].value;_x000D_
var c = document.forms["Form"]["answer_c"].value;_x000D_
var d = document.forms["Form"]["answer_d"].value;_x000D_
if (a == null || a == "", b == null || b == "", c == null || c == "", d == null || d == "") {_x000D_
alert("Please Fill All Required Field");_x000D_
return false;_x000D_
}_x000D_
}_x000D_
</script>_x000D_
_x000D_
<form method="post" name="Form" onsubmit="return validateForm()" action="">_x000D_
<textarea cols="30" rows="2" name="answer_a" id="a"></textarea>_x000D_
<textarea cols="30" rows="2" name="answer_b" id="b"></textarea>_x000D_
<textarea cols="30" rows="2" name="answer_c" id="c"></textarea>_x000D_
<textarea cols="30" rows="2" name="answer_d" id="d"></textarea>_x000D_
</form>
_x000D_
_x000D_
_x000D_
SQL Server : fetching records between two dates?
The unambiguous way to write this is (i.e. increase the 2nd date by 1 and make it <
)
select *
from xxx
where dates >= '20121026'
and dates < '20121028'
If you're using SQL Server 2008 or above, you can safety CAST as DATE while retaining SARGability, e.g.
select *
from xxx
where CAST(dates as DATE) between '20121026' and '20121027'
This explicitly tells SQL Server that you are only interested in the DATE portion of the dates
column for comparison against the BETWEEN range.
SQL Query for Student mark functionality
I like the simple solution using windows functions:
select t.*
from (select student.*, su.subname, max(mark) over (partition by subid) as maxmark
from marks m join
students st
on m.stid = st.stid join
subject su
on m.subid = su.subid
) t
where t.mark = maxmark
Or, alternatively:
select t.*
from (select student.*, su.subname, rank(mark) over (partition by subid order by mark desc) as markseqnum
from marks m join
students st
on m.stid = st.stid join
subject su
on m.subid = su.subid
) t
where markseqnum = 1
Python CSV error: line contains NULL byte
As @S.Lott says, you should be opening your files in 'rb' mode, not 'rU' mode. However that may NOT be causing your current problem. As far as I know, using 'rU' mode would mess you up if there are embedded \r
in the data, but not cause any other dramas. I also note that you have several files (all opened with 'rU' ??) but only one causing a problem.
If the csv module says that you have a "NULL" (silly message, should be "NUL") byte in your file, then you need to check out what is in your file. I would suggest that you do this even if using 'rb' makes the problem go away.
repr()
is (or wants to be) your debugging friend. It will show unambiguously what you've got, in a platform independant fashion (which is helpful to helpers who are unaware what od
is or does). Do this:
print repr(open('my.csv', 'rb').read(200)) # dump 1st 200 bytes of file
and carefully copy/paste (don't retype) the result into an edit of your question (not into a comment).
Also note that if the file is really dodgy e.g. no \r or \n within reasonable distance from the start of the file, the line number reported by reader.line_num
will be (unhelpfully) 1. Find where the first \x00
is (if any) by doing
data = open('my.csv', 'rb').read()
print data.find('\x00')
and make sure that you dump at least that many bytes with repr or od.
What does data.count('\x00')
tell you? If there are many, you may want to do something like
for i, c in enumerate(data):
if c == '\x00':
print i, repr(data[i-30:i]) + ' *NUL* ' + repr(data[i+1:i+31])
so that you can see the NUL bytes in context.
If you can see \x00
in the output (or \0
in your od -c
output), then you definitely have NUL byte(s) in the file, and you will need to do something like this:
fi = open('my.csv', 'rb')
data = fi.read()
fi.close()
fo = open('mynew.csv', 'wb')
fo.write(data.replace('\x00', ''))
fo.close()
By the way, have you looked at the file (including the last few lines) with a text editor? Does it actually look like a reasonable CSV file like the other (no "NULL byte" exception) files?
How do I create a new branch?
My solution if you work with the Trunk/
and Release/
workflow:
Right click on Trunk/
which you will be creating your Branch from:
Select Branch/Tag:
Type in location of your new branch, commit message, and any externals (if your repository has them):
How do I use popover from Twitter Bootstrap to display an image?
Sort of similar to what mattbtay said, but a few changes. needed html:true.
Put this script on bottom of the page towards close body tag.
<script type="text/javascript">
$(document).ready(function() {
$("[rel=drevil]").popover({
placement : 'bottom', //placement of the popover. also can use top, bottom, left or right
title : '<div style="text-align:center; color:red; text-decoration:underline; font-size:14px;"> Muah ha ha</div>', //this is the top title bar of the popover. add some basic css
html: 'true', //needed to show html of course
content : '<div id="popOverBox"><img src="http://www.hd-report.com/wp-content/uploads/2008/08/mr-evil.jpg" width="251" height="201" /></div>' //this is the content of the html box. add the image here or anything you want really.
});
});
</script>
Then HTML is:
<a href="#" rel="drevil">mischief</a>
Find unique lines
uniq -u has been driving me crazy because it did not work.
So instead of that, if you have python (most Linux distros and servers already have it):
Assuming you have the data file in notUnique.txt
#Python
#Assuming file has data on different lines
#Otherwise fix split() accordingly.
uniqueData = []
fileData = open('notUnique.txt').read().split('\n')
for i in fileData:
if i.strip()!='':
uniqueData.append(i)
print uniqueData
###Another option (less keystrokes):
set(open('notUnique.txt').read().split('\n'))
Note that due to empty lines, the final set may contain '' or only-space strings. You can remove that later. Or just get away with copying from the terminal ;)
#
Just FYI, From the uniq Man page:
"Note: 'uniq' does not detect repeated lines unless they are adjacent. You may want to sort the input first, or use 'sort -u' without 'uniq'. Also, comparisons honor the rules specified by 'LC_COLLATE'."
One of the correct ways, to invoke with:
#
sort nonUnique.txt | uniq
Example run:
$ cat x
3
1
2
2
2
3
1
3
$ uniq x
3
1
2
3
1
3
$ uniq -u x
3
1
3
1
3
$ sort x | uniq
1
2
3
Spaces might be printed, so be prepared!
Good way of getting the user's location in Android
I scoured the internet for an updated (past year) answer using the latest location pulling methods suggested by google (to use FusedLocationProviderClient). I finally landed on this:
https://github.com/googlesamples/android-play-location/tree/master/LocationUpdates
I created a new project and copied in most of this code. Boom. It works. And I think without any deprecated lines.
Also, the simulator doesn't seem to get a GPS location, that I know of. It did get as far as reporting this in the log: "All location settings are satisfied."
And finally, in case you wanted to know (I did), you DO NOT need a google maps api key from the google developer console, if all you want is the GPS location.
Also useful is their tutorial. But I wanted a full one page tutorial/code example, and that. Their tutorial stacks but is confusing when you're new to this because you don't know what pieces you need from earlier pages.
https://developer.android.com/training/location/index.html
And finally, remember things like this:
I not only had to modify the mainActivity.Java. I also had to modify Strings.xml, androidmanifest.xml, AND the correct build.gradle. And also your activity_Main.xml (but that part was easy for me).
I needed to add dependencies like this one: implementation 'com.google.android.gms:play-services-location:11.8.0', and update the settings of my android studio SDK to include google play services. (file settings appearance system settings android SDK SDK Tools check google play services).
update: the android simulator did seem to get a location and location change events (when I changed the value in the settings of the sim). But my best and first results were on an actual device. So it's probably easiest to test on actual devices.
response.sendRedirect() from Servlet to JSP does not seem to work
I'm posting this answer because the one with the most votes led me astray. To redirect from a servlet, you simply do this:
response.sendRedirect("simpleList.do")
In this particular question, I think @M-D is correctly explaining why the asker is having his problem, but since this is the first result on google when you search for "Redirect from Servlet" I think it's important to have an answer that helps most people, not just the original asker.
Swift Error: Editor placeholder in source file
If you have this error while you create segues with the view controllers not with the UI elements you have to change sender: Any?
to this
@IBAction func backButtonPressed(_ sender: Any) {
performSegue(withIdentifier: "goToMainScreen", sender: self)
}
It will work.
How to remove unused dependencies from composer?
In fact, it is very easy.
composer update
will do all this for you, but it will also update the other packages.
To remove a package without updating the others, specifiy that package in the command, for instance:
composer update monolog/monolog
will remove the monolog/monolog
package.
Nevertheless, there may remain some empty folders or files that cannot be removed automatically, and that have to be removed manually.
What causes this error? "Runtime error 380: Invalid property value"
Looks like the answers above are for when you are writing and compiling a program, but I'm using a Vendor's software, Catalog.exe
, part of the Voyager
card catalog by "Ex Libris" and I'm getting the error as well:
catalog-error.png http://img805.imageshack.us/img805/8275/catalogerror.png
I have two Windows 7 32-bit machines. The newer one is giving me the error but on the older one it runs fine. I have done a lot of research with Google and here are some of the things I've found that people are saying related to this issue. Maybe one of these things will help fix the error for you, although they didn't work for me:
From what others are saying (like David M) I think it could be related to the MSVBM60.DLL
library - but it appears that on both of my computers this file is the exact same (same version, size, date, etc).
Since that file wasn't different I tried to find what other (dll) files the application could be using, so I launched Process Explorer by Sysinternals and took a look at the application (it loads and then crashes when you tell it to "connect"), and the screenshots below are what I found.
screen1.png http://img195.imageshack.us/img195/2231/screen1oo.png
screen2.png http://img88.imageshack.us/img88/2153/screen2ao.png
Now, I'm not a Windows / VB programmer, just a power user, and so I'm about at the end of my knowledge for what to do. I've talked to the software vendor and they recommend reinstalling Windows. That will probably work, but it just bugs me that this program can run on Windows 7, but something on this particular system is causing errors. Finally, this is an image that has been deployed on multiple machines already and so while re-installing Windows once is not a big deal it would save me some serious time if I could figure out a fix or workaround.
How to hide console window in python?
Simply save it with a .pyw
extension. This will prevent the console window from opening.
On Windows systems, there is no notion of an “executable mode”. The Python installer automatically associates .py files with python.exe so that a double-click on a Python file will run it as a script. The extension can also be .pyw, in that case, the console window that normally appears is suppressed.
Explanation at the bottom of section 2.2.2
How to break out of a loop from inside a switch?
No, C++ does not have a construct for this, given that the keyword "break" is already reserved for exiting the switch block. Alternatively a do..while() with an exit flag could suffice.
do {
switch(option){
case 1: ..; break;
...
case n: .. ;break;
default: flag = false; break;
}
} while(flag);
Why do people use Heroku when AWS is present? What distinguishes Heroku from AWS?
Well Heroku uses AWS in background, it all depends on the type of solution you need. If you are a core linux and devops guy you are not worried about creating vm from scratch like selecting ami choosing palcement options etc, you can go with AWS. If you want to do things on surface level without having those nettigrities you can go with heroku.
How to make MySQL table primary key auto increment with some prefix
Here is PostgreSQL example without trigger if someone need it on PostgreSQL:
CREATE SEQUENCE messages_seq;
CREATE TABLE IF NOT EXISTS messages (
id CHAR(20) NOT NULL DEFAULT ('message_' || nextval('messages_seq')),
name CHAR(30) NOT NULL,
);
ALTER SEQUENCE messages_seq OWNED BY messages.id;
Open file in a relative location in Python
When I was a beginner I found these descriptions a bit intimidating. As at first I would try
For Windows
f= open('C:\Users\chidu\Desktop\Skipper New\Special_Note.txt','w+')
print(f)
and this would raise an syntax error
. I used get confused alot. Then after some surfing across google. found why the error occurred. Writing this for beginners
It's because for path to be read in Unicode you simple add a \
when starting file path
f= open('C:\\Users\chidu\Desktop\Skipper New\Special_Note.txt','w+')
print(f)
And now it works just add \
before starting the directory.
OS detecting makefile
Here's a simple solution that checks if you are in a Windows or posix-like (Linux/Unix/Cygwin/Mac) environment:
ifeq ($(shell echo "check_quotes"),"check_quotes")
WINDOWS := yes
else
WINDOWS := no
endif
It takes advantage of the fact that echo exists on both posix-like and Windows environments, and that in Windows the shell does not filter the quotes.
cor shows only NA or 1 for correlations - Why?
The NA can actually be due to 2 reasons. One is that there is a NA in your data. Another one is due to there being one of the values being constant. This results in standard deviation being equal to zero and hence the cor function returns NA.
What is the difference between window, screen, and document in Javascript?
Window
is the main JavaScript object root, aka the global object
in a browser, also can be treated as the root of the document object model. You can access it as window
window.screen
or just screen
is a small information object about physical screen dimensions.
window.document
or just document
is the main object of the potentially visible (or better yet: rendered) document object model/DOM.
Since window
is the global object you can reference any properties of it with just the property name - so you do not have to write down window.
- it will be figured out by the runtime.
What is the difference between DAO and Repository patterns?
In the spring framework, there is an annotation called the repository, and in the description of this annotation, there is useful information about the repository, which I think it is useful for this discussion.
Indicates that an annotated class is a "Repository", originally
defined by Domain-Driven Design (Evans, 2003) as "a mechanism for
encapsulating storage, retrieval, and search behavior which emulates a
collection of objects".
Teams implementing traditional Java EE patterns such as "Data Access
Object" may also apply this stereotype to DAO classes, though care
should be taken to understand the distinction between Data Access
Object and DDD-style repositories before doing so. This annotation is
a general-purpose stereotype and individual teams may narrow their
semantics and use as appropriate.
A class thus annotated is eligible for Spring DataAccessException
translation when used in conjunction with a
PersistenceExceptionTranslationPostProcessor. The annotated class is
also clarified as to its role in the overall application architecture
for the purpose of tooling, aspects, etc.
Get current value when change select option - Angular2
There is a way to get the value from different options. check this plunker
component.html
<select class="form-control" #t (change)="callType(t.value)">
<option *ngFor="#type of types" [value]="type">{{type}}</option>
</select>
component.ts
this.types = [ 'type1', 'type2', 'type3' ];
callType(value) {
console.log(value);
this.order.type = value;
}
SQLException : String or binary data would be truncated
BEGIN TRY
INSERT INTO YourTable (col1, col2) VALUES (@val1, @val2)
END TRY
BEGIN CATCH
--print or insert into error log or return param or etc...
PRINT '@val1='+ISNULL(CONVERT(varchar,@val1),'')
PRINT '@val2='+ISNULL(CONVERT(varchar,@val2),'')
END CATCH
Validating parameters to a Bash script
I would use bash's [[
:
if [[ ! ("$#" == 1 && $1 =~ ^[0-9]+$ && -d $1) ]]; then
echo 'Please pass a number that corresponds to a directory'
exit 1
fi
I found this faq to be a good source of information.
No Spring WebApplicationInitializer types detected on classpath
tomcat-maven-plugin in test
Tomcat usually does not add classes in src/test/java
to the classpath. They are missing if you run tomcat in scope test. To order tomcat to respect classes in test, use -Dmaven.tomcat.useTestClasspath=true
or add
<properties>
<maven.tomcat.useTestClasspath>true</maven.tomcat.useTestClasspath>
</properties>
To your pom.xml
.
How to download HTTP directory with all files and sub-directories as they appear on the online files/folders list?
No Software or Plugin required!
(only usable if you don't need recursive deptch)
Use bookmarklet. Drag this link in bookmarks, then edit and paste this code:
(function(){ var arr=[], l=document.links; var ext=prompt("select extension for download (all links containing that, will be downloaded.", ".mp3"); for(var i=0; i<l.length; i++) { if(l[i].href.indexOf(ext) !== false){ l[i].setAttribute("download",l[i].text); l[i].click(); } } })();
and go on page (from where you want to download files), and click that bookmarklet.
How does the ARM architecture differ from x86?
The ARM architecture was originally designed for Acorn personal computers (See Acorn Archimedes, circa 1987, and RiscPC), which were just as much keyboard-based personal computers as were x86 based IBM PC models. Only later ARM implementations were primarily targeted at the mobile and embedded market segment.
Originally, simple RISC CPUs of roughly equivalent performance could be designed by much smaller engineering teams (see Berkeley RISC) than those working on the x86 development at Intel.
But, nowadays, the fastest ARM chips have very complex multi-issue out-of-order instruction dispatch units designed by large engineering teams, and x86 cores may have something like a RISC core fed by an instruction translation unit.
So, any current differences between the two architectures are more related to the specific market needs of the product niches that the development teams are targeting. (Random opinion: ARM probably makes more in license fees from embedded applications that tend to be far more power and cost constrained. And Intel needs to maintain a performance edge in PCs and servers for their profit margins. Thus you see differing implementation optimizations.)
How to draw a rounded Rectangle on HTML Canvas?
Juan, I made a slight improvement to your method to allow for changing each rectangle corner radius individually:
/**
* Draws a rounded rectangle using the current state of the canvas.
* If you omit the last three params, it will draw a rectangle
* outline with a 5 pixel border radius
* @param {Number} x The top left x coordinate
* @param {Number} y The top left y coordinate
* @param {Number} width The width of the rectangle
* @param {Number} height The height of the rectangle
* @param {Object} radius All corner radii. Defaults to 0,0,0,0;
* @param {Boolean} fill Whether to fill the rectangle. Defaults to false.
* @param {Boolean} stroke Whether to stroke the rectangle. Defaults to true.
*/
CanvasRenderingContext2D.prototype.roundRect = function (x, y, width, height, radius, fill, stroke) {
var cornerRadius = { upperLeft: 0, upperRight: 0, lowerLeft: 0, lowerRight: 0 };
if (typeof stroke == "undefined") {
stroke = true;
}
if (typeof radius === "object") {
for (var side in radius) {
cornerRadius[side] = radius[side];
}
}
this.beginPath();
this.moveTo(x + cornerRadius.upperLeft, y);
this.lineTo(x + width - cornerRadius.upperRight, y);
this.quadraticCurveTo(x + width, y, x + width, y + cornerRadius.upperRight);
this.lineTo(x + width, y + height - cornerRadius.lowerRight);
this.quadraticCurveTo(x + width, y + height, x + width - cornerRadius.lowerRight, y + height);
this.lineTo(x + cornerRadius.lowerLeft, y + height);
this.quadraticCurveTo(x, y + height, x, y + height - cornerRadius.lowerLeft);
this.lineTo(x, y + cornerRadius.upperLeft);
this.quadraticCurveTo(x, y, x + cornerRadius.upperLeft, y);
this.closePath();
if (stroke) {
this.stroke();
}
if (fill) {
this.fill();
}
}
Use it like this:
var canvas = document.getElementById("canvas");
var c = canvas.getContext("2d");
c.fillStyle = "blue";
c.roundRect(50, 100, 50, 100, {upperLeft:10,upperRight:10}, true, true);
Equivalent of shell 'cd' command to change the working directory?
You can change the working directory with:
import os
os.chdir(path)
There are two best practices to follow when using this method:
- Catch the exception (WindowsError, OSError) on invalid path. If the exception is thrown, do not perform any recursive operations, especially destructive ones. They will operate on the old path and not the new one.
- Return to your old directory when you're done. This can be done in an exception-safe manner by wrapping your chdir call in a context manager, like Brian M. Hunt did in his answer.
Changing the current working directory in a subprocess does not change the current working directory in the parent process. This is true of the Python interpreter as well. You cannot use os.chdir()
to change the CWD of the calling process.
SQL RANK() over PARTITION on joined tables
As the rank doesn't depend at all from the contacts
RANKED_RSLTS
QRY_ID | RES_ID | SCORE | RANK
-------------------------------------
A | 1 | 15 | 3
A | 2 | 32 | 1
A | 3 | 29 | 2
C | 7 | 61 | 1
C | 9 | 30 | 2
Thus :
SELECT
C.*
,R.SCORE
,MYRANK
FROM CONTACTS C LEFT JOIN
(SELECT *,
MYRANK = RANK() OVER (PARTITION BY QRY_ID ORDER BY SCORE DESC)
FROM RSLTS) R
ON C.RES_ID = R.RES_ID
AND C.QRY_ID = R.QRY_ID
What is the use of adding a null key or value to a HashMap in Java?
I'm not positive what you're asking, but if you're looking for an example of when one would want to use a null key, I use them often in maps to represent the default case (i.e. the value that should be used if a given key isn't present):
Map<A, B> foo;
A search;
B val = foo.containsKey(search) ? foo.get(search) : foo.get(null);
HashMap
handles null keys specially (since it can't call .hashCode()
on a null object), but null values aren't anything special, they're stored in the map like anything else
Assign multiple values to array in C
The old-school way:
GLfloat coordinates[8];
...
GLfloat *p = coordinates;
*p++ = 1.0f; *p++ = 0.0f; *p++ = 1.0f; *p++ = 1.0f;
*p++ = 0.0f; *p++ = 1.0f; *p++ = 0.0f; *p++ = 0.0f;
return coordinates;
What is the 
 character?
That would be an HTML Encoded Line Feed character (using the hexadecimal value).
The decimal value would be
Create comma separated strings C#?
Another approach is to use the CommaDelimitedStringCollection class from System.Configuration namespace/assembly. It behaves like a list plus it has an overriden ToString method that returns a comma-separated string.
Pros - More flexible than an array.
Cons - You can't pass a string containing a comma.
CommaDelimitedStringCollection list = new CommaDelimitedStringCollection();
list.AddRange(new string[] { "Huey", "Dewey" });
list.Add("Louie");
//list.Add(",");
string s = list.ToString(); //Huey,Dewey,Louie
C Macro definition to determine big endian or little endian machine?
Don't forget that endianness is not the whole story - the size of char
might not be 8 bits (e.g. DSP's), two's complement negation is not guaranteed (e.g. Cray), strict alignment might be required (e.g. SPARC, also ARM springs into middle-endian when unaligned), etc, etc.
It might be a better idea to target a specific CPU architecture instead.
For example:
#if defined(__i386__) || defined(_M_IX86) || defined(_M_IX64)
#define USE_LITTLE_ENDIAN_IMPL
#endif
void my_func()
{
#ifdef USE_LITTLE_ENDIAN_IMPL
// Intel x86-optimized, LE implementation
#else
// slow but safe implementation
#endif
}
Note that this solution is also not ultra-portable unfortunately, as it depends on compiler-specific definitions (there is no standard, but here's a nice compilation of such definitions).
SQL query to make all data in a column UPPER CASE?
If you want to only update on rows that are not currently uppercase (instead of all rows), you'd need to identify the difference using COLLATE
like this:
UPDATE MyTable
SET MyColumn = UPPER(MyColumn)
WHERE MyColumn != UPPER(MyColumn) COLLATE Latin1_General_CS_AS
A Bit About Collation
Cases sensitivity is based on your collation settings, and is typically case insensitive by default.
Collation can be set at the Server, Database, Column, or Query Level:
-- Server
SELECT SERVERPROPERTY('COLLATION')
-- Database
SELECT name, collation_name FROM sys.databases
-- Column
SELECT COLUMN_NAME, COLLATION_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE CHARACTER_SET_NAME IS NOT NULL
Collation Names specify how a string should be encoded and read, for example:
Latin1_General_CI_AS
? Case Insensitive
Latin1_General_CS_AS
? Case Sensitive
Git - What is the difference between push.default "matching" and "simple"
Git v2.0 Release Notes
Backward compatibility notes
When git push [$there]
does not say what to push, we have used the
traditional "matching" semantics so far (all your branches were sent
to the remote as long as there already are branches of the same name
over there). In Git 2.0, the default is now the "simple" semantics,
which pushes:
only the current branch to the branch with the same name, and only
when the current branch is set to integrate with that remote
branch, if you are pushing to the same remote as you fetch from; or
only the current branch to the branch with the same name, if you
are pushing to a remote that is not where you usually fetch from.
You can use the configuration variable "push.default" to change
this. If you are an old-timer who wants to keep using the
"matching" semantics, you can set the variable to "matching", for
example. Read the documentation for other possibilities.
When git add -u
and git add -A
are run inside a subdirectory
without specifying which paths to add on the command line, they
operate on the entire tree for consistency with git commit -a
and
other commands (these commands used to operate only on the current
subdirectory). Say git add -u .
or git add -A .
if you want to
limit the operation to the current directory.
git add <path>
is the same as git add -A <path>
now, so that
git add dir/
will notice paths you removed from the directory and
record the removal. In older versions of Git, git add <path>
used
to ignore removals. You can say git add --ignore-removal <path>
to
add only added or modified paths in <path>
, if you really want to.
curl error 18 - transfer closed with outstanding read data remaining
I've solved this error by this way.
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, 'http://www.someurl/' );
curl_setopt ( $ch, CURLOPT_TIMEOUT, 30);
ob_start();
$response = curl_exec ( $ch );
$data = ob_get_clean();
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200 ) success;
Error still occurs, but I can handle response data in variable.
How do I redirect to the previous action in ASP.NET MVC?
For ASP.NET Core
You can use asp-route-* attribute:
<form asp-action="Login" asp-route-previous="@Model.ReturnUrl">
Other in details example:
Imagine that you have a Vehicle Controller with actions
Index
Details
Edit
and you can edit any vehicle from Index or from Details, so if you clicked edit from index you must return to index after edit
and if you clicked edit from details you must return to details after edit.
//In your viewmodel add the ReturnUrl Property
public class VehicleViewModel
{
..............
..............
public string ReturnUrl {get;set;}
}
Details.cshtml
<a asp-action="Edit" asp-route-previous="Details" asp-route-id="@Model.CarId">Edit</a>
Index.cshtml
<a asp-action="Edit" asp-route-previous="Index" asp-route-id="@item.CarId">Edit</a>
Edit.cshtml
<form asp-action="Edit" asp-route-previous="@Model.ReturnUrl" class="form-horizontal">
<div class="box-footer">
<a asp-action="@Model.ReturnUrl" class="btn btn-default">Back to List</a>
<button type="submit" value="Save" class="btn btn-warning pull-right">Save</button>
</div>
</form>
In your controller:
// GET: Vehicle/Edit/5
public ActionResult Edit(int id,string previous)
{
var model = this.UnitOfWork.CarsRepository.GetAllByCarId(id).FirstOrDefault();
var viewModel = this.Mapper.Map<VehicleViewModel>(model);//if you using automapper
//or by this code if you are not use automapper
var viewModel = new VehicleViewModel();
if (!string.IsNullOrWhiteSpace(previous)
viewModel.ReturnUrl = previous;
else
viewModel.ReturnUrl = "Index";
return View(viewModel);
}
[HttpPost]
public IActionResult Edit(VehicleViewModel model, string previous)
{
if (!string.IsNullOrWhiteSpace(previous))
model.ReturnUrl = previous;
else
model.ReturnUrl = "Index";
.............
.............
return RedirectToAction(model.ReturnUrl);
}
How to convert minutes to hours/minutes and add various time values together using jQuery?
Very short code for transferring minutes in two formats!
_x000D_
_x000D_
let format1 = (n) => `${n / 60 ^ 0}:` + n % 60_x000D_
_x000D_
console.log(format1(135)) // "2:15"_x000D_
console.log(format1(55)) // "0:55"_x000D_
_x000D_
let format2 = (n) => `0${n / 60 ^ 0}`.slice(-2) + ':' + ('0' + n % 60).slice(-2)_x000D_
_x000D_
console.log(format2(135)) // "02:15"_x000D_
console.log(format2(5)) // "00:05"
_x000D_
_x000D_
_x000D_
Error java.lang.OutOfMemoryError: GC overhead limit exceeded
This message means that for some reason the garbage collector is taking an excessive amount of time (by default 98% of all CPU time of the process) and recovers very little memory in each run (by default 2% of the heap).
This effectively means that your program stops doing any progress and is busy running only the garbage collection at all time.
To prevent your application from soaking up CPU time without getting anything done, the JVM throws this Error
so that you have a chance of diagnosing the problem.
The rare cases where I've seen this happen is where some code was creating tons of temporary objects and tons of weakly-referenced objects in an already very memory-constrained environment.
Check out the Java GC tuning guide, which is available for various Java versions and contains sections about this specific problem:
Plot logarithmic axes with matplotlib in python
You simply need to use semilogy instead of plot:
from pylab import *
import matplotlib.pyplot as pyplot
a = [ pow(10,i) for i in range(10) ]
fig = pyplot.figure()
ax = fig.add_subplot(2,1,1)
line, = ax.semilogy(a, color='blue', lw=2)
show()
ReactJS: Warning: setState(...): Cannot update during an existing state transition
The solution that I use to open Popover for components is reactstrap (React Bootstrap 4 components).
class Settings extends Component {
constructor(props) {
super(props);
this.state = {
popoversOpen: [] // array open popovers
}
}
// toggle my popovers
togglePopoverHelp = (selected) => (e) => {
const index = this.state.popoversOpen.indexOf(selected);
if (index < 0) {
this.state.popoversOpen.push(selected);
} else {
this.state.popoversOpen.splice(index, 1);
}
this.setState({ popoversOpen: [...this.state.popoversOpen] });
}
render() {
<div id="settings">
<button id="PopoverTimer" onClick={this.togglePopoverHelp(1)} className="btn btn-outline-danger" type="button">?</button>
<Popover placement="left" isOpen={this.state.popoversOpen.includes(1)} target="PopoverTimer" toggle={this.togglePopoverHelp(1)}>
<PopoverHeader>Header popover</PopoverHeader>
<PopoverBody>Description popover</PopoverBody>
</Popover>
<button id="popoverRefresh" onClick={this.togglePopoverHelp(2)} className="btn btn-outline-danger" type="button">?</button>
<Popover placement="left" isOpen={this.state.popoversOpen.includes(2)} target="popoverRefresh" toggle={this.togglePopoverHelp(2)}>
<PopoverHeader>Header popover 2</PopoverHeader>
<PopoverBody>Description popover2</PopoverBody>
</Popover>
</div>
}
}
Increasing heap space in Eclipse: (java.lang.OutOfMemoryError)
What to do if i have to processed even more that 500000 records ?
There are a few ways, to increase the java heap size for your app where a few have suggested already. Your app need to remove the elements from your adddressMap as your app add new element into it and so you won't encounter oom if there are more records coming in. Look for producer-consumer if you are interested.
Passing parameters in Javascript onClick event
Try this:
<div id="div"></div>
<script language="javascript" type="text/javascript">
var div = document.getElementById('div');
for (var i = 0; i < 10; i++) {
var f = function() {
var link = document.createElement('a');
var j = i; // this j is scoped to our anonymous function
// while i is scoped outside the anonymous function,
// getting incremented by the for loop
link.setAttribute('href', '#');
link.innerHTML = j + '';
link.onclick= function() { onClickLink(j+'');};
div.appendChild(link);
div.appendChild(document.createElement('br')); // lower case BR, please!
}(); // call the function immediately
}
function onClickLink(text) {
alert('Link ' + text + ' clicked');
return false;
}
</script>
Map HTML to JSON
Representing complex HTML documents will be difficult and full of corner cases, but I just wanted to share a couple techniques to show how to get this kind of program started. This answer differs in that it uses data abstraction and the toJSON
method to recursively build the result
Below, html2json
is a tiny function which takes an HTML node as input and it returns a JSON string as the result. Pay particular attention to how the code is quite flat but it's still plenty capable of building a deeply nested tree structure – all possible with virtually zero complexity
_x000D_
_x000D_
// data Elem = Elem Node_x000D_
_x000D_
const Elem = e => ({_x000D_
toJSON : () => ({_x000D_
tagName: _x000D_
e.tagName,_x000D_
textContent:_x000D_
e.textContent,_x000D_
attributes:_x000D_
Array.from(e.attributes, ({name, value}) => [name, value]),_x000D_
children:_x000D_
Array.from(e.children, Elem)_x000D_
})_x000D_
})_x000D_
_x000D_
// html2json :: Node -> JSONString_x000D_
const html2json = e =>_x000D_
JSON.stringify(Elem(e), null, ' ')_x000D_
_x000D_
console.log(html2json(document.querySelector('main')))
_x000D_
<main>_x000D_
<h1 class="mainHeading">Some heading</h1>_x000D_
<ul id="menu">_x000D_
<li><a href="/a">a</a></li>_x000D_
<li><a href="/b">b</a></li>_x000D_
<li><a href="/c">c</a></li>_x000D_
</ul>_x000D_
<p>some text</p>_x000D_
</main>
_x000D_
_x000D_
_x000D_
In the previous example, the textContent
gets a little butchered. To remedy this, we introduce another data constructor, TextElem
. We'll have to map over the childNodes
(instead of children
) and choose to return the correct data type based on e.nodeType
– this gets us a littler closer to what we might need
_x000D_
_x000D_
// data Elem = Elem Node | TextElem Node_x000D_
_x000D_
const TextElem = e => ({_x000D_
toJSON: () => ({_x000D_
type:_x000D_
'TextElem',_x000D_
textContent:_x000D_
e.textContent_x000D_
})_x000D_
})_x000D_
_x000D_
const Elem = e => ({_x000D_
toJSON : () => ({_x000D_
type:_x000D_
'Elem',_x000D_
tagName: _x000D_
e.tagName,_x000D_
attributes:_x000D_
Array.from(e.attributes, ({name, value}) => [name, value]),_x000D_
children:_x000D_
Array.from(e.childNodes, fromNode)_x000D_
})_x000D_
})_x000D_
_x000D_
// fromNode :: Node -> Elem_x000D_
const fromNode = e => {_x000D_
switch (e.nodeType) {_x000D_
case 3: return TextElem(e)_x000D_
default: return Elem(e)_x000D_
}_x000D_
}_x000D_
_x000D_
// html2json :: Node -> JSONString_x000D_
const html2json = e =>_x000D_
JSON.stringify(Elem(e), null, ' ')_x000D_
_x000D_
console.log(html2json(document.querySelector('main')))
_x000D_
<main>_x000D_
<h1 class="mainHeading">Some heading</h1>_x000D_
<ul id="menu">_x000D_
<li><a href="/a">a</a></li>_x000D_
<li><a href="/b">b</a></li>_x000D_
<li><a href="/c">c</a></li>_x000D_
</ul>_x000D_
<p>some text</p>_x000D_
</main>
_x000D_
_x000D_
_x000D_
Anyway, that's just two iterations on the problem. Of course you'll have to address corner cases where they come up, but what's nice about this approach is that it gives you a lot of flexibility to encode the HTML however you wish in JSON – and without introducing too much complexity
In my experience, you could keep iterating with this technique and achieve really good results. If this answer is interesting to anyone and would like me to expand upon anything, let me know ^_^
Related: Recursive methods using JavaScript: building your own version of JSON.stringify
C++ error 'Undefined reference to Class::Function()'
This part has problems:
Card* cardArray;
void Deck() {
cardArray = new Card[NUM_TOTAL_CARDS];
int cardCount = 0;
for (int i = 0; i > NUM_SUITS; i++) { //Error
for (int j = 0; j > NUM_RANKS; j++) { //Error
cardArray[cardCount] = Card(Card::Rank(i), Card::Suit(j) );
cardCount++;
}
}
}
cardArray
is a dynamic array, but not a member of Card
class. It is strange if you would like to initialize a dynamic array which is not member of the class
void Deck()
is not constructor of class Deck since you missed the
scope resolution operator. You may be confused with defining the constructor and the function with name Deck
and return type void
.
- in your loops, you should use
<
not >
otherwise, loop will never
be executed.
How to add trendline in python matplotlib dot (scatter) graphs?
as explained here
With help from numpy one can calculate for example a linear fitting.
# plot the data itself
pylab.plot(x,y,'o')
# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])
What is the Java equivalent for LINQ?
There are many LINQ equivalents for Java, see here for a comparison.
For a typesafe Quaere/LINQ style framework, consider using Querydsl. Querydsl supports JPA/Hibernate, JDO, SQL and Java Collections.
I am the maintainer of Querydsl, so this answer is biased.
ImportError: numpy.core.multiarray failed to import
In my case this problem was because I'd two python installations (2.7 and 3.5) and pip was installing numpy in the 3.5 python directory only, irrespective of which pip version I used.
I solved the problem by explicitly specifying the target install directory as such:
pip install --target c:\apps\python-2.7\Lib\site-packages numpy
How to loop through elements of forms with JavaScript?
$(function() {
$('form button').click(function() {
var allowSubmit = true;
$.each($('form input:text'), function(index, formField) {
if($(formField).val().trim().length == 0) {
alert('field is empty!');
allowSubmit = false;
}
});
return allowSubmit;
});
});
DEMO
TypeScript add Object to array with push
class PushObjects {
testMethod(): Array<number> {
//declaration and initialisation of array onject
var objs: number[] = [1,2,3,4,5,7];
//push the elements into the array object
objs.push(100);
//pop the elements from the array
objs.pop();
return objs;
}
}
let pushObj = new PushObjects();
//create the button element from the dom object
let btn = document.createElement('button');
//set the text value of the button
btn.textContent = "Click here";
//button click event
btn.onclick = function () {
alert(pushObj.testMethod());
}
document.body.appendChild(btn);
'cannot find or open the pdb file' Visual Studio C++ 2013
A bit late but I thought I'd share in case it helps anyone: what is most likely the problem is simply that your Debug Console (the command line window that opens when run your project if it is a Windows Console Application
) is still open from the last time you ran the code. Just close that window, then rebuild and run: Ctrl + B
and F5
, respectively.
postgresql - sql - count of `true` values
The shortest and laziest (without casting) solution would be to use the formula:
SELECT COUNT(myCol OR NULL) FROM myTable;
Try it yourself:
SELECT COUNT(x < 7 OR NULL)
FROM GENERATE_SERIES(0,10) t(x);
gives the same result than
SELECT SUM(CASE WHEN x < 7 THEN 1 ELSE 0 END)
FROM GENERATE_SERIES(0,10) t(x);