How to get current SIM card number in Android?
Getting the Phone Number, IMEI, and SIM Card ID
TelephonyManager tm = (TelephonyManager)
getSystemService(Context.TELEPHONY_SERVICE);
For SIM card, use the getSimSerialNumber()
//---get the SIM card ID---
String simID = tm.getSimSerialNumber();
if (simID != null)
Toast.makeText(this, "SIM card ID: " + simID,
Toast.LENGTH_LONG).show();
Phone number of your phone, use the getLine1Number() (some device's dont return the phone number)
//---get the phone number---
String telNumber = tm.getLine1Number();
if (telNumber != null)
Toast.makeText(this, "Phone number: " + telNumber,
Toast.LENGTH_LONG).show();
IMEI number of the phone, use the getDeviceId()
//---get the IMEI number---
String IMEI = tm.getDeviceId();
if (IMEI != null)
Toast.makeText(this, "IMEI number: " + IMEI,
Toast.LENGTH_LONG).show();
Permissions needed
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
How to prevent a dialog from closing when a button is clicked
Kotlin
val dialogView = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_userinput, null)
val dialogBuilder = MaterialAlertDialogBuilder(requireContext(), R.style.AlertDialogTheme)
dialogBuilder.setView(dialogView)
dialogBuilder.setCancelable(false)
dialogBuilder.setPositiveButton("send",null)
dialogBuilder.setNegativeButton("cancel") { dialog,_ ->
dialog.dismiss()
}
val alertDialog = dialogBuilder.create()
alertDialog.show()
val positiveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
positiveButton.setOnClickListener {
val myInputText = dialogView.etxt_userinput.text.toString().trim()
if(myInputText.isNotEmpty()){
//Do something
}else{
//Prompt error
dialogView.etxt_userinput.error = "Please fill this"
}
}
We just create an AlertDialog
with the dialogBuilder
and then just set the positive button as we want
Is there an easy way to add a border to the top and bottom of an Android View?
In android 2.2 you could do the following.
Create an xml drawable such as /res/drawable/textlines.xml and assign this as a TextView's background property.
<TextView
android:text="My text with lines above and below"
android:background="@drawable/textlines"
/>
/res/drawable/textlines.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape
android:shape="rectangle">
<stroke android:width="1dp" android:color="#FF000000" />
<solid android:color="#FFDDDDDD" />
</shape>
</item>
<item android:top="1dp" android:bottom="1dp">
<shape
android:shape="rectangle">
<stroke android:width="1dp" android:color="#FFDDDDDD" />
<solid android:color="#00000000" />
</shape>
</item>
</layer-list>
The down side to this is that you have to specify an opaque background colour, as transparencies won't work. (At least i thought they did but i was mistaken). In the above example you can see that the solid colour of the first shape #FFdddddd is copied in the 2nd shapes stroke colour.
Jenkins - Configure Jenkins to poll changes in SCM
That's an old question, I know. But, according to me, it is missing proper answer.
The actual / optimal workflow here would be to incorporate SVN's post-commit hook so it triggers Jenkins job after the actual commit is issued only, not in any other case. This way you avoid unneeded polls on your SCM system.
You may find the following links interesting:
In case of my setup in the corp's SVN server, I utilize the following (censored) script as a post-commit hook on the subversion server side:
#!/bin/sh
# POST-COMMIT HOOK
REPOS="$1"
REV="$2"
#TXN_NAME="$3"
LOGFILE=/var/log/xxx/svn/xxx.post-commit.log
MSG=$(svnlook pg --revprop $REPOS svn:log -r$REV)
JENK="http://jenkins.xxx.com:8080/job/xxx/job/xxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"
JENKtest="http://jenkins.xxx.com:8080/view/all/job/xxx/job/xxxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"
echo post-commit $* >> $LOGFILE 2>&1
# trigger Jenkins job - xxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx/xxx/Source"
if test 0 -eq $? ; then
echo $(date) - $REPOS - $REV: >> $LOGFILE
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx/xxx/Source" >> $LOGFILE 2>&1
echo logmsg: $MSG >> $LOGFILE 2>&1
echo curl -qs $JENK >> $LOGFILE 2>&1
curl -qs $JENK >> $LOGFILE 2>&1
echo -------- >> $LOGFILE
fi
# trigger Jenkins job - xxxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx_TEST"
if test 0 -eq $? ; then
echo $(date) - $REPOS - $REV: >> $LOGFILE
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx_TEST" >> $LOGFILE 2>&1
echo logmsg: $MSG >> $LOGFILE 2>&1
echo curl -qs $JENKtest >> $LOGFILE 2>&1
curl -qs $JENKtest >> $LOGFILE 2>&1
echo -------- >> $LOGFILE
fi
exit 0
Android fade in and fade out with ImageView
you can do it by two simple point and change in your code
1.In your xml in anim folder of your project, Set the fade in and fade out duration time not equal
2.In you java class before the start of fade out animation, set second imageView visibility Gone then after fade out animation started set second imageView visibility which you want to fade in visible
fadeout.xml
<alpha
android:duration="4000"
android:fromAlpha="1.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:toAlpha="0.0" />
fadein.xml
<alpha
android:duration="6000"
android:fromAlpha="0.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:toAlpha="1.0" />
In you java class
Animation animFadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_out);
ImageView iv = (ImageView) findViewById(R.id.imageView1);
ImageView iv2 = (ImageView) findViewById(R.id.imageView2);
iv.setVisibility(View.VISIBLE);
iv2.setVisibility(View.GONE);
animFadeOut.reset();
iv.clearAnimation();
iv.startAnimation(animFadeOut);
Animation animFadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in);
iv2.setVisibility(View.VISIBLE);
animFadeIn.reset();
iv2.clearAnimation();
iv2.startAnimation(animFadeIn);
How to execute IN() SQL queries with Spring's JDBCTemplate effectively?
Refer to here
write query with named parameter, use simple ListPreparedStatementSetter
with all parameters in sequence. Just add below snippet to convert the query in traditional form based to available parameters,
ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(namedSql);
List<Integer> parameters = new ArrayList<Integer>();
for (A a : paramBeans)
parameters.add(a.getId());
MapSqlParameterSource parameterSource = new MapSqlParameterSource();
parameterSource.addValue("placeholder1", parameters);
// create SQL with ?'s
String sql = NamedParameterUtils.substituteNamedParameters(parsedSql, parameterSource);
return sql;
Show empty string when date field is 1/1/1900
Two nitpicks. (1) Best not to use string literals for column alias - that is deprecated. (2) Just use style 120 to get the same value.
CASE
WHEN CreatedDate = '19000101' THEN ''
WHEN CreatedDate = '18000101' THEN ''
ELSE Convert(varchar(19), CreatedDate, 120)
END AS [Created Date]
How to generate a HTML page dynamically using PHP?
I'll just update the code to contain the changes, and comment it to so that you can see what's going on clearly...
<?php
include("templates/header.htm");
// Set the default name
$action = 'index';
// Specify some disallowed paths
$disallowed_paths = array('header', 'footer');
if (!empty($_GET['action'])) {
$tmp_action = basename($_GET['action']);
// If it's not a disallowed path, and if the file exists, update $action
if (!in_array($tmp_action, $disallowed_paths) && file_exists("templates/{$tmp_action}.htm"))
$action = $tmp_action;
}
// Include $action
include("templates/$action.htm");
include("templates/footer.htm");
Python: print a generator expression?
Unlike a list or a dictionary, a generator can be infinite. Doing this wouldn't work:
def gen():
x = 0
while True:
yield x
x += 1
g1 = gen()
list(g1) # never ends
Also, reading a generator changes it, so there's not a perfect way to view it.
To see a sample of the generator's output, you could do
g1 = gen()
[g1.next() for i in range(10)]
How to Sort Date in descending order From Arraylist Date in android?
If date in string format convert it to date format for each object :
String argmodifiledDate = "2014-04-06 22:26:15";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try
{
this.modifiledDate = format.parse(argmodifiledDate);
}
catch (ParseException e)
{
e.printStackTrace();
}
Then sort the arraylist in descending order :
ArrayList<Document> lstDocument= this.objDocument.getArlstDocuments();
Collections.sort(lstDocument, new Comparator<Document>() {
public int compare(Document o1, Document o2) {
if (o1.getModifiledDate() == null || o2.getModifiledDate() == null)
return 0;
return o2.getModifiledDate().compareTo(o1.getModifiledDate());
}
});
ImportError: No module named site on Windows
For me it happened because I had 2 versions of python installed - python 27 and python 3.3. Both these folder had path variable set, and hence there was this issue. To fix, this, I moved python27 to temp folder, as I was ok with python 3.3. So do check environment variables like PATH,PYTHONHOME as it may be a issue. Thanks.
Reading input files by line using read command in shell scripting skips last line
read
reads until it finds a newline character or the end of file, and returns a non-zero exit code if it encounters an end-of-file. So it's quite possible for it to both read a line and return a non-zero exit code.
Consequently, the following code is not safe if the input might not be terminated by a newline:
while read LINE; do
# do something with LINE
done
because the body of the while
won't be executed on the last line.
Technically speaking, a file not terminated with a newline is not a text file, and text tools may fail in odd ways on such a file. However, I'm always reluctant to fall back on that explanation.
One way to solve the problem is to test if what was read is non-empty (-n
):
while read -r LINE || [[ -n $LINE ]]; do
# do something with LINE
done
Other solutions include using mapfile
to read the file into an array, piping the file through some utility which is guaranteed to terminate the last line properly (grep .
, for example, if you don't want to deal with blank lines), or doing the iterative processing with a tool like awk
(which is usually my preference).
Note that -r
is almost certainly needed in the read
builtin; it causes read
to not reinterpret \
-sequences in the input.
Django: Display Choice Value
For every field that has choices set, the object will have a get_FOO_display() method, where FOO is the name of the field. This method returns the “human-readable” value of the field.
In Views
person = Person.objects.filter(to_be_listed=True)
context['gender'] = person.get_gender_display()
In Template
{{ person.get_gender_display }}
Documentation of get_FOO_display()
What is a PDB file?
PDB is an abbreviation for Program Data Base. As the name suggests, it is a repository (persistent storage such as databases) to maintain information required to run your program in debug mode. It contains many important relevant information required while you debug your code (in Visual Studio), for e.g. at what points you have inserted break points where you expect the debugger to break in Visual Studio.
This is the reason why many times Visual Studio fails to hit the break points if you remove the *.pdb
files from your debug folders. Visual Studio debugger is also able to tell you the precise line number of code file at which an exception occurred in a stack trace with the help of *.pdb
files. So effectively pdb files are really a boon to developers while debugging a program.
Generally it is not recommended to exclude the generation of *.pdb
files. From production release stand-point what you should be doing is create the pdb files but don't ship them to customer site in product installer. Preserve all the generated PDB files on to a symbol server from where it can be used/referenced in future if required. Specially for cases when you debug issues like process crash. When you start analysing the crash dump files and if your original *.pdb
files created during the build process are not preserved then Visual Studio will not be able to make out the exact line of code which is causing crash.
If you still want to disable generation of *.pdb
files altogether for any release then go to properties of the project -> Build Tab -> Click on Advanced button -> Choose none
from "Debug Info" drop-down box -> press OK as shown in the snapshot below.
Note: This setting will have to be done separately for "Debug" and "Release" build configurations.
What are the benefits of using C# vs F# or F# vs C#?
One of the aspects of .NET I like the most are generics. Even if you write procedural code in F#, you will still benefit from type inference. It makes writing generic code easy.
In C#, you write concrete code by default, and you have to put in some extra work to write generic code.
In F#, you write generic code by default. After spending over a year of programming in both F# and C#, I find that library code I write in F# is both more concise and more generic than the code I write in C#, and is therefore also more reusable. I miss many opportunities to write generic code in C#, probably because I'm blinded by the mandatory type annotations.
There are however situations where using C# is preferable, depending on one's taste and programming style.
- C# does not impose an order of declaration among types, and it's not sensitive to the order in which files are compiled.
- C# has some implicit conversions that F# cannot afford because of type inference.
How can I get the class name from a C++ object?
You can try this:
template<typename T>
inline const char* getTypeName() {
return typeid(T).name();
}
#define DEFINE_TYPE_NAME(type, type_name) \
template<> \
inline const char* getTypeName<type>() { \
return type_name; \
}
DEFINE_TYPE_NAME(int, "int")
DEFINE_TYPE_NAME(float, "float")
DEFINE_TYPE_NAME(double, "double")
DEFINE_TYPE_NAME(std::string, "string")
DEFINE_TYPE_NAME(bool, "bool")
DEFINE_TYPE_NAME(uint32_t, "uint")
DEFINE_TYPE_NAME(uint64_t, "uint")
// add your custom types' definitions
And call it like that:
void main() {
std::cout << getTypeName<int>();
}
What column type/length should I use for storing a Bcrypt hashed password in a Database?
If you are using PHP's password_hash()
with the PASSWORD_DEFAULT
algorithm to generate the bcrypt hash (which I would assume is a large percentage of people reading this question) be sure to keep in mind that in the future password_hash()
might use a different algorithm as the default and this could therefore affect the length of the hash (but it may not necessarily be longer).
From the manual page:
Note that this constant is designed to change over time as new and
stronger algorithms are added to PHP. For that reason, the length of
the result from using this identifier can change over time. Therefore,
it is recommended to store the result in a database column that can
expand beyond 60 characters (255 characters would be a good choice).
Using bcrypt, even if you have 1 billion users (i.e. you're currently competing with facebook) to store 255 byte password hashes it would only ~255 GB of data - about the size of a smallish SSD hard drive. It is extremely unlikely that storing the password hash is going to be the bottleneck in your application. However in the off chance that storage space really is an issue for some reason, you can use PASSWORD_BCRYPT
to force password_hash()
to use bcrypt, even if that's not the default. Just be sure to stay informed about any vulnerabilities found in bcrypt and review the release notes every time a new PHP version is released. If the default algorithm is ever changed it would be good to review why and make an informed decision whether to use the new algorithm or not.
What is lazy loading in Hibernate?
Bydefault lazy loading is true.Lazy loading means when the select query is executed it will not hit the database. It will wait for getter function i.e when we required then ,it will fetch from the datbase.
for example:
You are a parent who has a kid with a lot of toys. But the current issue is whenever you call him (we assume you have a boy), he comes to you with all his toys as well. Now this is an issue since you do not want him carrying around his toys all the time.
So being the rationale parent, you go right ahead and define the toys of the child as LAZY. Now whenever you call him, he just comes to you without his toys.
What is setBounds and how do I use it?
setBounds
is used to define the bounding rectangle of a component. This includes it's position and size.
The is used in a number of places within the framework.
- It is used by the layout manager's to define the position and size of a component within it's parent container.
- It is used by the paint sub system to define clipping bounds when painting the component.
For the most part, you should never call it. Instead, you should use appropriate layout managers and let them determine the best way to provide information to this method.
How can I expand and collapse a <div> using javascript?
You might want to give a look at this simple Javascript method to be invoked when clicking on a link to make a panel/div expande or collapse.
<script language="javascript">
function toggle(elementId) {
var ele = document.getElementById(elementId);
if(ele.style.display == "block") {
ele.style.display = "none";
}
else {
ele.style.display = "block";
}
}
</script>
You can pass the div ID and it will toggle between display 'none' or 'block'.
Original source on snip2code - How to collapse a div in html
How to add a class to a given element?
Just to elaborate on what others have said, multiple CSS classes are combined in a single string, delimited by spaces. Thus, if you wanted to hard-code it, it would simply look like this:
<div class="someClass otherClass yetAnotherClass">
<img ... id="image1" name="image1" />
</div>
From there you can easily derive the javascript necessary to add a new class... just append a space followed by the new class to the element's className property. Knowing this, you can also write a function to remove a class later should the need arise.
Finding the max/min value in an array of primitives using Java
Using Commons Lang (to convert) + Collections (to min/max)
import java.util.Arrays;
import java.util.Collections;
import org.apache.commons.lang.ArrayUtils;
public class MinMaxValue {
public static void main(String[] args) {
char[] a = {'3', '5', '1', '4', '2'};
List b = Arrays.asList(ArrayUtils.toObject(a));
System.out.println(Collections.min(b));
System.out.println(Collections.max(b));
}
}
Note that Arrays.asList()
wraps the underlying array, so it should not be too memory intensive and it should not perform a copy on the elements of the array.
Reading the selected value from asp:RadioButtonList using jQuery
This worked for me...
<asp:RadioButtonList runat="server" ID="Intent">
<asp:ListItem Value="Confirm">Yes!</asp:ListItem>
<asp:ListItem Value="Postpone">Not now</asp:ListItem>
<asp:ListItem Value="Decline">Never!</asp:ListItem>
</asp:RadioButtonList>
The handler:
$(document).ready(function () {
$("#<%=Intent.ClientID%>").change(function(){
var rbvalue = $("input[name='<%=Intent.UniqueID%>']:radio:checked").val();
if(rbvalue == "Confirm"){
alert("Woohoo, Thanks!");
} else if (rbvalue == "Postpone"){
alert("Well, I really hope it's soon");
} else if (rbvalue == "Decline"){
alert("Shucks!");
} else {
alert("How'd you get here? Who sent you?");
}
});
});
The important part:
$("input[name='<%=Intent.UniqueID%>']:radio:checked").val();
How to get selenium to wait for ajax response?
This work for me
public void waitForAjax(WebDriver driver) {
new WebDriverWait(driver, 180).until(new ExpectedCondition<Boolean>(){
public Boolean apply(WebDriver driver) {
JavascriptExecutor js = (JavascriptExecutor) driver;
return (Boolean) js.executeScript("return jQuery.active == 0");
}
});
}
Equivalent to AssemblyInfo in dotnet core/csproj
I do the following for my .NET Standard 2.0 projects.
Create a Directory.Build.props
file (e.g. in the root of your repo)
and move the properties to be shared from the .csproj
file to this file.
MSBuild will pick it up automatically and apply them to the autogenerated AssemblyInfo.cs
.
They also get applied to the nuget package when building one with dotnet pack
or via the UI in Visual Studio 2017.
See https://docs.microsoft.com/en-us/visualstudio/msbuild/customize-your-build
Example:
<Project>
<PropertyGroup>
<Company>Some company</Company>
<Copyright>Copyright © 2020</Copyright>
<AssemblyVersion>1.0.0.1</AssemblyVersion>
<FileVersion>1.0.0.1</FileVersion>
<Version>1.0.0.1</Version>
<!-- ... -->
</PropertyGroup>
</Project>
What's the best visual merge tool for Git?
Beyond Compare 3, my favorite, has a merge functionality in the Pro edition. The good thing with its merge is that it let you see all 4 views: base, left, right, and merged result. It's somewhat less visual than P4V but way more than WinDiff. It integrates with many source control and works on Windows/Linux. It has many features like advanced rules, editions, manual alignment...
The Perforce Visual Client (P4V) is a free tool that provides one of the most explicit interface for merging (see some screenshots). Works on all major platforms. My main disappointement with that tool is its kind of "read-only" interface. You cannot edit manually the files and you cannot manually align.
PS: P4Merge is included in P4V. Perforce tries to make it a bit hard to get their tool without their client.
SourceGear Diff/Merge may be my second free tool choice. Check that merge screens-shot and you'll see it's has the 3 views at least.
Meld is a newer free tool that I'd prefer to SourceGear Diff/Merge: Now it's also working on most platforms (Windows/Linux/Mac) with the distinct advantage of natively supporting some source control like Git. So you can have some history diff on all files much simpler. The merge view (see screenshot) has only 3 panes, just like SourceGear Diff/Merge. This makes merging somewhat harder in complex cases.
PS: If one tool one day supports 5 views merging, this would really be awesome, because if you cherry-pick commits in Git you really have not one base but two. Two base, two changes, and one resulting merge.
Fragment pressing back button
you can use this one in onCreateView, you can use transaction or replace
OnBackPressedCallback callback = new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
//what you want to do
}
};
requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
How to trigger an event after using event.preventDefault()
as long as "lots of stuff" isn't doing something asynchronous this is absolutely unneccessary - the event will call every handler on his way in sequence, so if theres a onklick-event on a parent-element this will fire after the onclik-event of the child has processed completely. javascript doesn't do some kind of "multithreading" here that makes "stopping" the event processing neccessary. conclusion: "pausing" an event just to resume it in the same handler doesn't make any sense.
if "lots of stuff" is something asynchronous this also doesn't make sense as it prevents the asynchonous things to do what they should do (asynchonous stuff) and make them bahave like everything is in sequence (where we come back to my first paragraph)
What's the point of 'meta viewport user-scalable=no' in the Google Maps API
From the v3 documentation (Developer's Guide > Concepts > Developing for Mobile Devices):
Android and iOS devices respect the following <meta>
tag:
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
This setting specifies that the map should be displayed full-screen and should not be resizable by the user. Note that the iPhone's Safari browser requires this <meta>
tag be included within the page's <head>
element.
Verify if file exists or not in C#
Try this:
string fileName = "6d294041-34d1-4c66-a04c-261a6d9aee17.jpeg";
string deletePath= "/images/uploads/";
if (!string.IsNullOrEmpty(fileName ))
{
// Append the name of the file to previous image.
deletePath += fileName ;
if (File.Exists(HttpContext.Current.Server.MapPath(deletePath)))
{
// deletevprevious image
File.Delete(HttpContext.Current.Server.MapPath(deletePath));
}
}
SQL Views - no variables?
Yes this is correct, you can't have variables in views
(there are other restrictions too).
Views can be used for cases where the result can be replaced with a select statement.
How to generate a GUID in Oracle?
you can use function bellow in order to generate your UUID
create or replace FUNCTION RANDOM_GUID
RETURN VARCHAR2 IS
RNG NUMBER;
N BINARY_INTEGER;
CCS VARCHAR2 (128);
XSTR VARCHAR2 (4000) := NULL;
BEGIN
CCS := '0123456789' || 'ABCDEF';
RNG := 15;
FOR I IN 1 .. 32 LOOP
N := TRUNC (RNG * DBMS_RANDOM.VALUE) + 1;
XSTR := XSTR || SUBSTR (CCS, N, 1);
END LOOP;
RETURN SUBSTR(XSTR, 1, 4) || '-' ||
SUBSTR(XSTR, 5, 4) || '-' ||
SUBSTR(XSTR, 9, 4) || '-' ||
SUBSTR(XSTR, 13,4) || '-' ||
SUBSTR(XSTR, 17,4) || '-' ||
SUBSTR(XSTR, 21,4) || '-' ||
SUBSTR(XSTR, 24,4) || '-' ||
SUBSTR(XSTR, 28,4);
END RANDOM_GUID;
Example of GUID genedrated by the function above:
8EA4-196D-BC48-9793-8AE8-5500-03DC-9D04
Add CSS class to a div in code behind
Here are two extension methods you can use. They ensure any existing classes are preserved and do not duplicate classes being added.
public static void RemoveCssClass(this WebControl control, String css) {
control.CssClass = String.Join(" ", control.CssClass.Split(' ').Where(x => x != css).ToArray());
}
public static void AddCssClass(this WebControl control, String css) {
control.RemoveCssClass(css);
css += " " + control.CssClass;
control.CssClass = css;
}
Usage: hlCreateNew.AddCssClass("disabled");
Usage: hlCreateNew.RemoveCssClass("disabled");
Convert java.time.LocalDate into java.util.Date type
Kotlin Solution:
1) Paste this extension function somewhere.
fun LocalDate.toDate(): Date = Date.from(this.atStartOfDay(ZoneId.systemDefault()).toInstant())
2) Use it, and never google this again.
val myDate = myLocalDate.toDate()
Java regex email
you can use a simple regular expression for validating email id,
public boolean validateEmail(String email){
return Pattern.matches("[_a-zA-Z1-9]+(\\.[A-Za-z0-9]*)*@[A-Za-z0-9]+\\.[A-Za-z0-9]+(\\.[A-Za-z0-9]*)*", email)
}
Description :
- [_a-zA-Z1-9]+ - it will accept all A-Z,a-z, 0-9 and _ (+ mean it must be occur)
- (\.[A-Za-z0-9]) - it's optional which will accept . and A-Z, a-z, 0-9( * mean its optional)
- @[A-Za-z0-9]+ - it wil accept @ and A-Z,a-z,0-9
- \.[A-Za-z0-9]+ - its for . and A-Z,a-z,0-9
- (\.[A-Za-z0-9]) - it occur, . but its optional
How do I disable text selection with CSS or JavaScript?
I'm not sure if you can turn it off, but you can change the colors of it :)
myDiv::selection,
myDiv::-moz-selection,
myDiv::-webkit-selection {
background:#000;
color:#fff;
}
Then just match the colors to your "darky" design and see what happens :)
How to find memory leak in a C++ code/project?
Answering the second part of your question,
Is there any standard or procedure one should follow to ensure there is no memory leak in the program.
Yes, there is. And this is one of the key differences between C and C++.
In C++, you should never call new
or delete
in your user code. RAII is a very commonly used technique, which pretty much solves the resource management problem. Every resource in your program (a resource is anything that has to be acquired, and then later on, released: file handles, network sockets, database connections, but also plain memory allocations, and in some cases, pairs of API calls (BeginX()/EndX(), LockY(), UnlockY()), should be wrapped in a class, where:
- the constructor acquires the resource (by calling
new
if the resource is a memroy allocation)
- the destructor releases the resource,
- copying and assignment is either prevented (by making the copy constructor and assignment operators private), or are implemented to work correctly (for example by cloning the underlying resource)
This class is then instantiated locally, on the stack, or as a class member, and not by calling new
and storing a pointer.
You often don't need to define these classes yourself. The standard library containers behave in this way as well, so that any object stored into a std::vector
gets freed when the vector is destroyed. So again, don't store a pointer into the container (which would require you to call new
and delete
), but rather the object itself (which gives you memory management for free). Likewise, smart pointer classes can be used to easily wrap objects that just have to be allocated with new
, and control their lifetimes.
This means that when the object goes out of scope, it is automatically destroyed, and its resource released and cleaned up.
If you do this consistently throughout your code, you simply won't have any memory leaks. Everything that could get leaked is tied to a destructor which is guaranteed to be called when control leaves the scope in which the object was declared.
CSS Cell Margin
A word of warning: though padding-right
might solve your particular (visual) problem, it is not the right way to add spacing between table cells. What padding-right
does for a cell is similar to what it does for most other elements: it adds space within the cell. If the cells do not have a border or background colour or something else that gives the game away, this can mimic the effect of setting the space between the cells, but not otherwise.
As someone noted, margin specifications are ignored for table cells:
CSS 2.1 Specification – Tables – Visual layout of table contents
Internal table elements generate
rectangular boxes with content and
borders. Cells have padding as well.
Internal table elements do not have
margins.
What's the "right" way then? If you are looking to replace the cellspacing
attribute of the table, then border-spacing
(with border-collapse
disabled) is a replacement. However, if per-cell "margins" are required, I am not sure how that can be correctly achieved using CSS. The only hack I can think of is to use padding
as above, avoid any styling of the cells (background colours, borders, etc.) and instead use container DIVs inside the cells to implement such styling.
I am not a CSS expert, so I could well be wrong in the above (which would be great to know! I too would like a table cell margin CSS solution).
Cheers!
jQuery-- Populate select from json
fiddle
var $select = $('#down');
$select.find('option').remove();
$.each(temp,function(key, value)
{
$select.append('<option value=' + key + '>' + value + '</option>');
});
Sorting A ListView By Column
I can see that this question was originally posted 5 yrs ago when programmers had to work harder to get their desired results.
With Visual Studio 2012 and beyond, a lazy programmer can go the Design View for the Listview properties settings, and click on Properties->Sorting, choose Ascending.
There are plenty of other properties features to obtain the various results a lazy (aka smart) programmer can leverage.
Efficient way to update all rows in a table
As Marcelo suggests:
UPDATE mytable
SET new_column = <expr containing old_column>;
If this takes too long and fails due to "snapshot too old" errors (e.g. if the expression queries another highly-active table), and if the new value for the column is always NOT NULL, you could update the table in batches:
UPDATE mytable
SET new_column = <expr containing old_column>
WHERE new_column IS NULL
AND ROWNUM <= 100000;
Just run this statement, COMMIT, then run it again; rinse, repeat until it reports "0 rows updated". It'll take longer but each update is less likely to fail.
EDIT:
A better alternative that should be more efficient is to use the DBMS_PARALLEL_EXECUTE
API.
Sample code (from Oracle docs):
DECLARE
l_sql_stmt VARCHAR2(1000);
l_try NUMBER;
l_status NUMBER;
BEGIN
-- Create the TASK
DBMS_PARALLEL_EXECUTE.CREATE_TASK ('mytask');
-- Chunk the table by ROWID
DBMS_PARALLEL_EXECUTE.CREATE_CHUNKS_BY_ROWID('mytask', 'HR', 'EMPLOYEES', true, 100);
-- Execute the DML in parallel
l_sql_stmt := 'update EMPLOYEES e
SET e.salary = e.salary + 10
WHERE rowid BETWEEN :start_id AND :end_id';
DBMS_PARALLEL_EXECUTE.RUN_TASK('mytask', l_sql_stmt, DBMS_SQL.NATIVE,
parallel_level => 10);
-- If there is an error, RESUME it for at most 2 times.
l_try := 0;
l_status := DBMS_PARALLEL_EXECUTE.TASK_STATUS('mytask');
WHILE(l_try < 2 and l_status != DBMS_PARALLEL_EXECUTE.FINISHED)
LOOP
l_try := l_try + 1;
DBMS_PARALLEL_EXECUTE.RESUME_TASK('mytask');
l_status := DBMS_PARALLEL_EXECUTE.TASK_STATUS('mytask');
END LOOP;
-- Done with processing; drop the task
DBMS_PARALLEL_EXECUTE.DROP_TASK('mytask');
END;
/
Oracle Docs: https://docs.oracle.com/database/121/ARPLS/d_parallel_ex.htm#ARPLS67333
How do I convert a number to a letter in Java?
You can convert the input to base 26 (Hexavigesimal) and convert each "digit" back to base 10 individually and apply the ASCII mapping. Since A is mapped to 0, you will get results A, B, C,..., Y, Z, BA, BB, BC,...etc, which may or may not be desirable depending on your requirements for input values > 26, since it may be natural to think AA comes after Z.
public static String getCharForNumber(int i){
// return null for bad input
if(i < 0){
return null;
}
// convert to base 26
String s = Integer.toString(i, 26);
char[] characters = s.toCharArray();
String result = "";
for(char c : characters){
// convert the base 26 character back to a base 10 integer
int x = Integer.parseInt(Character.valueOf(c).toString(), 26);
// append the ASCII value to the result
result += String.valueOf((char)(x + 'A'));
}
return result;
}
How can I hide select options with JavaScript? (Cross browser)
On pure JS:
let select = document.getElementById("select_id")
let to_hide = select[select.selectedIndex];
to_hide.setAttribute('hidden', 'hidden');
to unhide just
to_hide.removeAttr('hidden');
or
to_hide.hidden = true; // to hide
to_hide.hidden = false; // to unhide
Find nearest value in numpy array
For large arrays, the (excellent) answer given by @Demitri is far faster than the answer currently marked as best. I've adapted his exact algorithm in the following two ways:
The function below works whether or not the input array is sorted.
The function below returns the index of the input array corresponding to the closest value, which is somewhat more general.
Note that the function below also handles a specific edge case that would lead to a bug in the original function written by @Demitri. Otherwise, my algorithm is identical to his.
def find_idx_nearest_val(array, value):
idx_sorted = np.argsort(array)
sorted_array = np.array(array[idx_sorted])
idx = np.searchsorted(sorted_array, value, side="left")
if idx >= len(array):
idx_nearest = idx_sorted[len(array)-1]
elif idx == 0:
idx_nearest = idx_sorted[0]
else:
if abs(value - sorted_array[idx-1]) < abs(value - sorted_array[idx]):
idx_nearest = idx_sorted[idx-1]
else:
idx_nearest = idx_sorted[idx]
return idx_nearest
Get a particular cell value from HTML table using JavaScript
Make a javascript function
function addSampleTextInInputBox(message) {
//set value in input box
document.getElementById('textInput').value = message + "";
//or show an alert
//window.alert(message);
}
Then simply call in your table row button click
<td class="center">
<a class="btn btn-success" onclick="addSampleTextInInputBox('<?php echo $row->message; ?>')" title="Add" data-toggle="tooltip" title="Add">
<span class="fa fa-plus"></span>
</a>
</td>
bootstrap button shows blue outline when clicked
In Bootstrap 4 they use
box-shadow: 0 0 0 0px rgba(0,123,255,0);
on :focus, si i solved my problem with
a.active.focus,
a.active:focus,
a.focus,
a:active.focus,
a:active:focus,
a:focus,
button.active.focus,
button.active:focus,
button.focus,
button:active.focus,
button:active:focus,
button:focus,
.btn.active.focus,
.btn.active:focus,
.btn.focus,
.btn:active.focus,
.btn:active:focus,
.btn:focus {
outline: 0;
outline-color: transparent;
outline-width: 0;
outline-style: none;
box-shadow: 0 0 0 0 rgba(0,123,255,0);
}
How to call a method after a delay in Android
More Safety - With Kotlin
Most of the answers use Handler but I give a different solution to delay in activity, fragment, view model with Android Lifecycle ext. This way will auto cancel when the lifecycle begins destroyed.
In Activity or Fragment:
lifecycleScope.launch {
delay(DELAY_MS)
doSomething()
}
In ViewModel:
viewModelScope.lanch {
delay(DELAY_MS)
doSomething()
}
In suspend function: (Kotlin Coroutine)
suspend fun doSomethingAfter(){
delay(DELAY_MS)
doSomething()
}
If you get an error with the lifecycleScope not found - import to gradle file:
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.2.0"
Write a function that returns the longest palindrome in a given string
See Wikipedia article on this topic. Sample Manacher's Algorithm Java implementation for linear O(n) solution from the article below:
import java.util.Arrays; public class ManachersAlgorithm {
public static String findLongestPalindrome(String s) {
if (s==null || s.length()==0)
return "";
char[] s2 = addBoundaries(s.toCharArray());
int[] p = new int[s2.length];
int c = 0, r = 0; // Here the first element in s2 has been processed.
int m = 0, n = 0; // The walking indices to compare if two elements are the same
for (int i = 1; i<s2.length; i++) {
if (i>r) {
p[i] = 0; m = i-1; n = i+1;
} else {
int i2 = c*2-i;
if (p[i2]<(r-i)) {
p[i] = p[i2];
m = -1; // This signals bypassing the while loop below.
} else {
p[i] = r-i;
n = r+1; m = i*2-n;
}
}
while (m>=0 && n<s2.length && s2[m]==s2[n]) {
p[i]++; m--; n++;
}
if ((i+p[i])>r) {
c = i; r = i+p[i];
}
}
int len = 0; c = 0;
for (int i = 1; i<s2.length; i++) {
if (len<p[i]) {
len = p[i]; c = i;
}
}
char[] ss = Arrays.copyOfRange(s2, c-len, c+len+1);
return String.valueOf(removeBoundaries(ss)); }
private static char[] addBoundaries(char[] cs) {
if (cs==null || cs.length==0)
return "||".toCharArray();
char[] cs2 = new char[cs.length*2+1];
for (int i = 0; i<(cs2.length-1); i = i+2) {
cs2[i] = '|';
cs2[i+1] = cs[i/2];
}
cs2[cs2.length-1] = '|';
return cs2; }
private static char[] removeBoundaries(char[] cs) {
if (cs==null || cs.length<3)
return "".toCharArray();
char[] cs2 = new char[(cs.length-1)/2];
for (int i = 0; i<cs2.length; i++) {
cs2[i] = cs[i*2+1];
}
return cs2; } }
MySQL and PHP - insert NULL rather than empty string
your query can go as follows:
$query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$lng', '" . ($lat == '')?NULL:$lat . "', '" . ($long == '')?NULL:$long . "')";
mysql_query($query);
Convert pandas timezone-aware DateTimeIndex to naive timestamp, but in certain timezone
To answer my own question, this functionality has been added to pandas in the meantime. Starting from pandas 0.15.0, you can use tz_localize(None)
to remove the timezone resulting in local time.
See the whatsnew entry: http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#timezone-handling-improvements
So with my example from above:
In [4]: t = pd.date_range(start="2013-05-18 12:00:00", periods=2, freq='H',
tz= "Europe/Brussels")
In [5]: t
Out[5]: DatetimeIndex(['2013-05-18 12:00:00+02:00', '2013-05-18 13:00:00+02:00'],
dtype='datetime64[ns, Europe/Brussels]', freq='H')
using tz_localize(None)
removes the timezone information resulting in naive local time:
In [6]: t.tz_localize(None)
Out[6]: DatetimeIndex(['2013-05-18 12:00:00', '2013-05-18 13:00:00'],
dtype='datetime64[ns]', freq='H')
Further, you can also use tz_convert(None)
to remove the timezone information but converting to UTC, so yielding naive UTC time:
In [7]: t.tz_convert(None)
Out[7]: DatetimeIndex(['2013-05-18 10:00:00', '2013-05-18 11:00:00'],
dtype='datetime64[ns]', freq='H')
This is much more performant than the datetime.replace
solution:
In [31]: t = pd.date_range(start="2013-05-18 12:00:00", periods=10000, freq='H',
tz="Europe/Brussels")
In [32]: %timeit t.tz_localize(None)
1000 loops, best of 3: 233 µs per loop
In [33]: %timeit pd.DatetimeIndex([i.replace(tzinfo=None) for i in t])
10 loops, best of 3: 99.7 ms per loop
Blue and Purple Default links, how to remove?
Hey define color #000
into as like you and modify your css as like this
.navBtn { text-decoration: none; color:#000; }
.navBtn:visited { text-decoration: none; color:#000; }
.navBtn:hover { text-decoration: none; color:#000; }
.navBtn:focus { text-decoration: none; color:#000; }
.navBtn:hover, .navBtn:active { text-decoration: none; color:#000; }
or this
li a { text-decoration: none; color:#000; }
li a:visited { text-decoration: none; color:#000; }
li a:hover { text-decoration: none; color:#000; }
li a:focus { text-decoration: none; color:#000; }
li a:hover, .navBtn:active { text-decoration: none; color:#000; }
With MySQL, how can I generate a column containing the record index in a table?
You may want to try the following:
SELECT l.position,
l.username,
l.score,
@curRow := @curRow + 1 AS row_number
FROM league_girl l
JOIN (SELECT @curRow := 0) r;
The JOIN (SELECT @curRow := 0)
part allows the variable initialization without requiring a separate SET
command.
Test case:
CREATE TABLE league_girl (position int, username varchar(10), score int);
INSERT INTO league_girl VALUES (1, 'a', 10);
INSERT INTO league_girl VALUES (2, 'b', 25);
INSERT INTO league_girl VALUES (3, 'c', 75);
INSERT INTO league_girl VALUES (4, 'd', 25);
INSERT INTO league_girl VALUES (5, 'e', 55);
INSERT INTO league_girl VALUES (6, 'f', 80);
INSERT INTO league_girl VALUES (7, 'g', 15);
Test query:
SELECT l.position,
l.username,
l.score,
@curRow := @curRow + 1 AS row_number
FROM league_girl l
JOIN (SELECT @curRow := 0) r
WHERE l.score > 50;
Result:
+----------+----------+-------+------------+
| position | username | score | row_number |
+----------+----------+-------+------------+
| 3 | c | 75 | 1 |
| 5 | e | 55 | 2 |
| 6 | f | 80 | 3 |
+----------+----------+-------+------------+
3 rows in set (0.00 sec)
How do I get the list of keys in a Dictionary?
Or like this:
List< KeyValuePair< string, int > > theList =
new List< KeyValuePair< string,int > >(this.yourDictionary);
for ( int i = 0; i < theList.Count; i++)
{
// the key
Console.WriteLine(theList[i].Key);
}
.Net picking wrong referenced assembly version
Its almost like you have to wipe out your computer to get rid of the old dll. I have already tried everything above and then I went the extra step of just deleting every instance of the .DLL file that was on my computer and removing every reference from the application. However, it still compiles just fine and when it runs it is referencing the dll functions just fine. I'm starting to wonder if it is referencing it from a network drive somehwere.
segmentation fault : 11
Your array is occupying roughly 8 GB of memory (1,000 x 1,000,000 x sizeof(double) bytes). That might be a factor in your problem. It is a global variable rather than a stack variable, so you may be OK, but you're pushing limits here.
Writing that much data to a file is going to take a while.
You don't check that the file was opened successfully, which could be a source of trouble, too (if it did fail, a segmentation fault is very likely).
You really should introduce some named constants for 1,000 and 1,000,000; what do they represent?
You should also write a function to do the calculation; you could use an inline
function in C99 or later (or C++). The repetition in the code is excruciating to behold.
You should also use C99 notation for main()
, with the explicit return type (and preferably void
for the argument list when you are not using argc
or argv
):
int main(void)
Out of idle curiosity, I took a copy of your code, changed all occurrences of 1000 to ROWS, all occurrences of 1000000 to COLS, and then created enum { ROWS = 1000, COLS = 10000 };
(thereby reducing the problem size by a factor of 100). I made a few minor changes so it would compile cleanly under my preferred set of compilation options (nothing serious: static
in front of the functions, and the main array; file
becomes a local to main
; error check the fopen()
, etc.).
I then created a second copy and created an inline function to do the repeated calculation, (and a second one to do subscript calculations). This means that the monstrous expression is only written out once — which is highly desirable as it ensure consistency.
#include <stdio.h>
#define lambda 2.0
#define g 1.0
#define F0 1.0
#define h 0.1
#define e 0.00001
enum { ROWS = 1000, COLS = 10000 };
static double F[ROWS][COLS];
static void Inicio(double D[ROWS][COLS])
{
for (int i = 399; i < 600; i++) // Magic numbers!!
D[i][0] = F0;
}
enum { R = ROWS - 1 };
static inline int ko(int k, int n)
{
int rv = k + n;
if (rv >= R)
rv -= R;
else if (rv < 0)
rv += R;
return(rv);
}
static inline void calculate_value(int i, int k, double A[ROWS][COLS])
{
int ks2 = ko(k, -2);
int ks1 = ko(k, -1);
int kp1 = ko(k, +1);
int kp2 = ko(k, +2);
A[k][i] = A[k][i-1]
+ e/(h*h*h*h) * g*g * (A[kp2][i-1] - 4.0*A[kp1][i-1] + 6.0*A[k][i-1] - 4.0*A[ks1][i-1] + A[ks2][i-1])
+ 2.0*g*e/(h*h) * (A[kp1][i-1] - 2*A[k][i-1] + A[ks1][i-1])
+ e * A[k][i-1] * (lambda - A[k][i-1] * A[k][i-1]);
}
static void Iteration(double A[ROWS][COLS])
{
for (int i = 1; i < COLS; i++)
{
for (int k = 0; k < R; k++)
calculate_value(i, k, A);
A[999][i] = A[0][i];
}
}
int main(void)
{
FILE *file = fopen("P2.txt","wt");
if (file == 0)
return(1);
Inicio(F);
Iteration(F);
for (int i = 0; i < COLS; i++)
{
for (int j = 0; j < ROWS; j++)
{
fprintf(file,"%lf \t %.4f \t %lf\n", 1.0*j/10.0, 1.0*i, F[j][i]);
}
}
fclose(file);
return(0);
}
This program writes to P2.txt
instead of P1.txt
. I ran both programs and compared the output files; the output was identical. When I ran the programs on a mostly idle machine (MacBook Pro, 2.3 GHz Intel Core i7, 16 GiB 1333 MHz RAM, Mac OS X 10.7.5, GCC 4.7.1), I got reasonably but not wholly consistent timing:
Original Modified
6.334s 6.367s
6.241s 6.231s
6.315s 10.778s
6.378s 6.320s
6.388s 6.293s
6.285s 6.268s
6.387s 10.954s
6.377s 6.227s
8.888s 6.347s
6.304s 6.286s
6.258s 10.302s
6.975s 6.260s
6.663s 6.847s
6.359s 6.313s
6.344s 6.335s
7.762s 6.533s
6.310s 9.418s
8.972s 6.370s
6.383s 6.357s
However, almost all that time is spent on disk I/O. I reduced the disk I/O to just the very last row of data, so the outer I/O for
loop became:
for (int i = COLS - 1; i < COLS; i++)
the timings were vastly reduced and very much more consistent:
Original Modified
0.168s 0.165s
0.145s 0.165s
0.165s 0.166s
0.164s 0.163s
0.151s 0.151s
0.148s 0.153s
0.152s 0.171s
0.165s 0.165s
0.173s 0.176s
0.171s 0.165s
0.151s 0.169s
The simplification in the code from having the ghastly expression written out just once is very beneficial, it seems to me. I'd certainly far rather have to maintain that program than the original.
Adding a new line/break tag in XML
Wanted to add my solution:
< br/ >
which is basically the same as was suggested above
In my case I had to use <
for < and >
for >
Simply putting <br />
did not work.
Are there any standard exit status codes in Linux?
There are no standard exit codes, aside from 0 meaning success. Non-zero doesn't necessarily mean failure either.
stdlib.h does define EXIT_FAILURE
as 1 and EXIT_SUCCESS
as 0, but that's about it.
The 11 on segfault is interesting, as 11 is the signal number that the kernel uses to kill the process in the event of a segfault. There is likely some mechanism, either in the kernel or in the shell, that translates that into the exit code.
Define: What is a HashSet?
From application perspective, if one needs only to avoid duplicates then HashSet
is what you are looking for since it's Lookup, Insert and Remove complexities are O(1) - constant. What this means it does not matter how many elements HashSet
has it will take same amount of time to check if there's such element or not, plus since you are inserting elements at O(1) too it makes it perfect for this sort of thing.
How to avoid "StaleElementReferenceException" in Selenium?
A solution in C# would be:
Helper class:
internal class DriverHelper
{
private IWebDriver Driver { get; set; }
private WebDriverWait Wait { get; set; }
public DriverHelper(string driverUrl, int timeoutInSeconds)
{
Driver = new ChromeDriver();
Driver.Url = driverUrl;
Wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(timeoutInSeconds));
}
internal bool ClickElement(string cssSelector)
{
//Find the element
IWebElement element = Wait.Until(d=>ExpectedConditions.ElementIsVisible(By.CssSelector(cssSelector)))(Driver);
return Wait.Until(c => ClickElement(element, cssSelector));
}
private bool ClickElement(IWebElement element, string cssSelector)
{
try
{
//Check if element is still included in the dom
//If the element has changed a the OpenQA.Selenium.StaleElementReferenceException is thrown.
bool isDisplayed = element.Displayed;
element.Click();
return true;
}
catch (StaleElementReferenceException)
{
//wait until the element is visible again
element = Wait.Until(d => ExpectedConditions.ElementIsVisible(By.CssSelector(cssSelector)))(Driver);
return ClickElement(element, cssSelector);
}
catch (Exception)
{
return false;
}
}
}
Invocation:
DriverHelper driverHelper = new DriverHelper("http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp", 10);
driverHelper.ClickElement("input[value='csharp']:first-child");
Similarly can be used for Java.
Converting Integers to Roman Numerals - Java
Simplest solution:
public class RomanNumerals {
private static int [] arabic = {50, 40, 10, 9, 5, 4, 1};
private static String [] roman = {"L", "XL", "X", "IX", "V", "IV", "I"};
public static String convert(int arabicNumber) {
StringBuilder romanNumerals = new StringBuilder();
int remainder = arabicNumber;
for (int i=0;i<arabic.length;i++) {
while (remainder >= arabic[i]) {
romanNumerals.append(roman[i]);
remainder -= arabic[i];
}
}
return romanNumerals.toString();
}
}
GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag
Just want to add another way of doing this. I've seen multiple people on various related threads ask if you can use VerifyRenderingInServerForm without adding it to the parent page.
You actually can do this but it's a bit of a bodge.
First off create a new Page class which looks something like the following:
public partial class NoRenderPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
public override void VerifyRenderingInServerForm(Control control)
{
//Allows for printing
}
public override bool EnableEventValidation
{
get { return false; }
set { /*Do nothing*/ }
}
}
Does not need to have an .ASPX associated with it.
Then in the control you wish to render you can do something like the following.
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
var page = new NoRenderPage();
page.DesignerInitialize();
var form = new HtmlForm();
page.Controls.Add(form);
form.Controls.Add(pnl);
controlToRender.RenderControl(hw);
Now you've got your original control rendered as HTML. If you need to, add the control back into it's original position. You now have the HTML rendered, the page as normal and no changes to the page itself.
How do I set a variable to the output of a command in Bash?
Some Bash tricks I use to set variables from commands
Sorry, there is a loong answer, but as bash is a shell, where the main goal is to run other unix commands and react to resut code and/or output, ( commands are often piped filter, etc... ).
Storing command output in variables is something basic and fundamental.
Therefore, depending on
- compatibility (posix)
- kind of output (filter(s))
- number of variable to set (split or interpret)
- execution time (monitoring)
- error trapping
- repeatability of request (see long running background process, further)
- interactivity (considering user input while reading from another input file descriptor)
- do I miss something?
First simple, old, and compatible way
myPi=`echo '4*a(1)' | bc -l`
echo $myPi
3.14159265358979323844
Mostly compatible, second way
As nesting could become heavy, parenthesis was implemented for this
myPi=$(bc -l <<<'4*a(1)')
Nested sample:
SysStarted=$(date -d "$(ps ho lstart 1)" +%s)
echo $SysStarted
1480656334
bash features
Reading more than one variable (with Bashisms)
df -k /
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/dm-0 999320 529020 401488 57% /
If I just want a used value:
array=($(df -k /))
you could see an array variable:
declare -p array
declare -a array='([0]="Filesystem" [1]="1K-blocks" [2]="Used" [3]="Available" [
4]="Use%" [5]="Mounted" [6]="on" [7]="/dev/dm-0" [8]="999320" [9]="529020" [10]=
"401488" [11]="57%" [12]="/")'
Then:
echo ${array[9]}
529020
But I often use this:
{ read foo ; read filesystem size using avail prct mountpoint ; } < <(df -k /)
echo $using
529020
The first read foo
will just skip header line, but in only one command, you will populate 7 different variables:
declare -p avail filesystem foo mountpoint prct size using
declare -- avail="401488"
declare -- filesystem="/dev/dm-0"
declare -- foo="Filesystem 1K-blocks Used Available Use% Mounted on"
declare -- mountpoint="/"
declare -- prct="57%"
declare -- size="999320"
declare -- using="529020"
Or
{ read -a head;varnames=(${head[@]//[K1% -]});varnames=(${head[@]//[K1% -]});
read ${varnames[@],,} ; } < <(LANG=C df -k /)
Then:
declare -p varnames ${varnames[@],,}
declare -a varnames=([0]="Filesystem" [1]="blocks" [2]="Used" [3]="Available" [4]="Use" [5]="Mounted" [6]="on")
declare -- filesystem="/dev/dm-0"
declare -- blocks="999320"
declare -- used="529020"
declare -- available="401488"
declare -- use="57%"
declare -- mounted="/"
declare -- on=""
Or even:
{ read foo ; read filesystem dsk[{6,2,9}] prct mountpoint ; } < <(df -k /)
declare -p mountpoint dsk
declare -- mountpoint="/"
declare -a dsk=([2]="529020" [6]="999320" [9]="401488")
(Note Used
and Blocks
is switched there: read ... dsk[6] dsk[2] dsk[9] ...
)
... will work with associative arrays too: read foo disk[total] disk[used] ...
Dedicated fd
using unnamed fifo:
There is an elegent way:
users=()
while IFS=: read -u $list user pass uid gid name home bin ;do
((uid>=500)) &&
printf -v users[uid] "%11d %7d %-20s %s\n" $uid $gid $user $home
done {list}</etc/passwd
Using this way (... read -u $list; ... {list}<inputfile
) leave STDIN
free for other purposes, like user interaction.
Then
echo -n "${users[@]}"
1000 1000 user /home/user
...
65534 65534 nobody /nonexistent
and
echo ${!users[@]}
1000 ... 65534
echo -n "${users[1000]}"
1000 1000 user /home/user
This could be used with static files or even /dev/tcp/xx.xx.xx.xx/yyy
with x
for ip address or hostname and y
for port number:
{
read -u $list -a head # read header in array `head`
varnames=(${head[@]//[K1% -]}) # drop illegal chars for variable names
while read -u $list ${varnames[@],,} ;do
((pct=available*100/(available+used),pct<10)) &&
printf "WARN: FS: %-20s on %-14s %3d <10 (Total: %11u, Use: %7s)\n" \
"${filesystem#*/mapper/}" "$mounted" $pct $blocks "$use"
done
} {list}< <(LANG=C df -k)
And of course with inline documents:
while IFS=\; read -u $list -a myvar ;do
echo ${myvar[2]}
done {list}<<"eof"
foo;bar;baz
alice;bob;charlie
$cherry;$strawberry;$memberberries
eof
Sample function for populating some variables:
#!/bin/bash
declare free=0 total=0 used=0
getDiskStat() {
local foo
{
read foo
read foo total used free foo
} < <(
df -k ${1:-/}
)
}
getDiskStat $1
echo $total $used $free
Nota: declare
line is not required, just for readability.
About sudo cmd | grep ... | cut ...
shell=$(cat /etc/passwd | grep $USER | cut -d : -f 7)
echo $shell
/bin/bash
(Please avoid useless cat
! So this is just one fork less:
shell=$(grep $USER </etc/passwd | cut -d : -f 7)
All pipes (|
) implies forks. Where another process have to be run, accessing disk, libraries calls and so on.
So using sed
for sample, will limit subprocess to only one fork:
shell=$(sed </etc/passwd "s/^$USER:.*://p;d")
echo $shell
And with Bashisms:
But for many actions, mostly on small files, Bash could do the job itself:
while IFS=: read -a line ; do
[ "$line" = "$USER" ] && shell=${line[6]}
done </etc/passwd
echo $shell
/bin/bash
or
while IFS=: read loginname encpass uid gid fullname home shell;do
[ "$loginname" = "$USER" ] && break
done </etc/passwd
echo $shell $loginname ...
Going further about variable splitting...
Have a look at my answer to How do I split a string on a delimiter in Bash?
Alternative: reducing forks by using backgrounded long-running tasks
In order to prevent multiple forks like
myPi=$(bc -l <<<'4*a(1)'
myRay=12
myCirc=$(bc -l <<<" 2 * $myPi * $myRay ")
or
myStarted=$(date -d "$(ps ho lstart 1)" +%s)
mySessStart=$(date -d "$(ps ho lstart $$)" +%s)
This work fine, but running many forks is heavy and slow.
And commands like date
and bc
could make many operations, line by line!!
See:
bc -l <<<$'3*4\n5*6'
12
30
date -f - +%s < <(ps ho lstart 1 $$)
1516030449
1517853288
So we could use a long running background process to make many jobs, without having to initiate a new fork for each request.
Under bash, there is a built-in function: coproc
:
coproc bc -l
echo 4*3 >&${COPROC[1]}
read -u $COPROC answer
echo $answer
12
echo >&${COPROC[1]} 'pi=4*a(1)'
ray=42.0
printf >&${COPROC[1]} '2*pi*%s\n' $ray
read -u $COPROC answer
echo $answer
263.89378290154263202896
printf >&${COPROC[1]} 'pi*%s^2\n' $ray
read -u $COPROC answer
echo $answer
5541.76944093239527260816
As bc
is ready, running in background and I/O are ready too, there is no delay, nothing to load, open, close, before or after operation. Only the operation himself! This become a lot quicker than having to fork to bc
for each operation!
Border effect: While bc
stay running, they will hold all registers, so some variables or functions could be defined at initialisation step, as first write to ${COPROC[1]}
, just after starting the task (via coproc
).
Into a function newConnector
You may found my newConnector
function on GitHub.Com or on my own site (Note on GitHub: there are two files on my site. Function and demo are bundled into one uniq file which could be sourced for use or just run for demo.)
Sample:
source shell_connector.sh
tty
/dev/pts/20
ps --tty pts/20 fw
PID TTY STAT TIME COMMAND
29019 pts/20 Ss 0:00 bash
30745 pts/20 R+ 0:00 \_ ps --tty pts/20 fw
newConnector /usr/bin/bc "-l" '3*4' 12
ps --tty pts/20 fw
PID TTY STAT TIME COMMAND
29019 pts/20 Ss 0:00 bash
30944 pts/20 S 0:00 \_ /usr/bin/bc -l
30952 pts/20 R+ 0:00 \_ ps --tty pts/20 fw
declare -p PI
bash: declare: PI: not found
myBc '4*a(1)' PI
declare -p PI
declare -- PI="3.14159265358979323844"
The function myBc
lets you use the background task with simple syntax, and for date:
newConnector /bin/date '-f - +%s' @0 0
myDate '2000-01-01'
946681200
myDate "$(ps ho lstart 1)" boottime
myDate now now ; read utm idl </proc/uptime
myBc "$now-$boottime" uptime
printf "%s\n" ${utm%%.*} $uptime
42134906
42134906
ps --tty pts/20 fw
PID TTY STAT TIME COMMAND
29019 pts/20 Ss 0:00 bash
30944 pts/20 S 0:00 \_ /usr/bin/bc -l
32615 pts/20 S 0:00 \_ /bin/date -f - +%s
3162 pts/20 R+ 0:00 \_ ps --tty pts/20 fw
From there, if you want to end one of background processes, you just have to close its fd:
eval "exec $DATEOUT>&-"
eval "exec $DATEIN>&-"
ps --tty pts/20 fw
PID TTY STAT TIME COMMAND
4936 pts/20 Ss 0:00 bash
5256 pts/20 S 0:00 \_ /usr/bin/bc -l
6358 pts/20 R+ 0:00 \_ ps --tty pts/20 fw
which is not needed, because all fd close when the main process finishes.
pip install from git repo branch
Prepend the url prefix git+
(See VCS Support):
pip install git+https://github.com/tangentlabs/django-oscar-paypal.git@issue/34/oscar-0.6
And specify the branch name without the leading /
.
invalid use of non-static member function
You must make Foo::comparator
static or wrap it in a std::mem_fun
class object. This is because lower_bounds()
expects the comparer to be a class of object that has a call operator, like a function pointer or a functor object. Also, if you are using C++11 or later, you can also do as dwcanillas suggests and use a lambda function. C++11 also has std::bind
too.
Examples:
// Binding:
std::lower_bounds(first, last, value, std::bind(&Foo::comparitor, this, _1, _2));
// Lambda:
std::lower_bounds(first, last, value, [](const Bar & first, const Bar & second) { return ...; });
How to make flutter app responsive according to different screen size?
This class will help and then initialize the class with the init method.
import 'package:flutter/widgets.dart';
class SizeConfig {
static MediaQueryData _mediaQueryData;
static double screenWidth;
static double screenHeight;
static double blockSizeHorizontal;
static double blockSizeVertical;
static double _safeAreaHorizontal;
static double _safeAreaVertical;
static double safeBlockHorizontal;
static double safeBlockVertical;
void init(BuildContext context){
_mediaQueryData = MediaQuery.of(context);
screenWidth = _mediaQueryData.size.width;
screenHeight = _mediaQueryData.size.height;
blockSizeHorizontal = screenWidth/100;
blockSizeVertical = screenHeight/100;
_safeAreaHorizontal = _mediaQueryData.padding.left +
_mediaQueryData.padding.right;
_safeAreaVertical = _mediaQueryData.padding.top +
_mediaQueryData.padding.bottom;
safeBlockHorizontal = (screenWidth - _safeAreaHorizontal)/100;
safeBlockVertical = (screenHeight - _safeAreaVertical)/100;
}
}
then in your widgets dimension do this
Widget build(BuildContext context) {
SizeConfig().init(context);
return Container(
height: SizeConfig.safeBlockVertical * 10, //10 for example
width: SizeConfig.safeBlockHorizontal * 10, //10 for example
);}
All the credits to this post author:
https://medium.com/flutter-community/flutter-effectively-scale-ui-according-to-different-screen-sizes-2cb7c115ea0a
Hamcrest compare collections
To complement @Joe's answer:
Hamcrest provides you with three main methods to match a list:
contains
Checks for matching all the elements taking in count the order, if the list has more or less elements, it will fail
containsInAnyOrder
Checks for matching all the elements and it doesn't matter the order, if the list has more or less elements, will fail
hasItems
Checks just for the specified objects it doesn't matter if the list has more
hasItem
Checks just for one object it doesn't matter if the list has more
All of them can receive a list of objects and use equals
method for comparation or can be mixed with other matchers like @borjab mentioned:
assertThat(myList , contains(allOf(hasProperty("id", is(7L)),
hasProperty("name", is("testName1")),
hasProperty("description", is("testDesc1"))),
allOf(hasProperty("id", is(11L)),
hasProperty("name", is("testName2")),
hasProperty("description", is("testDesc2")))));
http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html#contains(E...)
http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html#containsInAnyOrder(java.util.Collection)
http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html#hasItems(T...)
How do I check if a string contains a specific word?
Check if string contains specific words?
This means the string has to be resolved into words (see note below).
One way to do this and to specify the separators is using preg_split
(doc):
<?php
function contains_word($str, $word) {
// split string into words
// separators are substrings of at least one non-word character
$arr = preg_split('/\W+/', $str, NULL, PREG_SPLIT_NO_EMPTY);
// now the words can be examined each
foreach ($arr as $value) {
if ($value === $word) {
return true;
}
}
return false;
}
function test($str, $word) {
if (contains_word($str, $word)) {
echo "string '" . $str . "' contains word '" . $word . "'\n";
} else {
echo "string '" . $str . "' does not contain word '" . $word . "'\n" ;
}
}
$a = 'How are you?';
test($a, 'are');
test($a, 'ar');
test($a, 'hare');
?>
A run gives
$ php -f test.php
string 'How are you?' contains word 'are'
string 'How are you?' does not contain word 'ar'
string 'How are you?' does not contain word 'hare'
Note: Here we do not mean word for every sequence of symbols.
A practical definition of word is in the sense the PCRE regular expression engine, where words are substrings consisting of word characters only, being separated by non-word characters.
A "word" character is any letter or digit or the underscore character,
that is, any character which can be part of a Perl " word ". The
definition of letters and digits is controlled by PCRE's character
tables, and may vary if locale-specific matching is taking place (..)
Reading a List from properties file and load with spring annotation @Value
If you are reading this and you are using Spring Boot, you have 1 more option for this feature
Usually comma separated list are very clumsy for real world use case
(And sometime not even feasible, if you want to use commas in your config):
[email protected],[email protected],[email protected],.....
With Spring Boot, you can write it like these (Index start at 0):
email.sendTo[0][email protected]
email.sendTo[1][email protected]
email.sendTo[2][email protected]
And use it like these:
@Component
@ConfigurationProperties("email")
public class EmailProperties {
private List<String> sendTo;
public List<String> getSendTo() {
return sendTo;
}
public void setSendTo(List<String> sendTo) {
this.sendTo = sendTo;
}
}
@Component
public class EmailModel {
@Autowired
private EmailProperties emailProperties;
//Use the sendTo List by
//emailProperties.getSendTo()
}
@Configuration
public class YourConfiguration {
@Bean
public EmailProperties emailProperties(){
return new EmailProperties();
}
}
#Put this in src/main/resource/META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=example.compackage.YourConfiguration
Split Spark Dataframe string column into multiple columns
pyspark.sql.functions.split()
is the right approach here - you simply need to flatten the nested ArrayType column into multiple top-level columns. In this case, where each array only contains 2 items, it's very easy. You simply use Column.getItem()
to retrieve each part of the array as a column itself:
split_col = pyspark.sql.functions.split(df['my_str_col'], '-')
df = df.withColumn('NAME1', split_col.getItem(0))
df = df.withColumn('NAME2', split_col.getItem(1))
The result will be:
col1 | my_str_col | NAME1 | NAME2
-----+------------+-------+------
18 | 856-yygrm | 856 | yygrm
201 | 777-psgdg | 777 | psgdg
I am not sure how I would solve this in a general case where the nested arrays were not the same size from Row to Row.
Passing multiple argument through CommandArgument of Button in Asp.net
You can pass semicolon separated values as command argument and then split the string and use it.
<asp:TemplateField ShowHeader="false">
<ItemTemplate>
<asp:LinkButton ID="lnkCustomize" Text="Customize" CommandName="Customize" CommandArgument='<%#Eval("IdTemplate") + ";" +Eval("EntityId")%>' runat="server">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
at server side
protected void gridview_RowCommand(object sender, GridViewCommandEventArgs e)
{
string[] arg = new string[2];
arg = e.CommandArgument.ToString().Split(';');
Session["IdTemplate"] = arg[0];
Session["IdEntity"] = arg[1];
Response.Redirect("Samplepage.aspx");
}
Hope it helps!!!!
Error # 1045 - Cannot Log in to MySQL server -> phpmyadmin
If you logged into "phpmyadmin", then logged out, you might have trouble attempting to log back in on the same browser window. The logout sends the browser to a URL that looks like this:
http://localhost/phpmyadmin/index.php?db=&token=354a350abed02588e4b59f44217826fd&old_usr=tester
But for me, on Mac OS X in Safari browser, that URL just doesn't want to work. Therefore, I have to put in the clean URL:
http://localhost/phpmyadmin
Don't know why, but as of today, Oct 20, 2015, that is what I am experiencing.
How can I read SMS messages from the device programmatically in Android?
It is a trivial process. You can see a good example in the source code SMSPopup
Examine the following methods:
SmsMmsMessage getSmsDetails(Context context, long ignoreThreadId, boolean unreadOnly)
long findMessageId(Context context, long threadId, long _timestamp, int messageType
void setMessageRead(Context context, long messageId, int messageType)
void deleteMessage(Context context, long messageId, long threadId, int messageType)
this is the method for reading:
SmsMmsMessage getSmsDetails(Context context,
long ignoreThreadId, boolean unreadOnly)
{
String SMS_READ_COLUMN = "read";
String WHERE_CONDITION = unreadOnly ? SMS_READ_COLUMN + " = 0" : null;
String SORT_ORDER = "date DESC";
int count = 0;
// Log.v(WHERE_CONDITION);
if (ignoreThreadId > 0) {
// Log.v("Ignoring sms threadId = " + ignoreThreadId);
WHERE_CONDITION += " AND thread_id != " + ignoreThreadId;
}
Cursor cursor = context.getContentResolver().query(
SMS_INBOX_CONTENT_URI,
new String[] { "_id", "thread_id", "address", "person", "date", "body" },
WHERE_CONDITION,
null,
SORT_ORDER);
if (cursor != null) {
try {
count = cursor.getCount();
if (count > 0) {
cursor.moveToFirst();
// String[] columns = cursor.getColumnNames();
// for (int i=0; i<columns.length; i++) {
// Log.v("columns " + i + ": " + columns[i] + ": " + cursor.getString(i));
// }
long messageId = cursor.getLong(0);
long threadId = cursor.getLong(1);
String address = cursor.getString(2);
long contactId = cursor.getLong(3);
String contactId_string = String.valueOf(contactId);
long timestamp = cursor.getLong(4);
String body = cursor.getString(5);
if (!unreadOnly) {
count = 0;
}
SmsMmsMessage smsMessage = new SmsMmsMessage(context, address,
contactId_string, body, timestamp,
threadId, count, messageId, SmsMmsMessage.MESSAGE_TYPE_SMS);
return smsMessage;
}
} finally {
cursor.close();
}
}
return null;
}
There are No resources that can be added or removed from the server
For this you need to update your Project Facets setting.
Project (right click) -> Properties -> Project Facets from left
navigation.
If it is not open...click on the link, Check the Dynamic Web Module Check Box and select the respective version (Probably 2.4). Click on Apply Button and then Click on OK.
How do I populate a JComboBox with an ArrayList?
DefaultComboBoxModel dml= new DefaultComboBoxModel();
for (int i = 0; i < <ArrayList>.size(); i++) {
dml.addElement(<ArrayList>.get(i).getField());
}
<ComboBoxName>.setModel(dml);
Understandable code.Edit<>
with type as required.
difference between variables inside and outside of __init__()
As noted by S.Lott,
Variable set outside init belong to the class. They're shared by
all instances.
Variables created inside init (and all other method functions) and
prefaced with self. belong to the object instance.
However,
Note that class variables can be accessed via self.<var> until they are masked by an object variable with a similar name This means that reading self.<var> before assigning it a value will return the value of Class.<var> but afterwards it will return obj.<var> . Here is an example
In [20]: class MyClass:
...: elem = 123
...:
...: def update(self,i):
...: self.elem=i
...: def print(self):
...: print (MyClass.elem, self.elem)
...:
...: c1 = MyClass()
...: c2 = MyClass()
...: c1.print()
...: c2.print()
123 123
123 123
In [21]: c1.update(1)
...: c2.update(42)
...: c1.print()
...: c2.print()
123 1
123 42
In [22]: MyClass.elem=22
...: c1.print()
...: c2.print()
22 1
22 42
Second note: Consider slots. They may offer a better way to implement object variables.
SELECT * FROM in MySQLi
You can still use it (mysqli is just another way of communicating with the server, the SQL language itself is expanded, not changed). Prepared statements are safer, though - since you don't need to go through the trouble of properly escaping your values each time. You can leave them as they were, if you want to but the risk of sql piggybacking is reduced if you switch.
Implode an array with JavaScript?
Array.join
is what you need, but if you like, the friendly people at phpjs.org have created implode
for you.
Then some slightly off topic ranting. As @jon_darkstar alreadt pointed out, jQuery is JavaScript and not vice versa. You don't need to know JavaScript to be able to understand how to use jQuery, but it certainly doesn't hurt and once you begin to appreciate reusability or start looking at the bigger picture you absolutely need to learn it.
How to get the body's content of an iframe in Javascript?
AFAIK, an Iframe cannot be used that way. You need to point its src attribute to another page.
Here's how to get its body content using plane old javascript. This works with both IE and Firefox.
function getFrameContents(){
var iFrame = document.getElementById('id_description_iframe');
var iFrameBody;
if ( iFrame.contentDocument )
{ // FF
iFrameBody = iFrame.contentDocument.getElementsByTagName('body')[0];
}
else if ( iFrame.contentWindow )
{ // IE
iFrameBody = iFrame.contentWindow.document.getElementsByTagName('body')[0];
}
alert(iFrameBody.innerHTML);
}
Passing an array by reference in C?
In plain C you can use a pointer/size combination in your API.
void doSomething(MyStruct* mystruct, size_t numElements)
{
for (size_t i = 0; i < numElements; ++i)
{
MyStruct current = mystruct[i];
handleElement(current);
}
}
Using pointers is the closest to call-by-reference available in C.
Unable to copy ~/.ssh/id_rsa.pub
Try this and it will work like a charm. I was having the same error but this approach did the trick for me:
ssh USER@REMOTE "cat file"|xclip -i
How to save image in database using C#
This is a method that uses a FileUpload control in asp.net:
byte[] buffer = new byte[fu.FileContent.Length];
Stream s = fu.FileContent;
s.Read(buffer, 0, buffer.Length);
//Then save 'buffer' to the varbinary column in your db where you want to store the image.
Notepad++ incrementally replace
Not sure about regex, but there is a way for you to do this in Notepad++, although it isn't very flexible.
In the example that you gave, hold Alt
and select the column of numbers that you wish to change. Then go to Edit->Column Editor
and select the Number to Insert
radio button in the window that appears. Then specify your initial number and increment, and hit OK. It should write out the incremented numbers.
Note: this also works with the Multi-editing
feature (selecting several locations while maintaining Ctrl key pressed).
This is, however, not anywhere near the flexibility that most people would find useful. Notepad++ is great, but if you want a truly powerful editor that can do things like this with ease, I'd say use Vim.
Returning from a void function
The first way is "more correct", what intention could there be to express? If the code ends, it ends. That's pretty clear, in my opinion.
I don't understand what could possibly be confusing and need clarification. If there's no looping construct being used, then what could possibly happen other than that the function stops executing?
I would be severly annoyed by such a pointless extra return
statement at the end of a void
function, since it clearly serves no purpose and just makes me feel the original programmer said "I was confused about this, and now you can be too!" which is not very nice.
Selecting all text in HTML text input when clicked
I know this is old, but the best option is to now use the new placeholder
HTML attribute if possible:
<input type="text" id="userid" name="userid" placeholder="Please enter the user ID" />
This will cause the text to show unless a value is entered, eliminating the need to select text or clear inputs.
TypeScript error: Type 'void' is not assignable to type 'boolean'
Your code is passing a function as an argument to find
. That function takes an element
argument (of type Conversation
) and returns void
(meaning there is no return value). TypeScript describes this as (element: Conversation) => void'
What TypeScript is saying is that the find
function doesn't expect to receive a function that takes a Conversation and returns void. It expects a function that takes a Conversations
, a number
and a Conversation
array, and that this function should return a boolean
.
So bottom line is that you either need to change your code to pass in the values to find
correctly, or else you need to provide an overload to the definition of find
in your definition file that accepts a Conversation
and returns void
.
Format certain floating dataframe columns into percentage in pandas
Often times we are interested in calculating the full significant digits, but
for the visual aesthetics, we may want to see only few decimal point when we display the dataframe.
In jupyter-notebook, pandas can utilize the html formatting taking advantage of the method called style
.
For the case of just seeing two significant digits of some columns, we can use this code snippet:
Given dataframe
import numpy as np
import pandas as pd
df = pd.DataFrame({'var1': [1.458315, 1.576704, 1.629253, 1.6693310000000001, 1.705139, 1.740447, 1.77598, 1.812037, 1.85313, 1.9439849999999999],
'var2': [1.500092, 1.6084450000000001, 1.652577, 1.685456, 1.7120959999999998, 1.741961, 1.7708009999999998, 1.7993270000000001, 1.8229819999999999, 1.8684009999999998],
'var3': [-0.0057090000000000005, -0.005122, -0.0047539999999999995, -0.003525, -0.003134, -0.0012230000000000001, -0.0017230000000000001, -0.002013, -0.001396, 0.005732]})
print(df)
var1 var2 var3
0 1.458315 1.500092 -0.005709
1 1.576704 1.608445 -0.005122
2 1.629253 1.652577 -0.004754
3 1.669331 1.685456 -0.003525
4 1.705139 1.712096 -0.003134
5 1.740447 1.741961 -0.001223
6 1.775980 1.770801 -0.001723
7 1.812037 1.799327 -0.002013
8 1.853130 1.822982 -0.001396
9 1.943985 1.868401 0.005732
Style to get required format
df.style.format({'var1': "{:.2f}",'var2': "{:.2f}",'var3': "{:.2%}"})
Gives:
var1 var2 var3
id
0 1.46 1.50 -0.57%
1 1.58 1.61 -0.51%
2 1.63 1.65 -0.48%
3 1.67 1.69 -0.35%
4 1.71 1.71 -0.31%
5 1.74 1.74 -0.12%
6 1.78 1.77 -0.17%
7 1.81 1.80 -0.20%
8 1.85 1.82 -0.14%
9 1.94 1.87 0.57%
Update
If display command is not found try following:
from IPython.display import display
df_style = df.style.format({'var1': "{:.2f}",'var2': "{:.2f}",'var3': "{:.2%}"})
display(df_style)
Requirements
- To use
display
command, you need to have installed Ipython in your machine.
- The
display
command does not work in online python interpreter which do not have IPyton
installed such as https://repl.it/languages/python3
- The display command works in jupyter-notebook, jupyter-lab, Google-colab, kaggle-kernels, IBM-watson,Mode-Analytics and many other platforms out of the box, you do not even have to import display from IPython.display
c# replace \" characters
Try it like this:
Replace("\\\"","");
This will replace occurrences of \"
with empty string.
Ex:
string t = "\\\"the dog is my friend\\\"";
t = t.Replace("\\\"","");
This will result in:
the dog is my friend
Can't start Tomcat as Windows Service
The simplest answer that worked for me was the one mentioned by Prashant, and edited by Bluish.
Go to Start > Configure Tomcat > Startup > Mode = Java Shutdown > Mode
= Java
Unfortunately I had(and possibly others) to do this in a different way, I went to the tomcat bin directory and ran the "tomcat7w" application, which is how I changed the configuration.
There I was able to change the startup mode and shutdown mode to Java. Like this:
Step1) Locate
tomcat7w:
general location => %TomCatHomeDIR%/bin
In my case tomcat was in the xampp folder so my address was:
C:\xampp\tomcat\bin
tomcat7w file location screenshot
Step2) Launch tomcat7w && change the Mode in the Startup and Shutdown tabs
tomcat7w startup tab screenshot
Note >This based on version 7.0.22 that comes standard with XAMPP.
How to display databases in Oracle 11g using SQL*Plus
Maybe you could use this view, but i'm not sure.
select * from v$database;
But I think It will only show you info about the current db.
Other option, if the db is running in linux... whould be something like this:
SQL>!grep SID $TNS_ADMIN/tnsnames.ora | grep -v PLSExtProc
How to access command line arguments of the caller inside a function?
My reading of the Bash Reference Manual says this stuff is captured in BASH_ARGV,
although it talks about "the stack" a lot.
#!/bin/bash
function argv {
for a in ${BASH_ARGV[*]} ; do
echo -n "$a "
done
echo
}
function f {
echo f $1 $2 $3
echo -n f ; argv
}
function g {
echo g $1 $2 $3
echo -n g; argv
f
}
f boo bar baz
g goo gar gaz
Save in f.sh
$ ./f.sh arg0 arg1 arg2
f boo bar baz
farg2 arg1 arg0
g goo gar gaz
garg2 arg1 arg0
f
farg2 arg1 arg0
Animate scroll to ID on page load
try with following code. make elements with class name page-scroll and keep id name to href
of corresponding links
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: ($($anchor.attr('href')).offset().top - 50)
}, 1250, 'easeInOutExpo');
event.preventDefault();
});
Limiting the number of characters in a JTextField
_x000D_
_x000D_
private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) { _x000D_
if (jTextField1.getText().length()>=3) {_x000D_
getToolkit().beep();_x000D_
evt.consume();_x000D_
}_x000D_
}
_x000D_
_x000D_
_x000D_
Testing HTML email rendering
If you don't want to use a submission service like Litmus (Litmus is the best, BTW) then you're just going to have to run Outlook 2007 to test your email.
It sounds like you want something a little more automatic (though I'm not sure why), but fortunately Outlook is easy to automate using Visual Basic for Applications (VBA).
You can write a VBA tool that runs from the command line to generate an email, load the email up in Outlook, and even capture a screenshot if you wish. (Presumably this is what the Litmus team does on the backend.)
(BTW, do not attempt to use MS Word to test mail; the renderer is similar but subtle differences in page layout can affect the rendering of your email.)
Increment a database field by 1
You didn't say what you're trying to do, but you hinted at it well enough in the comments to the other answer. I think you're probably looking for an auto increment column
create table logins (userid int auto_increment primary key,
username varchar(30), password varchar(30));
then no special code is needed on insert. Just
insert into logins (username, password) values ('user','pass');
The MySQL API has functions to tell you what userid was created when you execute this statement in client code.
Git - Won't add files?
Best bet is to copy your folder. Delete the original. Clone the project from github, copy your new files into the new cloned folder, and then try again.
How to create a multiline UITextfield?
Besides from the multiple line behaviour, the main difference between UITextView and UITextField is that the UITextView does not propose a placeholder. To bypass this limitation, you can use a UITextView with a "fake placeholder."
See this SO question for details: Placeholder in UITextView.
Convert Rows to columns using 'Pivot' in SQL Server
I'm writing an sp that could be useful for this purpose, basically this sp pivot any table and return a new table pivoted or return just the set of data, this is the way to execute it:
Exec dbo.rs_pivot_table @schema=dbo,@table=table_name,@column=column_to_pivot,@agg='sum([column_to_agg]),avg([another_column_to_agg]),',
@sel_cols='column_to_select1,column_to_select2,column_to_select1',@new_table=returned_table_pivoted;
please note that in the parameter @agg the column names must be with '['
and the parameter must end with a comma ','
SP
Create Procedure [dbo].[rs_pivot_table]
@schema sysname=dbo,
@table sysname,
@column sysname,
@agg nvarchar(max),
@sel_cols varchar(max),
@new_table sysname,
@add_to_col_name sysname=null
As
--Exec dbo.rs_pivot_table dbo,##TEMPORAL1,tip_liq,'sum([val_liq]),sum([can_liq]),','cod_emp,cod_con,tip_liq',##TEMPORAL1PVT,'hola';
Begin
Declare @query varchar(max)='';
Declare @aggDet varchar(100);
Declare @opp_agg varchar(5);
Declare @col_agg varchar(100);
Declare @pivot_col sysname;
Declare @query_col_pvt varchar(max)='';
Declare @full_query_pivot varchar(max)='';
Declare @ind_tmpTbl int; --Indicador de tabla temporal 1=tabla temporal global 0=Tabla fisica
Create Table #pvt_column(
pivot_col varchar(100)
);
Declare @column_agg table(
opp_agg varchar(5),
col_agg varchar(100)
);
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(@table) AND type in (N'U'))
Set @ind_tmpTbl=0;
ELSE IF OBJECT_ID('tempdb..'+ltrim(rtrim(@table))) IS NOT NULL
Set @ind_tmpTbl=1;
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(@new_table) AND type in (N'U')) OR
OBJECT_ID('tempdb..'+ltrim(rtrim(@new_table))) IS NOT NULL
Begin
Set @query='DROP TABLE '+@new_table+'';
Exec (@query);
End;
Select @query='Select distinct '+@column+' From '+(case when @ind_tmpTbl=1 then 'tempdb.' else '' end)+@schema+'.'+@table+' where '+@column+' is not null;';
Print @query;
Insert into #pvt_column(pivot_col)
Exec (@query)
While charindex(',',@agg,1)>0
Begin
Select @aggDet=Substring(@agg,1,charindex(',',@agg,1)-1);
Insert Into @column_agg(opp_agg,col_agg)
Values(substring(@aggDet,1,charindex('(',@aggDet,1)-1),ltrim(rtrim(replace(substring(@aggDet,charindex('[',@aggDet,1),charindex(']',@aggDet,1)-4),')',''))));
Set @agg=Substring(@agg,charindex(',',@agg,1)+1,len(@agg))
End
Declare cur_agg cursor read_only forward_only local static for
Select
opp_agg,col_agg
from @column_agg;
Open cur_agg;
Fetch Next From cur_agg
Into @opp_agg,@col_agg;
While @@fetch_status=0
Begin
Declare cur_col cursor read_only forward_only local static for
Select
pivot_col
From #pvt_column;
Open cur_col;
Fetch Next From cur_col
Into @pivot_col;
While @@fetch_status=0
Begin
Select @query_col_pvt='isnull('+@opp_agg+'(case when '+@column+'='+quotename(@pivot_col,char(39))+' then '+@col_agg+
' else null end),0) as ['+lower(Replace(Replace(@opp_agg+'_'+convert(varchar(100),@pivot_col)+'_'+replace(replace(@col_agg,'[',''),']',''),' ',''),'&',''))+
(case when @add_to_col_name is null then space(0) else '_'+isnull(ltrim(rtrim(@add_to_col_name)),'') end)+']'
print @query_col_pvt
Select @full_query_pivot=@full_query_pivot+@query_col_pvt+', '
--print @full_query_pivot
Fetch Next From cur_col
Into @pivot_col;
End
Close cur_col;
Deallocate cur_col;
Fetch Next From cur_agg
Into @opp_agg,@col_agg;
End
Close cur_agg;
Deallocate cur_agg;
Select @full_query_pivot=substring(@full_query_pivot,1,len(@full_query_pivot)-1);
Select @query='Select '+@sel_cols+','+@full_query_pivot+' into '+@new_table+' From '+(case when @ind_tmpTbl=1 then 'tempdb.' else '' end)+
@schema+'.'+@table+' Group by '+@sel_cols+';';
print @query;
Exec (@query);
End;
GO
This is an example of execution:
Exec dbo.rs_pivot_table @schema=dbo,@table=##TEMPORAL1,@column=tip_liq,@agg='sum([val_liq]),avg([can_liq]),',@sel_cols='cod_emp,cod_con,tip_liq',@new_table=##TEMPORAL1PVT;
then Select * From ##TEMPORAL1PVT
would return:
Spring Boot application.properties value not populating
The way you are performing the injection of the property will not work, because the injection is done after the constructor is called.
You need to do one of the following:
Better solution
@Component
public class MyBean {
private final String prop;
@Autowired
public MyBean(@Value("${some.prop}") String prop) {
this.prop = prop;
System.out.println("================== " + prop + "================== ");
}
}
Solution that will work but is less testable and slightly less readable
@Component
public class MyBean {
@Value("${some.prop}")
private String prop;
public MyBean() {
}
@PostConstruct
public void init() {
System.out.println("================== " + prop + "================== ");
}
}
Also note that is not Spring Boot specific but applies to any Spring application
moment.js 24h format
You can use
moment("15", "hh").format('LT')
to convert the time to 12 hours format like this 3:00 PM
JavaScript: How do I print a message to the error console?
_x000D_
_x000D_
function foo() {_x000D_
function bar() {_x000D_
console.trace("Tracing is Done here");_x000D_
}_x000D_
bar();_x000D_
}_x000D_
_x000D_
foo();
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
console.log(console); //to print console object_x000D_
console.clear('console.clear'); //to clear console_x000D_
console.log('console.log'); //to print log message_x000D_
console.info('console.info'); //to print log message _x000D_
console.debug('console.debug'); //to debug message_x000D_
console.warn('console.warn'); //to print Warning_x000D_
console.error('console.error'); //to print Error_x000D_
console.table(["car", "fruits", "color"]);//to print data in table structure_x000D_
console.assert('console.assert'); //to print Error_x000D_
console.dir({"name":"test"});//to print object_x000D_
console.dirxml({"name":"test"});//to print object as xml formate
_x000D_
_x000D_
_x000D_
To Print Error:- console.error('x=%d', x);
_x000D_
_x000D_
console.log("This is the outer level");_x000D_
console.group();_x000D_
console.log("Level 2");_x000D_
console.group();_x000D_
console.log("Level 3");_x000D_
console.warn("More of level 3");_x000D_
console.groupEnd();_x000D_
console.log("Back to level 2");_x000D_
console.groupEnd();_x000D_
console.log("Back to the outer level");
_x000D_
_x000D_
_x000D_
Running command line silently with VbScript and getting output?
I am pretty new to all of this, but I found that if the script is started via CScript.exe (console scripting host) there is no window popping up on exec(): so when running:
cscript myscript.vbs //nologo
any .Exec() calls in the myscript.vbs do not open an extra window, meaning
that you can use the first variant of your original solution (using exec).
(Note that the two forward slashes in the above code are intentional, see cscript /?)
C#: calling a button event handler method without actually clicking the button
btnTest_Click(null, null);
Provided that the method isn't using either of these parameters (it's very common not to.)
To be honest though this is icky. If you have code that needs to be called you should follow the following convention:
protected void btnTest_Click(object sender, EventArgs e)
{
SomeSub();
}
protected void SomeOtherFunctionThatNeedsToCallTheCode()
{
SomeSub();
}
protected void SomeSub()
{
// ...
}
How to format LocalDate to string?
There is a built-in way to format LocalDate in Joda library
import org.joda.time.LocalDate;
LocalDate localDate = LocalDate.now();
String dateFormat = "MM/dd/yyyy";
localDate.toString(dateFormat);
In case you don't have it already - add this to the build.gradle:
implementation 'joda-time:joda-time:2.9.5'
Happy coding! :)
Not able to change TextField Border Color
We have tried custom search box with the pasted snippet. This code will useful for all kind of TextFiled
decoration in Flutter. Hope this snippet will helpful for others.
Container(
margin: EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 10.0),
child: new Theme(
data: new ThemeData(
hintColor: Colors.white,
primaryColor: Colors.white,
primaryColorDark: Colors.white,
),
child:Padding(
padding: EdgeInsets.all(10.0),
child: TextField(
style: TextStyle(color: Colors.white),
onChanged: (value) {
filterSearchResults(value);
},
controller: editingController,
decoration: InputDecoration(
labelText: "Search",
hintText: "Search",
prefixIcon: Icon(Icons.search,color: Colors.white,),
enabled: true,
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.white),
borderRadius: BorderRadius.all(Radius.circular(25.0))),
border: OutlineInputBorder(
borderSide: const BorderSide(color: Colors.white, width: 0.0),
borderRadius: BorderRadius.all(Radius.circular(25.0)))),
),
),
),
),
System.Net.WebException HTTP status code
You can try this code to get HTTP status code from WebException. It works in Silverlight too because SL does not have WebExceptionStatus.ProtocolError defined.
HttpStatusCode GetHttpStatusCode(WebException we)
{
if (we.Response is HttpWebResponse)
{
HttpWebResponse response = (HttpWebResponse)we.Response;
return response.StatusCode;
}
return null;
}
ValueError: invalid literal for int () with base 10
I had hard time figuring out the actual reason, it happens when we dont read properly from file.
you need to open file and read with readlines() method as below:
with open('/content/drive/pre-processed-users1.1.tsv') as f:
file=f.readlines()
It corrects the formatted output
How can I order a List<string>?
List<string> myCollection = new List<string>()
{
"Bob", "Bob","Alex", "Abdi", "Abdi", "Bob", "Alex", "Bob","Abdi"
};
myCollection.Sort();
foreach (var name in myCollection.Distinct())
{
Console.WriteLine(name + " " + myCollection.Count(x=> x == name));
}
output:
Abdi 3
Alex 2
Bob 4
What is Python used for?
Why should you learn Python Programming Language?
Python offers a stepping stone into the world of programming. Even though Python Programming Language has been around for 25 years, it is still rising in popularity.
Some of the biggest advantage of Python are it's
- Easy to Read & Easy to Learn
- Very productive or small as well as big projects
- Big libraries for many things
What is Python Programming Language used for?
As a general purpose programming language, Python can be used for multiple things. Python can be easily used for small, large, online and offline projects. The best options for utilizing Python are web development, simple scripting and data analysis. Below are a few examples of what Python will let you do:
Web Development:
You can use Python to create web applications on many levels of complexity. There are many excellent Python web frameworks including, Pyramid, Django and Flask, to name a few.
Data Analysis:
Python is the leading language of choice for many data scientists. Python has grown in popularity, within this field, due to its excellent libraries including; NumPy and Pandas and its superb libraries for data visualisation like Matplotlib and Seaborn.
Machine Learning:
What if you could predict customer satisfaction or analyse what factors will affect household pricing or to predict stocks over the next few days, based on previous years data? There are many wonderful libraries implementing machine learning algorithms such as Scikit-Learn, NLTK and TensorFlow.
Computer Vision:
You can do many interesting things such as Face detection, Color detection while using Opencv and Python.
Internet Of Things With Raspberry Pi:
Raspberry Pi is a very tiny and affordable computer which was developed for education and has gained enormous popularity among hobbyists with do-it-yourself hardware and automation. You can even build a robot and automate your entire home. Raspberry Pi can be used as the brain for your robot in order to perform various actions and/or react to the environment. The coding on a Raspberry Pi can be performed using Python. The Possibilities are endless!
Game Development:
Create a video game using module Pygame. Basically, you use Python to write the logic of the game. PyGame applications can run on Android devices.
Web Scraping:
If you need to grab data from a website but the site does not have an API to expose data, use Python to scraping data.
Writing Scripts:
If you're doing something manually and want to automate repetitive stuff, such as emails, it's not difficult to automate once you know the basics of this language.
Browser Automation:
Perform some neat things such as opening a browser and posting a Facebook status, you can do it with Selenium with Python.
GUI Development:
Build a GUI application (desktop app) using Python modules Tkinter, PyQt to support it.
Rapid Prototyping:
Python has libraries for just about everything. Use it to quickly built a (lower-performance, often less powerful) prototype. Python is also great for validating ideas or products for established companies and start-ups alike.
Python can be used in so many different projects. If you're a programmer looking for a new language, you want one that is growing in popularity. As a newcomer to programming, Python is the perfect choice for learning quickly and easily.
How to change the Title of the window in Qt?
void QWidget::setWindowTitle ( const QString & )
EDIT: If you are using QtDesigner, on the property tab, there is an editable property called windowTitle which can be found under the QWidget section. The property tab can usually be found on the lower right part of the designer window.
SQL Query to find missing rows between two related tables
SELECT A.ABC_ID, A.VAL FROM A WHERE NOT EXISTS
(SELECT * FROM B WHERE B.ABC_ID = A.ABC_ID AND B.VAL = A.VAL)
or
SELECT A.ABC_ID, A.VAL FROM A WHERE VAL NOT IN
(SELECT VAL FROM B WHERE B.ABC_ID = A.ABC_ID)
or
SELECT A.ABC_ID, A.VAL LEFT OUTER JOIN B
ON A.ABC_ID = B.ABC_ID AND A.VAL = B.VAL FROM A WHERE B.VAL IS NULL
Please note that these queries do not require that ABC_ID be in table B at all. I think that does what you want.
using if else with eval in aspx page
You can try
c#
public string ProcessMyDataItem(object myValue)
{
if (myValue == null)
{
return "0 %"";
}
else
{
if(Convert.ToInt32(myValue) < 50)
return "0";
else
return myValue.ToString() + "%";
}
}
asp
<div class="tooltip" style="display: none">
<div style="text-align: center; font-weight: normal">
Value =<%# ProcessMyDataItem(Eval("Percentage")) %> </div>
</div>
How to use XPath in Python?
You can use the simple soupparser
from lxml
Example:
from lxml.html.soupparser import fromstring
tree = fromstring("<a>Find me!</a>")
print tree.xpath("//a/text()")
Explain the different tiers of 2 tier & 3 tier architecture?
In a modern two-tier architecture, the server holds both the application and the data. The application resides on the server rather than the client, probably because the server will have more processing power and disk space than the PC.
In a three-tier architecture, the data and applications are split onto seperate servers, with the server-side distributed between a database server and an application server. The client is a front end, simply requesting and displaying data. Reason being that each server will be dedicated to processing either data or application requests, hence a more manageable system and less contention for resources will occur.
You can refer to Difference between three tier vs. n-tier
How to catch integer(0)?
Inspired by Andrie's answer, you could use identical
and avoid any attribute problems by using the fact that it is the empty set of that class of object and combine it with an element of that class:
attr(a, "foo") <- "bar"
identical(1L, c(a, 1L))
#> [1] TRUE
Or more generally:
is.empty <- function(x, mode = NULL){
if (is.null(mode)) mode <- class(x)
identical(vector(mode, 1), c(x, vector(class(x), 1)))
}
b <- numeric(0)
is.empty(a)
#> [1] TRUE
is.empty(a,"numeric")
#> [1] FALSE
is.empty(b)
#> [1] TRUE
is.empty(b,"integer")
#> [1] FALSE
Writing File to Temp Folder
System.IO.Path.GetTempPath()
The path specified by the TMP
environment variable.
The path specified by the TEMP
environment variable.
The path specified by the USERPROFILE
environment variable.
The Windows directory.
What are the differences between delegates and events?
NOTE: If you have access to C# 5.0 Unleashed, read the "Limitations on Plain Use of Delegates" in Chapter 18 titled "Events" to understand better the differences between the two.
It always helps me to have a simple, concrete example. So here's one for the community. First I show how you can use delegates alone to do what Events do for us. Then I show how the same solution would work with an instance of EventHandler
. And then I explain why we DON'T want to do what I explain in the first example. This post was inspired by an article by John Skeet.
Example 1: Using public delegate
Suppose I have a WinForms app with a single drop-down box. The drop-down is bound to an List<Person>
. Where Person has properties of Id, Name, NickName, HairColor. On the main form is a custom user control that shows the properties of that person. When someone selects a person in the drop-down the labels in the user control update to show the properties of the person selected.
Here is how that works. We have three files that help us put this together:
- Mediator.cs -- static class holds the delegates
- Form1.cs -- main form
- DetailView.cs -- user control shows all details
Here is the relevant code for each of the classes:
class Mediator
{
public delegate void PersonChangedDelegate(Person p); //delegate type definition
public static PersonChangedDelegate PersonChangedDel; //delegate instance. Detail view will "subscribe" to this.
public static void OnPersonChanged(Person p) //Form1 will call this when the drop-down changes.
{
if (PersonChangedDel != null)
{
PersonChangedDel(p);
}
}
}
Here is our user control:
public partial class DetailView : UserControl
{
public DetailView()
{
InitializeComponent();
Mediator.PersonChangedDel += DetailView_PersonChanged;
}
void DetailView_PersonChanged(Person p)
{
BindData(p);
}
public void BindData(Person p)
{
lblPersonHairColor.Text = p.HairColor;
lblPersonId.Text = p.IdPerson.ToString();
lblPersonName.Text = p.Name;
lblPersonNickName.Text = p.NickName;
}
}
Finally we have the following code in our Form1.cs. Here we are Calling OnPersonChanged, which calls any code subscribed to the delegate.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Mediator.OnPersonChanged((Person)comboBox1.SelectedItem); //Call the mediator's OnPersonChanged method. This will in turn call all the methods assigned (i.e. subscribed to) to the delegate -- in this case `DetailView_PersonChanged`.
}
Ok. So that's how you would get this working without using events and just using delegates. We just put a public delegate into a class -- you can make it static or a singleton, or whatever. Great.
BUT, BUT, BUT, we do not want to do what I just described above. Because public fields are bad for many, many reason. So what are our options? As John Skeet describes, here are our options:
- A public delegate variable (this is what we just did above. don't do this. i just told you above why it's bad)
- Put the delegate into a property with a get/set (problem here is that subscribers could override each other -- so we could subscribe a bunch of methods to the delegate and then we could accidentally say
PersonChangedDel = null
, wiping out all of the other subscriptions. The other problem that remains here is that since the users have access to the delegate, they can invoke the targets in the invocation list -- we don't want external users having access to when to raise our events.
- A delegate variable with AddXXXHandler and RemoveXXXHandler methods
This third option is essentially what an event gives us. When we declare an EventHandler, it gives us access to a delegate -- not publicly, not as a property, but as this thing we call an event that has just add/remove accessors.
Let's see what the same program looks like, but now using an Event instead of the public delegate (I've also changed our Mediator to a singleton):
Example 2: With EventHandler instead of a public delegate
Mediator:
class Mediator
{
private static readonly Mediator _Instance = new Mediator();
private Mediator() { }
public static Mediator GetInstance()
{
return _Instance;
}
public event EventHandler<PersonChangedEventArgs> PersonChanged; //this is just a property we expose to add items to the delegate.
public void OnPersonChanged(object sender, Person p)
{
var personChangedDelegate = PersonChanged as EventHandler<PersonChangedEventArgs>;
if (personChangedDelegate != null)
{
personChangedDelegate(sender, new PersonChangedEventArgs() { Person = p });
}
}
}
Notice that if you F12 on the EventHandler, it will show you the definition is just a generic-ified delegate with the extra "sender" object:
public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e);
The User Control:
public partial class DetailView : UserControl
{
public DetailView()
{
InitializeComponent();
Mediator.GetInstance().PersonChanged += DetailView_PersonChanged;
}
void DetailView_PersonChanged(object sender, PersonChangedEventArgs e)
{
BindData(e.Person);
}
public void BindData(Person p)
{
lblPersonHairColor.Text = p.HairColor;
lblPersonId.Text = p.IdPerson.ToString();
lblPersonName.Text = p.Name;
lblPersonNickName.Text = p.NickName;
}
}
Finally, here's the Form1.cs code:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Mediator.GetInstance().OnPersonChanged(this, (Person)comboBox1.SelectedItem);
}
Because the EventHandler wants and EventArgs as a parameter, I created this class with just a single property in it:
class PersonChangedEventArgs
{
public Person Person { get; set; }
}
Hopefully that shows you a bit about why we have events and how they are different -- but functionally the same -- as delegates.
Definition of "downstream" and "upstream"
Upstream Called Harmful
There is, alas, another use of "upstream" that the other answers here are not getting at, namely to refer to the parent-child relationship of commits within a repo. Scott Chacon in the Pro Git book is particularly prone to this, and the results are unfortunate. Do not imitate this way of speaking.
For example, he says of a merge resulting a fast-forward that this happens because
the commit pointed to by the branch you merged in was directly
upstream of the commit you’re on
He wants to say that commit B is the only child of the only child of ... of the only child of commit A, so to merge B into A it is sufficient to move the ref A to point to commit B. Why this direction should be called "upstream" rather than "downstream", or why the geometry of such a pure straight-line graph should be described "directly upstream", is completely unclear and probably arbitrary. (The man page for git-merge
does a far better job of explaining this relationship when it says that "the current branch head is an ancestor of the named commit." That is the sort of thing Chacon should have said.)
Indeed, Chacon himself appears to use "downstream" later to mean exactly the same thing, when he speaks of rewriting all child commits of a deleted commit:
You must rewrite all the commits downstream from 6df76 to fully remove
this file from your Git history
Basically he seems not to have any clear idea what he means by "upstream" and "downstream" when referring to the history of commits over time. This use is informal, then, and not to be encouraged, as it is just confusing.
It is perfectly clear that every commit (except one) has at least one parent, and that parents of parents are thus ancestors; and in the other direction, commits have children and descendants. That's accepted terminology, and describes the directionality of the graph unambiguously, so that's the way to talk when you want to describe how commits relate to one another within the graph geometry of a repo. Do not use "upstream" or "downstream" loosely in this situation.
[Additional note: I've been thinking about the relationship between the first Chacon sentence I cite above and the git-merge
man page, and it occurs to me that the former may be based on a misunderstanding of the latter. The man page does go on to describe a situation where the use of "upstream" is legitimate: fast-forwarding often happens when "you are tracking an upstream repository, you have committed no local changes, and now you want to update to a newer upstream revision." So perhaps Chacon used "upstream" because he saw it here in the man page. But in the man page there is a remote repository; there is no remote repository in Chacon's cited example of fast-forwarding, just a couple of locally created branches.]
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
Restore the mysql database from .frm files
Yes this is possible. It is not enough you just copy the .frm
files to the to the databse folder but you also need to copy the ib_logfiles
and ibdata
file into your data folder. I have just copy the .frm
files and copy those files and just restart the server and my database is restored.
After copying the above files execute the following command -
sudo chown -R mysql:mysql /var/lib/mysql
The above command will change the file owner under mysql and it's folder to MySql user. Which is important for mysql to read the .frm
and ibdata
files.
YAML Multi-Line Arrays
The following would work:
myarray: [
String1, String2, String3,
String4, String5, String5, String7
]
I tested it using the snakeyaml implementation, I am not sure about other implementations though.
How can I do a line break (line continuation) in Python?
It may not be the Pythonic way, but I generally use a list with the join function for writing a long string, like SQL queries:
query = " ".join([
'SELECT * FROM "TableName"',
'WHERE "SomeColumn1"=VALUE',
'ORDER BY "SomeColumn2"',
'LIMIT 5;'
])
JQuery Validate Dropdown list
As we know jQuery validate plugin invalidates Select field when it has blank value. Why don't we set its value to blank when required.
Yes, you can validate select field with some predefined value.
$("#everything").validate({
rules: {
select_field:{
required: {
depends: function(element){
if('none' == $('#select_field').val()){
//Set predefined value to blank.
$('#select_field').val('');
}
return true;
}
}
}
}
});
We can set blank value for select field but in some case we can't. For Ex: using a function that generates Dropdown field for you and you don't have control over it.
I hope it helps as it helps me.
cell format round and display 2 decimal places
I use format, Number, 2 decimal places & tick ' use 1000 separater ', then go to 'File', 'Options', 'Advanced', scroll down to 'When calculating this workbook' and tick 'set precision as displayed'. You get an error message about losing accuracy, that's good as it means it is rounding to 2 decimal places. So much better than bothering with adding a needless ROUND function.
How to start up spring-boot application via command line?
Run Spring Boot app using Maven
You can also use Maven plugin to run your Spring Boot app. Use the below example to run your Spring Boot app with Maven plugin:
mvn spring-boot:run
Run Spring Boot App with Gradle
And if you use Gradle you can run the Spring Boot app with the following command:
gradle bootRun
How to shut down the computer from C#
System.Diagnostics.Process.Start("shutdown", "/s /t 0")
Should work.
For restart, it's /r
This will restart the PC box directly and cleanly, with NO dialogs.
Createuser: could not connect to database postgres: FATAL: role "tom" does not exist
Your error is posted in the official documentation. You can read this article.
I have copied the reason for you (and hyperlinked the URLs) from that article:
This will happen if the administrator has not created a PostgreSQL user account for you. (PostgreSQL user accounts are distinct from operating system user accounts.) If you are the administrator, see Chapter 20 for help creating accounts. You will need to become the operating system user under which PostgreSQL was installed (usually postgres) to create the first user account. It could also be that you were assigned a PostgreSQL user name that is different from your operating system user name; in that case you need to use the -U switch or set the PGUSER environment variable to specify your PostgreSQL user name
For your purposes, you can do:
1) Create a PostgreSQL user account:
sudo -u postgres createuser tom -d -P
(the -P
option to set a password; the -d
option for allowing the creation of database for your username 'tom'. Note that 'tom' is your operating system username. That way, you can execute PostgreSQL commands without sudo
ing.)
2) Now you should be able to execute createdb
and other PostgreSQL commands.
How set the android:gravity to TextView from Java side in Android
We can set layout gravity on any view like below way-
myView = findViewById(R.id.myView);
myView.setGravity(Gravity.CENTER_VERTICAL|Gravity.RIGHT);
or
myView.setGravity(Gravity.BOTTOM);
This is equilent to below xml code
<...
android:gravity="center_vertical|right"
...
.../>
Check if string contains a value in array
You can concatenate the array values with implode and a separator of |
and then use preg_match to search for the value.
Here is the solution I came up with ...
$emails = array('@gmail', '@hotmail', '@outlook', '@live', '@msn', '@yahoo', '@ymail', '@aol');
$emails = implode('|', $emails);
if(!preg_match("/$emails/i", $email)){
// do something
}
Generate random string/characters in JavaScript
How about this below... this will produce the really random values:
function getRandomStrings(length) {
const value = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const randoms = [];
for(let i=0; i < length; i++) {
randoms.push(value[Math.floor(Math.random()*value.length)]);
}
return randoms.join('');
}
But if you looking for a shorter syntax one in ES6:
const getRandomStrings = length => Math.random().toString(36).substr(-length);
Adding image to JFrame
Here is a simple example of adding an image to a JFrame
:
frame.add(new JLabel(new ImageIcon("Path/To/Your/Image.png")));
How to export a table dataframe in PySpark to csv?
You need to repartition the Dataframe in a single partition and then define the format, path and other parameter to the file in Unix file system format and here you go,
df.repartition(1).write.format('com.databricks.spark.csv').save("/path/to/file/myfile.csv",header = 'true')
Read more about the repartition function
Read more about the save function
However, repartition is a costly function and toPandas() is worst. Try using .coalesce(1) instead of .repartition(1) in previous syntax for better performance.
Read more on repartition vs coalesce functions.
How to Get a Sublist in C#
Your collection class could have a method that returns a collection (a sublist) based on criteria passed in to define the filter. Build a new collection with the foreach loop and pass it out.
Or, have the method and loop modify the existing collection by setting a "filtered" or "active" flag (property). This one could work but could also cause poblems in multithreaded code. If other objects deped on the contents of the collection this is either good or bad depending of how you use the data.
How do I get a Date without time in Java?
Definitely not the most correct way, but if you just need a quick solution to get the date without the time and you do not wish to use a third party library this should do
Date db = db.substring(0, 10) + db.substring(23,28);
I only needed the date for visual purposes and couldn't Joda so I substringed.
HTTP Basic Authentication - what's the expected web browser experience?
If there are no credentials provided in the request headers, the following is the minimum response required for IE to prompt the user for credentials and resubmit the request.
Response.Clear();
Response.StatusCode = (Int32)HttpStatusCode.Unauthorized;
Response.AddHeader("WWW-Authenticate", "Basic");
Differences between SP initiated SSO and IDP initiated SSO
SP Initiated SSO
Bill the user: "Hey Jimmy, show me that report"
Jimmy the SP: "Hey, I'm not sure who you are yet. We have a process here so you go get yourself verified with Bob the IdP first. I trust him."
Bob the IdP: "I see Jimmy sent you here. Please give me your credentials."
Bill the user: "Hi I'm Bill. Here are my credentials."
Bob the IdP: "Hi Bill. Looks like you check out."
Bob the IdP: "Hey Jimmy. This guy Bill checks out and here's some additional information about him. You do whatever you want from here."
Jimmy the SP: "Ok cool. Looks like Bill is also in our list of known guests. I'll let Bill in."
IdP Initiated SSO
Bill the user: "Hey Bob. I want to go to Jimmy's place. Security is tight over there."
Bob the IdP: "Hey Jimmy. I trust Bill. He checks out and here's some additional information about him. You do whatever you want from here."
Jimmy the SP: "Ok cool. Looks like Bill is also in our list of known guests. I'll let Bill in."
I go into more detail here, but still keeping things simple: https://jorgecolonconsulting.com/saml-sso-in-simple-terms/.
can you host a private repository for your organization to use with npm?
This post talks about how to setup a private registry
- make sure couchdb is installed in your system
Replicating npmjs.org use the following command
curl -X POST http://127.0.0.1:5984/_replicate -d '{"source":"http://isaacs.iriscouch.com/registry/", "target":"registry", "continuous":true, "create_target":true}' -H "Content-Type: application/json"
Note there is "continuous":true
in the command, this utilises CouchDB’s _changes API and will pull any new changes when this API is notified.
If you ever want to stop these replications, you can easily add "cancel":true
. Then the script would be
curl -X POST http://127.0.0.1:5984/_replicate -d '{"source":"http://isaacs.iriscouch.com/registry/", "target":"registry", "continuous":true, "create_target":true, "cancel":true}' -H "Content-Type: application/json"
Then go to npmjs.org readme to install npm (make sure nodejs
and git
is installed). Blow is all the steps
git clone git://github.com/isaacs/npmjs.org.git
cd npmjs.org
sudo npm install -g couchapp
npm install couchapp
npm install semver
couchapp push registry/app.js http://localhost:5984/registry
couchapp push www/app.js http://localhost:5984/registry
How many bytes does one Unicode character take?
I know this question is old and already has an accepted answer, but I want to offer a few examples (hoping it'll be useful to someone).
As far as I know old ASCII characters took one byte per character.
Right. Actually, since ASCII is a 7-bit encoding, it supports 128 codes (95 of which are printable), so it only uses half a byte (if that makes any sense).
How many bytes does a Unicode character require?
Unicode just maps characters to codepoints. It doesn't define how to encode them. A text file does not contain Unicode characters, but bytes/octets that may represent Unicode characters.
I assume that one Unicode character can contain every possible
character from any language - am I correct?
No. But almost. So basically yes. But still no.
So how many bytes does it need per character?
Same as your 2nd question.
And what do UTF-7, UTF-6, UTF-16 etc mean? Are they some kind Unicode
versions?
No, those are encodings. They define how bytes/octets should represent Unicode characters.
A couple of examples. If some of those cannot be displayed in your browser (probably because the font doesn't support them), go to http://codepoints.net/U+1F6AA
(replace 1F6AA
with the codepoint in hex) to see an image.
- U+0061 LATIN SMALL LETTER A:
a
- Nº: 97
- UTF-8: 61
- UTF-16: 00 61
- U+00A9 COPYRIGHT SIGN:
©
- Nº: 169
- UTF-8: C2 A9
- UTF-16: 00 A9
- U+00AE REGISTERED SIGN:
®
- Nº: 174
- UTF-8: C2 AE
- UTF-16: 00 AE
- U+1337 ETHIOPIC SYLLABLE PHWA:
?
- Nº: 4919
- UTF-8: E1 8C B7
- UTF-16: 13 37
- U+2014 EM DASH:
—
- Nº: 8212
- UTF-8: E2 80 94
- UTF-16: 20 14
- U+2030 PER MILLE SIGN:
‰
- Nº: 8240
- UTF-8: E2 80 B0
- UTF-16: 20 30
- U+20AC EURO SIGN:
€
- Nº: 8364
- UTF-8: E2 82 AC
- UTF-16: 20 AC
- U+2122 TRADE MARK SIGN:
™
- Nº: 8482
- UTF-8: E2 84 A2
- UTF-16: 21 22
- U+2603 SNOWMAN:
?
- Nº: 9731
- UTF-8: E2 98 83
- UTF-16: 26 03
- U+260E BLACK TELEPHONE:
?
- Nº: 9742
- UTF-8: E2 98 8E
- UTF-16: 26 0E
- U+2614 UMBRELLA WITH RAIN DROPS:
?
- Nº: 9748
- UTF-8: E2 98 94
- UTF-16: 26 14
- U+263A WHITE SMILING FACE:
?
- Nº: 9786
- UTF-8: E2 98 BA
- UTF-16: 26 3A
- U+2691 BLACK FLAG:
?
- Nº: 9873
- UTF-8: E2 9A 91
- UTF-16: 26 91
- U+269B ATOM SYMBOL:
?
- Nº: 9883
- UTF-8: E2 9A 9B
- UTF-16: 26 9B
- U+2708 AIRPLANE:
?
- Nº: 9992
- UTF-8: E2 9C 88
- UTF-16: 27 08
- U+271E SHADOWED WHITE LATIN CROSS:
?
- Nº: 10014
- UTF-8: E2 9C 9E
- UTF-16: 27 1E
- U+3020 POSTAL MARK FACE:
?
- Nº: 12320
- UTF-8: E3 80 A0
- UTF-16: 30 20
- U+8089 CJK UNIFIED IDEOGRAPH-8089:
?
- Nº: 32905
- UTF-8: E8 82 89
- UTF-16: 80 89
- U+1F4A9 PILE OF POO:
- Nº: 128169
- UTF-8: F0 9F 92 A9
- UTF-16: D8 3D DC A9
- U+1F680 ROCKET:
- Nº: 128640
- UTF-8: F0 9F 9A 80
- UTF-16: D8 3D DE 80
Okay I'm getting carried away...
Fun facts:
How to abort a Task like aborting a Thread (Thread.Abort method)?
You can "abort" a task by running it on a thread you control and aborting that thread. This causes the task to complete in a faulted state with a ThreadAbortException
. You can control thread creation with a custom task scheduler, as described in this answer. Note that the caveat about aborting a thread applies.
(If you don't ensure the task is created on its own thread, aborting it would abort either a thread-pool thread or the thread initiating the task, neither of which you typically want to do.)
How to upload a file to directory in S3 bucket using boto
For upload folder example as following code and S3 folder picture
import boto
import boto.s3
import boto.s3.connection
import os.path
import sys
# Fill in info on data to upload
# destination bucket name
bucket_name = 'willie20181121'
# source directory
sourceDir = '/home/willie/Desktop/x/' #Linux Path
# destination directory name (on s3)
destDir = '/test1/' #S3 Path
#max size in bytes before uploading in parts. between 1 and 5 GB recommended
MAX_SIZE = 20 * 1000 * 1000
#size of parts when uploading in parts
PART_SIZE = 6 * 1000 * 1000
access_key = 'MPBVAQ*******IT****'
secret_key = '11t63yDV***********HgUcgMOSN*****'
conn = boto.connect_s3(
aws_access_key_id = access_key,
aws_secret_access_key = secret_key,
host = '******.org.tw',
is_secure=False, # uncomment if you are not using ssl
calling_format = boto.s3.connection.OrdinaryCallingFormat(),
)
bucket = conn.create_bucket(bucket_name,
location=boto.s3.connection.Location.DEFAULT)
uploadFileNames = []
for (sourceDir, dirname, filename) in os.walk(sourceDir):
uploadFileNames.extend(filename)
break
def percent_cb(complete, total):
sys.stdout.write('.')
sys.stdout.flush()
for filename in uploadFileNames:
sourcepath = os.path.join(sourceDir + filename)
destpath = os.path.join(destDir, filename)
print ('Uploading %s to Amazon S3 bucket %s' % \
(sourcepath, bucket_name))
filesize = os.path.getsize(sourcepath)
if filesize > MAX_SIZE:
print ("multipart upload")
mp = bucket.initiate_multipart_upload(destpath)
fp = open(sourcepath,'rb')
fp_num = 0
while (fp.tell() < filesize):
fp_num += 1
print ("uploading part %i" %fp_num)
mp.upload_part_from_file(fp, fp_num, cb=percent_cb, num_cb=10, size=PART_SIZE)
mp.complete_upload()
else:
print ("singlepart upload")
k = boto.s3.key.Key(bucket)
k.key = destpath
k.set_contents_from_filename(sourcepath,
cb=percent_cb, num_cb=10)
PS: For more reference URL
Select DataFrame rows between two dates
I prefer not to alter the df
.
An option is to retrieve the index
of the start
and end
dates:
import numpy as np
import pandas as pd
#Dummy DataFrame
df = pd.DataFrame(np.random.random((30, 3)))
df['date'] = pd.date_range('2017-1-1', periods=30, freq='D')
#Get the index of the start and end dates respectively
start = df[df['date']=='2017-01-07'].index[0]
end = df[df['date']=='2017-01-14'].index[0]
#Show the sliced df (from 2017-01-07 to 2017-01-14)
df.loc[start:end]
which results in:
0 1 2 date
6 0.5 0.8 0.8 2017-01-07
7 0.0 0.7 0.3 2017-01-08
8 0.8 0.9 0.0 2017-01-09
9 0.0 0.2 1.0 2017-01-10
10 0.6 0.1 0.9 2017-01-11
11 0.5 0.3 0.9 2017-01-12
12 0.5 0.4 0.3 2017-01-13
13 0.4 0.9 0.9 2017-01-14