Bat file to run a .exe at the command prompt
A bat file has no structure...it is how you would type it on the command line. So just open your favourite editor..copy the line of code you want to run..and save the file as whatever.bat or whatever.cmd
How to pass values across the pages in ASP.net without using Session
You can use query string to pass value from one page to another..
1.pass the value using querystring
Response.Redirect("Default3.aspx?value=" + txt.Text + "& number="+n);
2.Retrive the value in the page u want by using any of these methods..
Method1:
string v = Request.QueryString["value"];
string n=Request.QueryString["number"];
Method2:
NameValueCollection v = Request.QueryString;
if (v.HasKeys())
{
string k = v.GetKey(0);
string n = v.Get(0);
if (k == "value")
{
lbltext.Text = n.ToString();
}
if (k == "value1")
{
lbltext.Text = "error occured";
}
}
NOTE:Method 2 is the fastest method.
Black transparent overlay on image hover with only CSS?
.overlay
didn't have a height or width and no content, and you can't hover over display:none
.
I instead gave the div the same size and position as .image
and changes RGBA
value on hover.
http://jsfiddle.net/Zf5am/566/
.image { position: absolute; border: 1px solid black; width: 200px; height: 200px; z-index:1;}
.image img { max-width: 100%; max-height: 100%; }
.overlay { position: absolute; top: 0; left: 0; background:rgba(255,0,0,0); z-index: 200; width:200px; height:200px; }
.overlay:hover { background:rgba(255,0,0,.7); }
VLook-Up Match first 3 characters of one column with another column
=VLOOKUP(LEFT(A4,LEN(A4)-9),$D:$F,3,0)
I use this if my Lookup_Value
needs to be truncated because of the format the name is in the Table_Array. E.g. my Lookup_Value
is "Eastbay District", but the Table_Array
list I have only shows this as "Eastbay". "Eastbay District" minus 9 characters will result in "Eastbay".
I hope this helps!
Scroll RecyclerView to show selected item on top
just call this method simply:
((LinearLayoutManager)recyclerView.getLayoutManager()).scrollToPositionWithOffset(yourItemPosition,0);
instead of:
recyclerView.scrollToPosition(yourItemPosition);
pandas get rows which are NOT in other dataframe
The currently selected solution produces incorrect results. To correctly solve this problem, we can perform a left-join from df1
to df2
, making sure to first get just the unique rows for df2
.
First, we need to modify the original DataFrame to add the row with data [3, 10].
df1 = pd.DataFrame(data = {'col1' : [1, 2, 3, 4, 5, 3],
'col2' : [10, 11, 12, 13, 14, 10]})
df2 = pd.DataFrame(data = {'col1' : [1, 2, 3],
'col2' : [10, 11, 12]})
df1
col1 col2
0 1 10
1 2 11
2 3 12
3 4 13
4 5 14
5 3 10
df2
col1 col2
0 1 10
1 2 11
2 3 12
Perform a left-join, eliminating duplicates in df2
so that each row of df1
joins with exactly 1 row of df2
. Use the parameter indicator
to return an extra column indicating which table the row was from.
df_all = df1.merge(df2.drop_duplicates(), on=['col1','col2'],
how='left', indicator=True)
df_all
col1 col2 _merge
0 1 10 both
1 2 11 both
2 3 12 both
3 4 13 left_only
4 5 14 left_only
5 3 10 left_only
Create a boolean condition:
df_all['_merge'] == 'left_only'
0 False
1 False
2 False
3 True
4 True
5 True
Name: _merge, dtype: bool
Why other solutions are wrong
A few solutions make the same mistake - they only check that each value is independently in each column, not together in the same row. Adding the last row, which is unique but has the values from both columns from df2
exposes the mistake:
common = df1.merge(df2,on=['col1','col2'])
(~df1.col1.isin(common.col1))&(~df1.col2.isin(common.col2))
0 False
1 False
2 False
3 True
4 True
5 False
dtype: bool
This solution gets the same wrong result:
df1.isin(df2.to_dict('l')).all(1)
java calling a method from another class
You're very close. What you need to remember is when you're calling a method from another class you need to tell the compiler where to find that method.
So, instead of simply calling addWord("someWord")
, you will need to initialise an instance of the WordList class (e.g. WordList list = new WordList();
), and then call the method using that (i.e. list.addWord("someWord");
.
However, your code at the moment will still throw an error there, because that would be trying to call a non-static method from a static one. So, you could either make addWord()
static, or change the methods in the Words class so that they're not static.
My bad with the above paragraph - however you might want to reconsider ProcessInput()
being a static method - does it really need to be?
How to set RelativeLayout layout params in code not in xml?
Just a basic example:
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
Button button1;
button1.setLayoutParams(params);
params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.RIGHT_OF, button1.getId());
Button button2;
button2.setLayoutParams(params);
As you can see, this is what you have to do:
- Create a
RelativeLayout.LayoutParams
object.
- Use
addRule(int)
or addRule(int, int)
to set the rules. The first method is used to add rules that don't require values.
- Set the parameters to the view (in this case, to each button).
How to call a Parent Class's method from Child Class in Python?
I would recommend using CLASS.__bases__
something like this
class A:
def __init__(self):
print "I am Class %s"%self.__class__.__name__
for parentClass in self.__class__.__bases__:
print " I am inherited from:",parentClass.__name__
#parentClass.foo(self) <- call parents function with self as first param
class B(A):pass
class C(B):pass
a,b,c = A(),B(),C()
How to run a script file remotely using SSH
If you want to execute a local script remotely without saving that script remotely you can do it like this:
cat local_script.sh | ssh user@remotehost 'bash -'
It works like a charm for me.
I do that even from Windows to Linux given that you have MSYS installed on your Windows computer.
Android LinearLayout : Add border with shadow around a LinearLayout
okay, i know this is way too late. but i had the same requirement. i solved like this
1.First create a xml file (example: border_shadow.xml) in "drawable"
folder and copy the below code into it.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<item>
<shape>
<!-- set the shadow color here -->
<stroke
android:width="2dp"
android:color="#7000" />
<!-- setting the thickness of shadow (positive value will give shadow on that side) -->
<padding
android:bottom="2dp"
android:left="2dp"
android:right="-1dp"
android:top="-1dp" />
<corners android:radius="3dp" />
</shape>
</item>
<!-- Background -->
<item>
<shape>
<solid android:color="#fff" />
<corners android:radius="3dp" />
</shape>
</item>
2.now on the layout where you want the shadow(example: LinearLayout) add this in android:background
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="8dip"
android:background="@drawable/border_shadow"
android:orientation="vertical">
and that worked for me.
Returning value from called function in a shell script
I think returning 0 for succ/1 for fail (glenn jackman) and olibre's clear and explanatory answer says it all; just to mention a kind of "combo" approach for cases where results are not binary and you'd prefer to set a variable rather than "echoing out" a result (for instance if your function is ALSO suppose to echo something, this approach will not work). What then? (below is Bourne Shell)
# Syntax _w (wrapReturn)
# arg1 : method to wrap
# arg2 : variable to set
_w(){
eval $1
read $2 <<EOF
$?
EOF
eval $2=\$$2
}
as in (yep, the example is somewhat silly, it's just an.. example)
getDay(){
d=`date '+%d'`
[ $d -gt 255 ] && echo "Oh no a return value is 0-255!" && BAIL=0 # this will of course never happen, it's just to clarify the nature of returns
return $d
}
dayzToSalary(){
daysLeft=0
if [ $1 -lt 26 ]; then
daysLeft=`expr 25 - $1`
else
lastDayInMonth=`date -d "`date +%Y%m01` +1 month -1 day" +%d`
rest=`expr $lastDayInMonth - 25`
daysLeft=`expr 25 + $rest`
fi
echo "Mate, it's another $daysLeft days.."
}
# main
_w getDay DAY # call getDay, save the result in the DAY variable
dayzToSalary $DAY
minimize app to system tray
try this
private void Form1_Load(object sender, EventArgs e)
{
notifyIcon1.BalloonTipText = "Application Minimized.";
notifyIcon1.BalloonTipTitle = "test";
}
private void Form1_Resize(object sender, EventArgs e)
{
if (WindowState == FormWindowState.Minimized)
{
ShowInTaskbar = false;
notifyIcon1.Visible = true;
notifyIcon1.ShowBalloonTip(1000);
}
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
ShowInTaskbar = true;
notifyIcon1.Visible = false;
WindowState = FormWindowState.Normal;
}
How to decompile to java files intellij idea
The decompiler of IntelliJ IDEA was not built with this kind of usage in mind. It is only meant to help programmers peek at the bytecode of the java classes that they are developing. For decompiling lots of class files of which you do not have source code, you will need some other java decompiler, which is specialized for this job, and most likely runs standalone. If you google you should find a bunch.
How to add a line break in an Android TextView?
try this:
TextView calloutContent = new TextView(getApplicationContext());
calloutContent.setTextColor(Color.BLACK);
calloutContent.setSingleLine(false);
calloutContent.setLines(2);
calloutContent.setText(" line 1" + System.getProperty ("line.separator")+" line2" );
In C# check that filename is *possibly* valid (not that it exists)
Just do;
System.IO.FileInfo fi = null;
try {
fi = new System.IO.FileInfo(fileName);
}
catch (ArgumentException) { }
catch (System.IO.PathTooLongException) { }
catch (NotSupportedException) { }
if (ReferenceEquals(fi, null)) {
// file name is not valid
} else {
// file name is valid... May check for existence by calling fi.Exists.
}
For creating a FileInfo
instance the file does not need to exist.
What is the effect of encoding an image in base64?
Encoding an image to base64 will make it about 30% bigger.
See the details in the wikipedia article about the Data URI scheme, where it states:
Base64-encoded data URIs are 1/3 larger in size than their binary equivalent. (However, this overhead is reduced to 2-3% if the HTTP server compresses the response using gzip)
Typescript: React event types
To combine both Nitzan's and Edwin's answers, I found that something like this works for me:
update = (e: React.FormEvent<EventTarget>): void => {
let target = e.target as HTMLInputElement;
this.props.login[target.name] = target.value;
}
Converting string from snake_case to CamelCase in Ruby
Extend String to Add Camelize
In pure Ruby you could extend the string class using code lifted from Rails .camelize
class String
def camelize(uppercase_first_letter = true)
string = self
if uppercase_first_letter
string = string.sub(/^[a-z\d]*/) { |match| match.capitalize }
else
string = string.sub(/^(?:(?=\b|[A-Z_])|\w)/) { |match| match.downcase }
end
string.gsub(/(?:_|(\/))([a-z\d]*)/) { "#{$1}#{$2.capitalize}" }.gsub("/", "::")
end
end
Exception thrown inside catch block - will it be caught again?
As said above...
I would add that if you have trouble seeing what is going on, if you can't reproduce the issue in the debugger, you can add a trace before re-throwing the new exception (with the good old System.out.println at worse, with a good log system like log4j otherwise).
JavaScript string and number conversion
r = ("1"+"2"+"3") // step1 | build string ==> "123"
r = +r // step2 | to number ==> 123
r = r+100 // step3 | +100 ==> 223
r = ""+r // step4 | to string ==> "223"
//in one line
r = ""+(+("1"+"2"+"3")+100);
How to pass parameters to ThreadStart method in Thread?
You can encapsulate the thread function(download) and the needed parameter(s)(filename) in a class and use the ThreadStart delegate to execute the thread function.
public class Download
{
string _filename;
Download(string filename)
{
_filename = filename;
}
public void download(string filename)
{
//download code
}
}
Download = new Download(filename);
Thread thread = new Thread(new ThreadStart(Download.download);
Linker Error C++ "undefined reference "
This error tells you everything:
undefined reference toHash::insert(int, char)
You're not linking with the implementations of functions defined in Hash.h
. Don't you have a Hash.cpp
to also compile and link?
Can promises have multiple arguments to onFulfilled?
Since functions in Javascript can be called with any number of arguments, and the document doesn't place any restriction on the onFulfilled()
method's arguments besides the below clause, I think that you can pass multiple arguments to the onFulfilled()
method as long as the promise's value is the first argument.
2.2.2.1 it must be called after promise is fulfilled, with promise’s value as its first argument.
Python list of dictionaries search
names = [{'name':'Tom', 'age': 10}, {'name': 'Mark', 'age': 5}, {'name': 'Pam', 'age': 7}]
resultlist = [d for d in names if d.get('name', '') == 'Pam']
first_result = resultlist[0]
This is one way...
build maven project with propriatery libraries included
You can get it from your local driver as below:
<dependency>
<groupId>sample</groupId>
<artifactId>com.sample</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/yourJar.jar</systemPath>
</dependency>
How to configure slf4j-simple
I noticed that Eemuli said that you can't change the log level after they are created - and while that might be the design, it isn't entirely true.
I ran into a situation where I was using a library that logged to slf4j - and I was using the library while writing a maven mojo plugin.
Maven uses a (hacked) version of the slf4j SimpleLogger, and I was unable to get my plugin code to reroute its logging to something like log4j, which I could control.
And I can't change the maven logging config.
So, to quiet down some noisy info messages, I found I could use reflection like this, to futz with the SimpleLogger at runtime.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.spi.LocationAwareLogger;
try
{
Logger l = LoggerFactory.getLogger("full.classname.of.noisy.logger"); //This is actually a MavenSimpleLogger, but due to various classloader issues, can't work with the directly.
Field f = l.getClass().getSuperclass().getDeclaredField("currentLogLevel");
f.setAccessible(true);
f.set(l, LocationAwareLogger.WARN_INT);
}
catch (Exception e)
{
getLog().warn("Failed to reset the log level of " + loggerName + ", it will continue being noisy.", e);
}
Of course, note, this isn't a very stable / reliable solution... as it will break the next time the maven folks change their logger.
How to delete a workspace in Perforce (using p4v)?
From the "View" menu, select "Workspaces". You'll see all of the workspaces you've created. Select the workspaces you want to delete and click "Edit" -> "Delete Workspace", or right-click and select "Delete Workspace". If the workspace is "locked" to prevent changes, you'll get an error message.
To unlock the workspace, click "Edit" (or right-click and click "Edit Workspace") to pull up the workspace editor, uncheck the "locked" checkbox, and save your changes. You can delete the workspace once it's unlocked.
In my experience, the workspace will continue to be shown in the drop-down list until you click on it, at which point p4v will figure out you've deleted it and remove it from the list.
Broken references in Virtualenvs
This occurred when I updated to Mac OS X Mavericks from Snow Leopard. I had to re-install brew beforehand too. Hopefully you ran the freeze command for your project with pip.
To resolve, you have to update the paths that the virtual environment points to.
- Install a version of python with brew:
brew install python
- Re-install virtualenvwrapper.
pip install --upgrade virtualenvwrapper
- Removed the old virtual environment:
rmvirtualenv old_project
- Create a new virtual environment:
mkvirtualenv new_project
- Work on new virtual environment
workon new_project
- Use pip to install the requirements for the new project.
pip install -r requirements.txt
This should leave the project as it was before.
JAVA_HOME is set to an invalid directory:
First try removing the '\bin' from the path and set the home directory JAVA_HOME as below:
JAVA_HOME : C:\Program Files\Java\jdk1.8.0_131
Second Update System PATH:
- In “Environment Variables” window under “System variables” select Path
- Click on “Edit…”
- In “Edit environment variable” window click “New”
- Type in %JAVA_HOME%\bin
Third restart your docker.
Refer to the link for setting the java path in windows.
Get a list of all threads currently running in Java
Have you taken a look at jconsole?
This will list all threads running for a particular Java process.
You can start jconsole from the JDK bin folder.
You can also get a full stack trace for all threads by hitting Ctrl+Break
in Windows or by sending kill pid --QUIT
in Linux.
Quick Sort Vs Merge Sort
Quick sort is typically faster than merge sort when the data is stored in memory. However, when the data set is huge and is stored on external devices such as a hard drive, merge sort is the clear winner in terms of speed. It minimizes the expensive reads of the external drive and also lends itself well to parallel computing.
If else on WHERE clause
try this ,hope it helps
select user_display_image as user_image,
user_display_name as user_name,
invitee_phone,
(
CASE
WHEN invitee_status=1 THEN "attending"
WHEN invitee_status=2 THEN "unsure"
WHEN invitee_status=3 THEN "declined"
WHEN invitee_status=0 THEN "notreviwed" END
) AS invitee_status
FROM your_tbl
CSS3 opacity gradient?
Except using css mask answered by @vals, you can also use transparency gradient background and set background-clip
to text
.
Create proper gradient:
background: linear-gradient(to bottom, rgba(0, 0, 0, 1) 0%, rgba(0, 0, 0, 0) 100%);
Then clip the backgroud with text:
background-clip: text;
color: transparent;
Demo
https://jsfiddle.net/simonmysun/2h61Ljbn/4/
Tested under Chrome 75 under Windows 10.
Supported platforms:
Slick Carousel Uncaught TypeError: $(...).slick is not a function
For me, the problem resolves after I changed:
<script type='text/javascript' src='../../path-to-slick/slick.min.js'></script>
to
<script src='../../path-to-slick/slick.min.js'></script>
My work is based on Jquery 2.2.4, and I'm running my development on the latest Xampp and Chrome.
Logging levels - Logback - rule-of-thumb to assign log levels
This may also tangentially help, to understand if a logging request (from the code) at a certain level will result in it actually being logged given the effective logging level that a deployment is configured with. Decide what effective level you want to configure you deployment with from the other Answers here, and then refer to this to see if a particular logging request from your code will actually be logged then...
For examples:
- "Will a logging code line that logs at WARN actually get logged on my deployment configured with ERROR?" The table says, NO.
- "Will a logging code line that logs at WARN actually get logged on my deployment configured with DEBUG?" The table says, YES.
from logback documentation:
In a more graphic way, here is how the selection rule works. In the following table, the vertical header shows the level of the logging request, designated by p, while the horizontal header shows effective level of the logger, designated by q. The intersection of the rows (level request) and columns (effective level) is the boolean resulting from the basic selection rule.
So a code line that requests logging will only actually get logged if the effective logging level of its deployment is less than or equal to that code line's requested level of severity.
How do you split and unsplit a window/view in Eclipse IDE?
This is possible with the menu items Window>Editor>Toggle Split Editor.
Current shortcut for splitting is:
Azerty keyboard:
- Ctrl + _ for split horizontally, and
- Ctrl + { for split vertically.
Qwerty US keyboard:
- Ctrl + Shift + - (accessing _) for split horizontally, and
- Ctrl + Shift + [ (accessing {) for split vertically.
MacOS - Qwerty US keyboard:
- ⌘ + Shift + - (accessing _) for split horizontally, and
- ⌘ + Shift + [ (accessing {) for split vertically.
On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:
- Alt + ASCII code + Ctrl then release Alt
Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.
Example of vertical split:
PS:
- The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
- The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
- The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.
android get real path by Uri.getPath()
Hii here is my complete code for taking image from camera or galeery
//My variable declaration
protected static final int CAMERA_REQUEST = 0;
protected static final int GALLERY_REQUEST = 1;
Bitmap bitmap;
Uri uri;
Intent picIntent = null;
//Onclick
if (v.getId()==R.id.image_id){
startDilog();
}
//method body
private void startDilog() {
AlertDialog.Builder myAlertDilog = new AlertDialog.Builder(yourActivity.this);
myAlertDilog.setTitle("Upload picture option..");
myAlertDilog.setMessage("Where to upload picture????");
myAlertDilog.setPositiveButton("Gallery", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
picIntent = new Intent(Intent.ACTION_GET_CONTENT,null);
picIntent.setType("image/*");
picIntent.putExtra("return_data",true);
startActivityForResult(picIntent,GALLERY_REQUEST);
}
});
myAlertDilog.setNegativeButton("Camera", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
picIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(picIntent,CAMERA_REQUEST);
}
});
myAlertDilog.show();
}
//And rest of things
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==GALLERY_REQUEST){
if (resultCode==RESULT_OK){
if (data!=null) {
uri = data.getData();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
try {
BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
options.inSampleSize = calculateInSampleSize(options, 100, 100);
options.inJustDecodeBounds = false;
Bitmap image = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
imageofpic.setImageBitmap(image);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}else {
Toast.makeText(getApplicationContext(), "Cancelled",
Toast.LENGTH_SHORT).show();
}
}else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Cancelled",
Toast.LENGTH_SHORT).show();
}
}else if (requestCode == CAMERA_REQUEST) {
if (resultCode == RESULT_OK) {
if (data.hasExtra("data")) {
bitmap = (Bitmap) data.getExtras().get("data");
uri = getImageUri(YourActivity.this,bitmap);
File finalFile = new File(getRealPathFromUri(uri));
imageofpic.setImageBitmap(bitmap);
} else if (data.getExtras() == null) {
Toast.makeText(getApplicationContext(),
"No extras to retrieve!", Toast.LENGTH_SHORT)
.show();
BitmapDrawable thumbnail = new BitmapDrawable(
getResources(), data.getData().getPath());
pet_pic.setImageDrawable(thumbnail);
}
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Cancelled",
Toast.LENGTH_SHORT).show();
}
}
}
private String getRealPathFromUri(Uri tempUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = this.getContentResolver().query(tempUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
private Uri getImageUri(YourActivity youractivity, Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
String path = MediaStore.Images.Media.insertImage(youractivity.getContentResolver(), bitmap, "Title", null);
return Uri.parse(path);
}
How to completely hide the navigation bar in iPhone / HTML5
Try the following:
Add this meta
tag in the head
of your HTML file:
<meta name="apple-mobile-web-app-capable" content="yes" />
Open your site with Safari on iPhone, and use the bookmark feature to add your site to the home screen.
Go back to home screen and open the bookmarked site. The URL and status bar will be gone.
As long as you only need to work with the iPhone, you should be fine with this solution.
In addition, your sample on the warnerbros.com site uses the Sencha touch framework. You can Google it for more information or check out their demos.
How to append new data onto a new line
I presume that all you are wanting is simple string concatenation:
def storescores():
hs = open("hst.txt","a")
hs.write(name + " ")
hs.close()
Alternatively, change the " " to "\n" for a newline.
Editor does not contain a main type in Eclipse
Ideally, the source code file should go within the src/default package even if you haven't provided any package name. For some reason, the source file might be outside src folder. Create within the scr folder it will work!
git pull while not in a git directory
Using combination pushd
, git pull
and popd
, we can achieve this functionality:
pushd <path-to-git-repo> && git pull && popd
For example:
pushd "E:\Fake Directory\gitrepo" && git pull && popd
Java: convert seconds to minutes, hours and days
The simpliest way
Scanner in = new Scanner(System.in);
System.out.println("Enter seconds");
int s = in.nextInt();
int sec = s % 60;
int min = (s / 60)%60;
int hours = (s/60)/60;
System.out.println(hours + ":" + min + ":" + sec);
Browser detection in JavaScript?
Below code snippet will show how how you can show UI elemnts depends on IE version and browser
$(document).ready(function () {
var msiVersion = GetMSIieversion();
if ((msiVersion <= 8) && (msiVersion != false)) {
//Show UI elements specific to IE version 8 or low
} else {
//Show UI elements specific to IE version greater than 8 and for other browser other than IE,,ie..Chrome,Mozila..etc
}
}
);
Below code will give how we can get IE version
function GetMSIieversion() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf('MSIE ');
if (msie > 0) {
// IE 10 or older => return version number
return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
}
var trident = ua.indexOf('Trident/');
if (trident > 0) {
// IE 11 => return version number
var rv = ua.indexOf('rv:');
return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
}
var edge = ua.indexOf('Edge/');
if (edge > 0) {
// Edge (IE 12+) => return version number
return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
}
// other browser like Chrome,Mozila..etc
return false;
}
Storing data into list with class
You're not adding a new instance of the class to the list. Try this:
lstemail.Add(new EmailData { FirstName="John", LastName="Smith", Location="Los Angeles" });`
List
is a generic class. When you specify a List<EmailData>
, the Add
method is expecting an object that's of type EmailData
. The example above, expressed in more verbose syntax, would be:
EmailData data = new EmailData();
data.FirstName="John";
data.LastName="Smith;
data.Location = "Los Angeles";
lstemail.Add(data);
How to remove extension from string (only real extension!)
The following code works well for me, and it's pretty short. It just breaks the file up into an array delimited by dots, deletes the last element (which is hypothetically the extension), and reforms the array with the dots again.
$filebroken = explode( '.', $filename);
$extension = array_pop($filebroken);
$fileTypeless = implode('.', $filebroken);
What is the difference between a JavaBean and a POJO?
A JavaBean follows certain conventions. Getter/setter naming, having a public default constructor, being serialisable etc. See JavaBeans Conventions for more details.
A POJO (plain-old-Java-object) isn't rigorously defined. It's a Java object that doesn't have a requirement to implement a particular interface or derive from a particular base class, or make use of particular annotations in order to be compatible with a given framework, and can be any arbitrary (often relatively simple) Java object.
How to execute an SSIS package from .NET?
You can use this Function if you have some variable in the SSIS.
Package pkg;
Microsoft.SqlServer.Dts.Runtime.Application app;
DTSExecResult pkgResults;
Variables vars;
app = new Microsoft.SqlServer.Dts.Runtime.Application();
pkg = app.LoadPackage(" Location of your SSIS package", null);
vars = pkg.Variables;
// your variables
vars["somevariable1"].Value = "yourvariable1";
vars["somevariable2"].Value = "yourvariable2";
pkgResults = pkg.Execute(null, vars, null, null, null);
if (pkgResults == DTSExecResult.Success)
{
Console.WriteLine("Package ran successfully");
}
else
{
Console.WriteLine("Package failed");
}
How can I disable mod_security in .htaccess file?
For anyone that simply are looking to bypass the ERROR page to display the content on shared hosting. You might wanna try and use redirect in .htaccess file. If it is say 406 error, on UnoEuro it didn't seem to work simply deactivating the security. So I used this instead:
ErrorDocument 406 /
Then you can always change the error status using PHP. But be aware that in my case doing so means I am opening a door to SQL injections as I am bypassing WAF. So you will need to make sure that you either have your own security measures or enable the security again asap.
Get the position of a spinner in Android
final int[] positions=new int[2];
Spinner sp=findViewByID(R.id.spinner);
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText( arg2....);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Showing empty view when ListView is empty
It should be like this:
<TextView android:id="@android:id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="No Results" />
Note the id attribute.
Xamarin.Forms ListView: Set the highlight color of a tapped item
The previous answers either suggest custom renderers or require you to keep track of the selected item either in your data objects or otherwise. This isn't really required, there is a way to link to the functioning of the ListView
in a platform agnostic way. This can then be used to change the selected item in any way required. Colors can be modified, different parts of the cell shown or hidden depending on the selected state.
Let's add an IsSelected
property to our ViewCell
. There is no need to add it to the data object; the listview selects the cell, not the bound data.
public partial class SelectableCell : ViewCell {
public static readonly BindableProperty IsSelectedProperty = BindableProperty.Create(nameof(IsSelected), typeof(bool), typeof(SelectableCell), false, propertyChanged: OnIsSelectedPropertyChanged);
public bool IsSelected {
get => (bool)GetValue(IsSelectedProperty);
set => SetValue(IsSelectedProperty, value);
}
// You can omit this if you only want to use IsSelected via binding in XAML
private static void OnIsSelectedPropertyChanged(BindableObject bindable, object oldValue, object newValue) {
var cell = ((SelectableCell)bindable);
// change color, visibility, whatever depending on (bool)newValue
}
// ...
}
To create the missing link between the cells and the selection in the list view, we need a converter (the original idea came from the Xamarin Forum):
public class IsSelectedConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) =>
value != null && value == ((ViewCell)parameter).View.BindingContext;
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) =>
throw new NotImplementedException();
}
We connect the two using this converter:
<ListView x:Name="ListViewName">
<ListView.ItemTemplate>
<DataTemplate>
<local:SelectableCell x:Name="ListViewCell"
IsSelected="{Binding SelectedItem, Source={x:Reference ListViewName}, Converter={StaticResource IsSelectedConverter}, ConverterParameter={x:Reference ListViewCell}}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
This relatively complex binding serves to check which actual item is currently selected. It compares the SelectedItem
property of the list view to the BindingContext
of the view in the cell. That binding context is the data object we actually bind to. In other words, it checks whether the data object pointed to by SelectedItem
is actually the data object in the cell. If they are the same, we have the selected cell. We bind this into to the IsSelected
property which can then be used in XAML or code behind to see if the view cell is in the selected state.
There is just one caveat: if you want to set a default selected item when your page displays, you need to be a bit clever. Unfortunately, Xamarin Forms has no page Displayed event, we only have Appearing and this is too early for setting the default: the binding won't be executed then. So, use a little delay:
protected override async void OnAppearing() {
base.OnAppearing();
Device.BeginInvokeOnMainThread(async () => {
await Task.Delay(100);
ListViewName.SelectedItem = ...;
});
}
Best C# API to create PDF
My work uses Winnovative's PDF generator (We've used it mainly to convert HTML to PDF, but you can generate it other ways as well)
Log4j2 configuration - No log4j2 configuration file found
Eclipse will never see a file until you force a refresh of the IDE. Its a feature! So you can put the file all over the project and Eclipse will ignore it completely and throw these errors. Hit refresh in Eclipse project view and then it works.
Preloading images with JavaScript
You can move this code to index.html for preload images from any url
<link rel="preload" href="https://via.placeholder.com/160" as="image">
How to read request body in an asp.net core webapi controller?
To those who simply want to get the content (request body) from the request:
Use the [FromBody]
attribute in your controller method parameter.
[Route("api/mytest")]
[ApiController]
public class MyTestController : Controller
{
[HttpPost]
[Route("content")]
public async Task<string> ReceiveContent([FromBody] string content)
{
// Do work with content
}
}
As doc says: this attribute specifies that a parameter or property should be bound using the request body.
SQL Server Linked Server Example Query
select name from drsql01.test.dbo.employee
- drslq01 is servernmae --linked serer
- test is database name
- dbo is schema -default schema
- employee is table name
I hope it helps to understand, how to execute query for linked server
How can I convert a DOM element to a jQuery element?
What about constructing the element using jQuery? e.g.
$("<div></div>")
creates a new div element, ready to be added to the page. Can be shortened further to
$("<div>")
then you can chain on commands that you need, set up event handlers and append it to the DOM. For example
$('<div id="myid">Div Content</div>')
.bind('click', function(e) { /* event handler here */ })
.appendTo('#myOtherDiv');
filters on ng-model in an input
Use a directive which adds to both the $formatters and $parsers collections to ensure that the transformation is performed in both directions.
See this other answer for more details including a link to jsfiddle.
Anaconda export Environment file
The easiest way to save the packages from an environment to be installed in another computer is:
$ conda list -e > req.txt
then you can install the environment using
$ conda create -n <environment-name> --file req.txt
if you use pip
, please use the following commands: reference https://pip.pypa.io/en/stable/reference/pip_freeze/
$ env1/bin/pip freeze > requirements.txt
$ env2/bin/pip install -r requirements.txt
jQuery object equality
If you still don't know, you can get back the original object by:
alert($("#deviceTypeRoot")[0] == $("#deviceTypeRoot")[0]); //True
alert($("#deviceTypeRoot")[0] === $("#deviceTypeRoot")[0]);//True
because $("#deviceTypeRoot")
also returns an array of objects which the selector has selected.
How to show form input fields based on select value?
Demo on JSFiddle
$(document).ready(function () {
toggleFields(); // call this first so we start out with the correct visibility depending on the selected form values
// this will call our toggleFields function every time the selection value of our other field changes
$("#dbType").change(function () {
toggleFields();
});
});
// this toggles the visibility of other server
function toggleFields() {
if ($("#dbType").val() === "other")
$("#otherServer").show();
else
$("#otherServer").hide();
}
HTML:
<p>Choose type</p>
<p>Server:
<select id="dbType" name="dbType">
<option>Choose Database Type</option>
<option value="oracle">Oracle</option>
<option value="mssql">MS SQL</option>
<option value="mysql">MySQL</option>
<option value="other">Other</option>
</select>
</p>
<div id="otherServer">
<p>Server:
<input type="text" name="server_name" />
</p>
<p>Port:
<input type="text" name="port_no" />
</p>
</div>
<p align="center">
<input type="submit" value="Submit!" />
</p>
CSS scale down image to fit in containing div, without specifing original size
In a webpage where I wanted a in image to scale with browser size change and remain at the top, next to a fixed div, all I had to do was use a single CSS line: overflow:hidden;
and it did the trick. The image scales perfectly.
What is especially nice is that this is pure css and will work even if Javascript is turned off.
CSS:
#ImageContainerDiv {
overflow: hidden;
}
HTML:
<div id="ImageContainerDiv">
<a href="URL goes here" target="_blank">
<img src="MapName.png" alt="Click to load map" />
</a>
</div>
Need to make a clickable <div> button
There are two solutions posted on that page. The one with lower votes I would recommend if possible.
If you are using HTML5 then it is perfectly valid to put a div
inside of a
. As long as the div doesn't also contain some other specific elements like other link tags.
<a href="Music.html">
<div id="music" class="nav">
Music I Like
</div>
</a>
The solution you are confused about actually makes the link as big as its container div. To make it work in your example you just need to add position: relative
to your div. You also have a small syntax error which is that you have given the span a class instead of an id. You also need to put your span inside the link because that is what the user is clicking on. I don't think you need the z-index
at all from that example.
div { position: relative; }
.hyperspan {
position:absolute;
width:100%;
height:100%;
left:0;
top:0;
}
<div id="music" class="nav">Music I Like
<a href="http://www.google.com">
<span class="hyperspan"></span>
</a>
</div>
http://jsfiddle.net/rBKXM/9
When you give absolute
positioning to an element it bases its location and size after the first parent it finds that is relatively positioned. If none, then it uses the document. By adding relative
to the parent div you tell the span to only be as big as that.
App.settings - the Angular way?
If you are using angular-cli, there is yet another option:
Angular CLI provides environment files in src/environments
(default ones are environment.ts
(dev) and environment.prod.ts
(production)).
Note that you need to provide the config parameters in all environment.*
files, e.g.,
environment.ts:
export const environment = {
production: false,
apiEndpoint: 'http://localhost:8000/api/v1'
};
environment.prod.ts:
export const environment = {
production: true,
apiEndpoint: '__your_production_server__'
};
and use them in your service (the correct environment file is chosen automatically):
api.service.ts
// ... other imports
import { environment } from '../../environments/environment';
@Injectable()
export class ApiService {
public apiRequest(): Observable<MyObject[]> {
const path = environment.apiEndpoint + `/objects`;
// ...
}
// ...
}
Read more on application environments on Github (Angular CLI version 6) or in the official Angular guide (version 7).
Session variables in ASP.NET MVC
Although I don't know about asp.net mvc, but this is what we should do in a normal .net website. It should work for asp.net mvc also.
YourSessionClass obj=Session["key"] as YourSessionClass;
if(obj==null){
obj=new YourSessionClass();
Session["key"]=obj;
}
You would put this inside a method for easy access.
HTH
Recursion in Python? RuntimeError: maximum recursion depth exceeded while calling a Python object
The error is a stack overflow. That should ring a bell on this site, right? It occurs because a call to poruszanie
results in another call to poruszanie
, incrementing the recursion depth by 1. The second call results in another call to the same function. That happens over and over again, each time incrementing the recursion depth.
Now, the usable resources of a program are limited. Each function call takes a certain amount of space on top of what is called the stack. If the maximum stack height is reached, you get a stack overflow error.
CSS Change List Item Background Color with Class
This is an issue of selector specificity. (The selector .selected
is less specific than ul.nav li
.)
To fix, use as much specificity in the overriding rule as in the original:
ul.nav li {
background-color:blue;
}
ul.nav li.selected {
background-color:red;
}
You might also consider nixing the ul
, unless there will be other .nav
s. So:
.nav li {
background-color:blue;
}
.nav li.selected {
background-color:red;
}
That's a bit cleaner, less typing, and fewer bits.
How to create a label inside an <input> element?
Here is a simple example, all it does is overlay an image (with whatever wording you want). I saw this technique somewhere. I am using the prototype library so you would need to modify if using something else. With the image loading after window.load it fails gracefully if javascript is disabled.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1;" />
<meta http-equiv="Expires" content="Fri, Jan 1 1981 08:00:00 GMT" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Cache-Control" content="no-cache" />
<style type="text/css" >
input.searcher
{
background-image: url(/images/search_back.png);
background-repeat: no-repeat;
background-attachment: scroll;
background-x-position: left;
background-y-position: center;
}
</style>
<script type="text/javascript" src="/logist/include/scripts/js/prototype.js" ></script>
</head>
<body>
<input type="text" id="q" name="q" value="" />
<script type="text/javascript" language="JavaScript" >
// <![CDATA[
function f(e){
$('q').removeClassName('searcher');
}
function b(e){
if ( $F('q') == '' )
{
$('q').addClassName('searcher');
}
}
Event.observe( 'q', 'focus', f);
Event.observe( 'q', 'blur', b);
Event.observe( window, 'load', b);
// ]]>
</script>
</body>
</html>
View RDD contents in Python Spark?
If you want to see the contents of RDD then yes collect is one option, but it fetches all the data to driver so there can be a problem
<rdd.name>.take(<num of elements you want to fetch>)
Better if you want to see just a sample
Running foreach and trying to print, I dont recommend this because if you are running this on cluster then the print logs would be local to the executor and it would print for the data accessible to that executor. print statement is not changing the state hence it is not logically wrong. To get all the logs you will have to do something like
**Pseudocode**
collect
foreach print
But this may result in job failure as collecting all the data on driver may crash it. I would suggest using take command or if u want to analyze it then use sample collect on driver or write to file and then analyze it.
How to do a regular expression replace in MySQL?
My brute force method to get this to work was just:
- Dump the table -
mysqldump -u user -p database table > dump.sql
- Find and replace a couple patterns -
find /path/to/dump.sql -type f -exec sed -i 's/old_string/new_string/g' {} \;
, There are obviously other perl regeular expressions you could perform on the file as well.
- Import the table -
mysqlimport -u user -p database table < dump.sql
If you want to make sure the string isn't elsewhere in your dataset, run a few regular expressions to make sure they all occur in a similar environment. It's also not that tough to create a backup before you run a replace, in case you accidentally destroy something that loses depth of information.
How can I get the current screen orientation?
if you want to override that onConfigurationChanged method and still want it to do the basic stuff then consider using super.onConfigyrationChanged() as the first statement in the overriden method.
Double precision - decimal places
It is because it's being converted from a binary representation. Just because it has printed all those decimal digits doesn't mean it can represent all decimal values to that precision. Take, for example, this in Python:
>>> 0.14285714285714285
0.14285714285714285
>>> 0.14285714285714286
0.14285714285714285
Notice how I changed the last digit, but it printed out the same number anyway.
Objective-C declared @property attributes (nonatomic, copy, strong, weak)
Nonatomic
Nonatomic
will not generate threadsafe routines thru @synthesize
accessors. atomic
will generate threadsafe accessors so atomic
variables are threadsafe (can be accessed from multiple threads without botching of data)
Copy
copy
is required when the object is mutable. Use this if you need the value of the object as it is at this moment, and you don't want that value to reflect any changes made by other owners of the object. You will need to release the object when you are finished with it because you are retaining the copy.
Assign
Assign
is somewhat the opposite to copy
. When calling the getter of an assign
property, it returns a reference to the actual data. Typically you use this attribute when you have a property of primitive type (float, int, BOOL...)
Retain
retain
is required when the attribute is a pointer to a reference counted object that was allocated on the heap. Allocation should look something like:
NSObject* obj = [[NSObject alloc] init]; // ref counted var
The setter generated by @synthesize
will add a reference count to the object when it is copied so the underlying object is not autodestroyed if the original copy goes out of scope.
You will need to release the object when you are finished with it. @property
s using retain
will increase the reference count and occupy memory in the autorelease pool.
Strong
strong
is a replacement for the retain attribute, as part of Objective-C Automated Reference Counting (ARC). In non-ARC code it's just a synonym for retain.
This is a good website to learn about strong
and weak
for iOS 5.
http://www.raywenderlich.com/5677/beginning-arc-in-ios-5-part-1
Weak
weak
is similar to strong
except that it won't increase the reference count by 1. It does not become an owner of that object but just holds a reference to it. If the object's reference count drops to 0, even though you may still be pointing to it here, it will be deallocated from memory.
The above link contain both Good information regarding Weak and Strong.
Sqlite: CURRENT_TIMESTAMP is in GMT, not the timezone of the machine
I found on the sqlite documentation (https://www.sqlite.org/lang_datefunc.html) this text:
Compute the date and time given a unix
timestamp 1092941466, and compensate
for your local timezone.
SELECT datetime(1092941466, 'unixepoch', 'localtime');
That didn't look like it fit my needs, so I tried changing the "datetime" function around a bit, and wound up with this:
select datetime(timestamp, 'localtime')
That seems to work - is that the correct way to convert for your timezone, or is there a better way to do this?
Cannot access wamp server on local network
1.
first of all
Port 80(or what ever you are using) and 443 must be allow for both TCP and UDP packets. To do this, create 2 inbound rules for TPC and UDP on Windows Firewall for port 80 and 443.
(or you can disable your whole firewall for testing but permanent solution if allow inbound rule)
2.
If you are using WAMPServer 3 See bottom of answer
For WAMPServer versions <= 2.5
You need to change the security setting on Apache to allow access from anywhere else, so edit your httpd.conf
file.
Change this section from :
# onlineoffline tag - don't remove
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
Allow from ::1
Allow from localhost
To :
# onlineoffline tag - don't remove
Order Allow,Deny
Allow from all
if "Allow from all" line not work for your then use "Require all granted"
then it will work for you.
WAMPServer 3 has a different method
In version 3 and > of WAMPServer there is a Virtual Hosts pre defined for localhost
so dont amend the httpd.conf
file at all, leave it as you found it.
Using the menus, edit the httpd-vhosts.conf
file.
It should look like this :
<VirtualHost *:80>
ServerName localhost
DocumentRoot D:/wamp/www
<Directory "D:/wamp/www/">
Options +Indexes +FollowSymLinks +MultiViews
AllowOverride All
Require local
</Directory>
</VirtualHost>
Amend it to
<VirtualHost *:80>
ServerName localhost
DocumentRoot D:/wamp/www
<Directory "D:/wamp/www/">
Options +Indexes +FollowSymLinks +MultiViews
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
Note:if you are running wamp for other than port 80 then VirtualHost will be like VirtualHost *:86.(86 or port whatever you are using) instead of VirtualHost *:80
3.
Dont forget to restart All Services of Wamp or Apache after making this change
How to sum a variable by group
I find ave
very helpful (and efficient) when you need to apply different aggregation functions on different columns (and you must/want to stick on base R) :
e.g.
Given this input :
DF <-
data.frame(Categ1=factor(c('A','A','B','B','A','B','A')),
Categ2=factor(c('X','Y','X','X','X','Y','Y')),
Samples=c(1,2,4,3,5,6,7),
Freq=c(10,30,45,55,80,65,50))
> DF
Categ1 Categ2 Samples Freq
1 A X 1 10
2 A Y 2 30
3 B X 4 45
4 B X 3 55
5 A X 5 80
6 B Y 6 65
7 A Y 7 50
we want to group by Categ1
and Categ2
and compute the sum of Samples
and mean of Freq
.
Here's a possible solution using ave
:
# create a copy of DF (only the grouping columns)
DF2 <- DF[,c('Categ1','Categ2')]
# add sum of Samples by Categ1,Categ2 to DF2
# (ave repeats the sum of the group for each row in the same group)
DF2$GroupTotSamples <- ave(DF$Samples,DF2,FUN=sum)
# add mean of Freq by Categ1,Categ2 to DF2
# (ave repeats the mean of the group for each row in the same group)
DF2$GroupAvgFreq <- ave(DF$Freq,DF2,FUN=mean)
# remove the duplicates (keep only one row for each group)
DF2 <- DF2[!duplicated(DF2),]
Result :
> DF2
Categ1 Categ2 GroupTotSamples GroupAvgFreq
1 A X 6 45
2 A Y 9 40
3 B X 7 50
6 B Y 6 65
No process is on the other end of the pipe (SQL Server 2012)
If you are trying to login with SQL credentials, you can also try changing the LoginMode for SQL Server in the registry to allow both SQL Server and Windows Authentication.
- Open regedit
- Go to the SQL instance key (may vary depending on your instance name):
Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL14.SQLEXPRESS\MSSQLServer\
- Set LoginMode to 2
- Restart SQL service and SQL Server Management Studio and try again.
Go to next item in ForEach-Object
I know this is an old post, but I wanted to add something I learned for the next folks who land here while googling.
In Powershell 5.1, you want to use continue
to move onto the next item in your loop. I tested with 6 items in an array, had a foreach
loop through, but put an if statement with:
foreach($i in $array){
write-host -fore green "hello $i"
if($i -like "something"){
write-host -fore red "$i is bad"
continue
write-host -fore red "should not see this"
}
}
Of the 6 items, the 3rd one was something. As expected, it looped through the first 2, then the matching something gave me the red line where $i
matched, I saw something is bad
and then it went on to the next item in the array without saying should not see this
. I tested with return
and it exited the loop altogether.
How can I build for release/distribution on the Xcode 4?
To set the build configuration to Debug or Release, choose 'Edit Scheme' from the 'Product' menu.
Then you see a clear choice.
The Apple Transition Guide mentions a button at the top left of the Xcode screen, but I cannot see it in Xcode 4.3.
Dynamically load a JavaScript file
The technique we use at work is to request the javascript file using an AJAX request and then eval() the return. If you're using the prototype library, they support this functionality in their Ajax.Request call.
How to save traceback / sys.exc_info() values in a variable?
sys.exc_info() returns a tuple with three values (type, value, traceback).
- Here type gets the exception type of the Exception being handled
- value is the arguments that are being passed to constructor of exception class
- traceback contains the stack information like where the exception occurred etc.
For Example, In the following program
try:
a = 1/0
except Exception,e:
exc_tuple = sys.exc_info()
Now If we print the tuple the values will be this.
- exc_tuple[0] value will be "ZeroDivisionError"
- exc_tuple[1] value will be "integer division or modulo by zero" (String passed as parameter to the exception class)
- exc_tuple[2] value will be "trackback object at (some memory address)"
The above details can also be fetched by simply printing the exception in string format.
print str(e)
Vagrant shared and synced folders
shared folders VS synced folders
Basically shared folders are renamed to synced folder from v1 to v2 (docs), under the bonnet it is still using vboxsf
between host and guest (there is known performance issues if there are large numbers of files/directories).
Vagrantfile directory mounted as /vagrant
in guest
Vagrant is mounting the current working directory (where Vagrantfile
resides) as /vagrant
in the guest, this is the default behaviour.
See docs
NOTE: By default, Vagrant will share your project directory (the directory with the Vagrantfile) to /vagrant.
You can disable this behaviour by adding cfg.vm.synced_folder ".", "/vagrant", disabled: true
in your Vagrantfile
.
Why synced folder is not working
Based on the output /tmp
on host was NOT mounted during up time.
Use VAGRANT_INFO=debug vagrant up
or VAGRANT_INFO=debug vagrant reload
to start the VM for more output regarding why the synced folder is not mounted. Could be a permission issue (mode bits of /tmp
on host should be drwxrwxrwt
).
I did a test quick test using the following and it worked (I used opscode bento raring vagrant base box)
config.vm.synced_folder "/tmp", "/tmp/src"
output
$ vagrant reload
[default] Attempting graceful shutdown of VM...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Available bridged network interfaces:
1) eth0
2) vmnet8
3) lxcbr0
4) vmnet1
What interface should the network bridge to? 1
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Running 'pre-boot' VM customizations...
[default] Booting VM...
[default] Waiting for VM to boot. This can take a few minutes.
[default] VM booted and ready for use!
[default] Configuring and enabling network interfaces...
[default] Mounting shared folders...
[default] -- /vagrant
[default] -- /tmp/src
Within the VM, you can see the mount info /tmp/src on /tmp/src type vboxsf (uid=900,gid=900,rw)
.
How can I switch my signed in user in Visual Studio 2013?
what worked for me was to go to Team explorer in VS2013 and under 'connect' you'll see a link saying 'select team projects'. click this and a window opens asking you to select the project but in the bottom left corner of this window there is a (switch user) link, just click this and use your new id. simple
AngularJS : When to use service instead of factory
The concept for all these providers is much simpler than it initially appears. If you dissect a provider you and pull out the different parts it becomes very clear.
To put it simply each one of these providers is a specialized version of the other, in this order: provider
> factory
> value
/ constant
/ service
.
So long the provider does what you can you can use the provider further down the chain which would result in writing less code. If it doesn't accomplish what you want you can go up the chain and you'll just have to write more code.
This image illustrates what I mean, in this image you will see the code for a provider, with the portions highlighted showing you which portions of the provider could be used to create a factory, value, etc instead.
(source: simplygoodcode.com)
For more details and examples from the blog post where I got the image from go to: http://www.simplygoodcode.com/2015/11/the-difference-between-service-provider-and-factory-in-angularjs/
Invalid hook call. Hooks can only be called inside of the body of a function component
I had this issue when I used npm link
to install my local library, which I've built using cra
. I found the answer here. Which literally says:
This problem can also come up when you use npm link or an equivalent.
In that case, your bundler might “see” two Reacts — one in application
folder and one in your library folder. Assuming 'myapp' and 'mylib'
are sibling folders, one possible fix is to run 'npm link
../myapp/node_modules/react' from 'mylib'. This should make the
library use the application’s React copy.
Thus, running the command: npm link ../../libraries/core/decipher/node_modules/react
from my project folder has fixed the issue.
How can I delay a method call for 1 second?
There is a Swift 3 solution from the checked solution :
self.perform(#selector(self.targetMethod), with: self, afterDelay: 1.0)
And there is the method
@objc fileprivate func targetMethod(){
}
Send auto email programmatically
Sending email programmatically with Kotlin.
- simple email sending, not all the other features (like attachments).
- TLS is always on
- Only 1 gradle email dependency needed also.
I also found this list of email POP services really helpful:
https://support.office.com/en-gb/article/pop-and-imap-email-settings-for-outlook-8361e398-8af4-4e97-b147-6c6c4ac95353
How to use:
val auth = EmailService.UserPassAuthenticator("yourUser", "yourPass")
val to = listOf(InternetAddress("[email protected]"))
val from = InternetAddress("[email protected]")
val email = EmailService.Email(auth, to, from, "Test Subject", "Hello Body World")
val emailService = EmailService("yourSmtpServer", 587)
GlobalScope.launch { // or however you do background threads
emailService.send(email)
}
The code:
import java.util.*
import javax.mail.*
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeBodyPart
import javax.mail.internet.MimeMessage
import javax.mail.internet.MimeMultipart
class EmailService(private var server: String, private var port: Int) {
data class Email(
val auth: Authenticator,
val toList: List<InternetAddress>,
val from: Address,
val subject: String,
val body: String
)
class UserPassAuthenticator(private val username: String, private val password: String) : Authenticator() {
override fun getPasswordAuthentication(): PasswordAuthentication {
return PasswordAuthentication(username, password)
}
}
fun send(email: Email) {
val props = Properties()
props["mail.smtp.auth"] = "true"
props["mail.user"] = email.from
props["mail.smtp.host"] = server
props["mail.smtp.port"] = port
props["mail.smtp.starttls.enable"] = "true"
props["mail.smtp.ssl.trust"] = server
props["mail.mime.charset"] = "UTF-8"
val msg: Message = MimeMessage(Session.getDefaultInstance(props, email.auth))
msg.setFrom(email.from)
msg.sentDate = Calendar.getInstance().time
msg.setRecipients(Message.RecipientType.TO, email.toList.toTypedArray())
// msg.setRecipients(Message.RecipientType.CC, email.ccList.toTypedArray())
// msg.setRecipients(Message.RecipientType.BCC, email.bccList.toTypedArray())
msg.replyTo = arrayOf(email.from)
msg.addHeader("X-Mailer", CLIENT_NAME)
msg.addHeader("Precedence", "bulk")
msg.subject = email.subject
msg.setContent(MimeMultipart().apply {
addBodyPart(MimeBodyPart().apply {
setText(email.body, "iso-8859-1")
//setContent(email.htmlBody, "text/html; charset=UTF-8")
})
})
Transport.send(msg)
}
companion object {
const val CLIENT_NAME = "Android StackOverflow programmatic email"
}
}
Gradle:
dependencies {
implementation 'com.sun.mail:android-mail:1.6.4'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3"
}
AndroidManifest:
<uses-permission name="android.permission.INTERNET" />
Disable Scrolling on Body
To accomplish this, add 2 CSS properties on the <body>
element.
body {
height: 100%;
overflow-y: hidden;
}
These days there are many news websites which require users to create an account. Typically they will give full access to the page for about a second, and then they show a pop-up, and stop users from scrolling down.
how to change any data type into a string in python
Be careful if you really want to "change" the data type. Like in other cases (e.g. changing the iterator in a for
loop) this might bring up unexpected behaviour:
>> dct = {1:3, 2:1}
>> len(str(dct))
12
>> print(str(dct))
{1: 31, 2: 0}
>> l = ["all","colours"]
>> len(str(l))
18
What techniques can be used to define a class in JavaScript, and what are their trade-offs?
A base
function Base(kind) {
this.kind = kind;
}
A class
// Shared var
var _greeting;
(function _init() {
Class.prototype = new Base();
Class.prototype.constructor = Class;
Class.prototype.log = function() { _log.apply(this, arguments); }
_greeting = "Good afternoon!";
})();
function Class(name, kind) {
Base.call(this, kind);
this.name = name;
}
// Shared function
function _log() {
console.log(_greeting + " Me name is " + this.name + " and I'm a " + this.kind);
}
Action
var c = new Class("Joe", "Object");
c.log(); // "Good afternoon! Me name is Joe and I'm a Object"
Update multiple rows using select statement
If you have ids in both tables, the following works:
update table2
set value = (select value from table1 where table1.id = table2.id)
Perhaps a better approach is a join:
update table2
set value = table1.value
from table1
where table1.id = table2.id
Note that this syntax works in SQL Server but may be different in other databases.
How do I make a dictionary with multiple keys to one value?
I guess you mean this:
class Value:
def __init__(self, v=None):
self.v = v
v1 = Value(1)
v2 = Value(2)
d = {'a': v1, 'b': v1, 'c': v2, 'd': v2}
d['a'].v += 1
d['b'].v == 2 # True
- Python's strings and numbers are immutable objects,
- So, if you want
d['a']
and d['b']
to point to the same value that "updates" as it changes, make the value refer to a mutable object (user-defined class like above, or a dict
, list
, set
).
- Then, when you modify the object at
d['a']
, d['b']
changes at same time because they both point to same object.
I'm getting Key error in python
For dict, just use
if key in dict
and don't use searching in key list
if key in dict.keys()
The latter will be more time-consuming.
How to re-enable right click so that I can inspect HTML elements in Chrome?
I built upon @Chema solution and added resetting pointer-events
and user-select
. If they are set to none
for an image, right-clicking it does not invoke the context menu for the image with options to view or save it.
javascript:function enableContextMenu(aggressive = true) { void(document.ondragstart=null); void(document.onselectstart=null); void(document.onclick=null); void(document.onmousedown=null); void(document.onmouseup=null); void(document.body.oncontextmenu=null); enableRightClickLight(document); if (aggressive) { enableRightClick(document); removeContextMenuOnAll('body'); removeContextMenuOnAll('img'); removeContextMenuOnAll('td'); } } function removeContextMenuOnAll(tagName) { var elements = document.getElementsByTagName(tagName); for (var i = 0; i < elements.length; i++) { enableRightClick(elements[i]); enablePointerEvents(elements[i]); } } function enableRightClickLight(el) { el || (el = document); el.addEventListener('contextmenu', bringBackDefault, true); } function enableRightClick(el) { el || (el = document); el.addEventListener('contextmenu', bringBackDefault, true); el.addEventListener('dragstart', bringBackDefault, true); el.addEventListener('selectstart', bringBackDefault, true); el.addEventListener('click', bringBackDefault, true); el.addEventListener('mousedown', bringBackDefault, true); el.addEventListener('mouseup', bringBackDefault, true); } function restoreRightClick(el) { el || (el = document); el.removeEventListener('contextmenu', bringBackDefault, true); el.removeEventListener('dragstart', bringBackDefault, true); el.removeEventListener('selectstart', bringBackDefault, true); el.removeEventListener('click', bringBackDefault, true); el.removeEventListener('mousedown', bringBackDefault, true); el.removeEventListener('mouseup', bringBackDefault, true); } function bringBackDefault(event) { event.returnValue = true; (typeof event.stopPropagation === 'function') && event.stopPropagation(); (typeof event.cancelBubble === 'function') && event.cancelBubble(); } function enablePointerEvents(el) { if (!el) return; el.style.pointerEvents='auto'; el.style.webkitTouchCallout='default'; el.style.webkitUserSelect='auto'; el.style.MozUserSelect='auto'; el.style.msUserSelect='auto'; el.style.userSelect='auto'; enablePointerEvents(el.parentElement); } enableContextMenu();
Java string split with "." (dot)
The dot "." is a special character in java regex engine, so you have to use "\\." to escape this character:
final String extensionRemoved = filename.split("\\.")[0];
I hope this helps
C# Select elements in list as List of string
List<string> empnames = emplist.Select(e => e.Ename).ToList();
This is an example of Projection in Linq. Followed by a ToList
to resolve the IEnumerable<string>
into a List<string>
.
Alternatively in Linq syntax (head compiled):
var empnamesEnum = from emp in emplist
select emp.Ename;
List<string> empnames = empnamesEnum.ToList();
Projection is basically representing the current type of the enumerable as a new type. You can project to anonymous types, another known type by calling constructors etc, or an enumerable of one of the properties (as in your case).
For example, you can project an enumerable of Employee
to an enumerable of Tuple<int, string>
like so:
var tuples = emplist.Select(e => new Tuple<int, string>(e.EID, e.Ename));
How do you make a div follow as you scroll?
You can either use the css property Fixed, or if you need something more fine-tuned then you need to use javascript and track the scrollTop property which defines where the user agent's scrollbar location is (0 being at the top ... and x being at the bottom)
.Fixed
{
position: fixed;
top: 20px;
}
or with jQuery:
$('#ParentContainer').scroll(function() {
$('#FixedDiv').css('top', $(this).scrollTop());
});
How to get the full path of running process?
You can use pInvoke and a native call such as the following. This doesn't seem to have the 32 / 64 bit limitation (at least in my testing)
Here is the code
using System.Runtime.InteropServices;
[DllImport("Kernel32.dll")]
static extern uint QueryFullProcessImageName(IntPtr hProcess, uint flags, StringBuilder text, out uint size);
//Get the path to a process
//proc = the process desired
private string GetPathToApp (Process proc)
{
string pathToExe = string.Empty;
if (null != proc)
{
uint nChars = 256;
StringBuilder Buff = new StringBuilder((int)nChars);
uint success = QueryFullProcessImageName(proc.Handle, 0, Buff, out nChars);
if (0 != success)
{
pathToExe = Buff.ToString();
}
else
{
int error = Marshal.GetLastWin32Error();
pathToExe = ("Error = " + error + " when calling GetProcessImageFileName");
}
}
return pathToExe;
}
Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel
If, like me, none of the above quite works, it might be worth also specifically trying a lower TLS version alone. I had tried both of the following, but didn't seem to solve my problem:
[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls
In the end, it was only when I targetted TLS 1.0 (specifically remove 1.1 and 1.2 in the code) that it worked:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls
The local server (that this was being attempted on) is fine with TLS 1.2, although the remote server (which was previously "confirmed" as fine for TLS 1.2 by a 3rd party) seems not to be.
Hope this helps someone.
Internal and external fragmentation
First of all the term fragmentation cues there's an entity divided into parts — fragments.
Internal fragmentation: Typical paper book is a collection of pages (text divided into pages). When a chapter's end isn't located at the end of page and new chapter starts from new page, there's a gap between those chapters and it's a waste of space — a chunk (page for a book) has unused space inside (internally) — "white space"
External fragmentation: Say you have a paper diary and you didn't write your thoughts sequentially page after page, but, rather randomly. You might end up with a situation when you'd want to write 3 pages in row, but you can't since there're no 3 clean pages one-by-one, you might have 15 clean pages in the diary totally, but they're not contiguous
Can we rely on String.isEmpty for checking null condition on a String in Java?
No, absolutely not - because if acct
is null, it won't even get to isEmpty
... it will immediately throw a NullPointerException
.
Your test should be:
if (acct != null && !acct.isEmpty())
Note the use of &&
here, rather than your ||
in the previous code; also note how in your previous code, your conditions were wrong anyway - even with &&
you would only have entered the if
body if acct
was an empty string.
Alternatively, using Guava:
if (!Strings.isNullOrEmpty(acct))
How does the SQL injection from the "Bobby Tables" XKCD comic work?
Say you naively wrote a student creation method like this:
void createStudent(String name) {
database.execute("INSERT INTO students (name) VALUES ('" + name + "')");
}
And someone enters the name Robert'); DROP TABLE STUDENTS; --
What gets run on the database is this query:
INSERT INTO students (name) VALUES ('Robert'); DROP TABLE STUDENTS --')
The semicolon ends the insert command and starts another; the -- comments out the rest of the line. The DROP TABLE command is executed...
This is why bind parameters are a good thing.
How to check String in response body with mockMvc
Taken from spring's tutorial
mockMvc.perform(get("/" + userName + "/bookmarks/"
+ this.bookmarkList.get(0).getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$.id", is(this.bookmarkList.get(0).getId().intValue())))
.andExpect(jsonPath("$.uri", is("http://bookmark.com/1/" + userName)))
.andExpect(jsonPath("$.description", is("A description")));
is
is available from import static org.hamcrest.Matchers.*;
jsonPath
is available from import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
and jsonPath
reference can be found here
encrypt and decrypt md5
/* you can match the exact string with table value*/
if(md5("string to match") == $res["hashstring"])
echo "login correct";
Getting the names of all files in a directory with PHP
Recursive code to explore all the file contained in a directory ('$path' contains the path of the directory):
function explore_directory($path)
{
$scans = scandir($path);
foreach($scans as $scan)
{
$new_path = $path.$scan;
if(is_dir($new_path))
{
$new_path = $new_path."/";
explore_directory($new_path);
}
else // A file
{
/*
Body of code
*/
}
}
}
Installing and Running MongoDB on OSX
Download MongoDB and install it on your local machine.
Link https://www.mongodb.com/try/download/enterprise
Extract the file and put it on the desktop.
Create another folder where you want to store the data. I have created mongodb-data folder.
Then run the below command.
Desktop/mongodb/bin/mongod --dbpath=/Users/yourname/Desktop/mongodb-data/
Before the hyphen is the executable path of your mongoDB and after hyphen is your data store.
Getting java.net.SocketTimeoutException: Connection timed out in android
If you are using Kotlin + Retrofit + Coroutines then just use try
and catch
for network operations like,
viewModelScope.launch(Dispatchers.IO) {
try {
val userListResponseModel = apiEndPointsInterface.usersList()
returnusersList(userListResponseModel)
} catch (e: Exception) {
e.printStackTrace()
}
}
Where, Exception is type of kotlin
and not of java.lang
This will handle every exception like,
- HttpException
- SocketTimeoutException
- FATAL EXCEPTION: DefaultDispatcher etc
Here is my usersList()
function
@GET(AppConstants.APIEndPoints.HOME_CONTENT)
suspend fun usersList(): UserListResponseModel
Note:
Your RetrofitClient Classs must have this as client
OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
Use of Custom Data Types in VBA
It looks like you want to define Truck as a Class
with properties NumberOfAxles, AxleWeights & AxleSpacings.
This can be defined in a CLASS MODULE (here named clsTrucks)
Option Explicit
Private tID As String
Private tNumberOfAxles As Double
Private tAxleSpacings As Double
Public Property Get truckID() As String
truckID = tID
End Property
Public Property Let truckID(value As String)
tID = value
End Property
Public Property Get truckNumberOfAxles() As Double
truckNumberOfAxles = tNumberOfAxles
End Property
Public Property Let truckNumberOfAxles(value As Double)
tNumberOfAxles = value
End Property
Public Property Get truckAxleSpacings() As Double
truckAxleSpacings = tAxleSpacings
End Property
Public Property Let truckAxleSpacings(value As Double)
tAxleSpacings = value
End Property
then in a MODULE the following defines a new truck and it's properties and adds it to a collection of trucks and then retrieves the collection.
Option Explicit
Public TruckCollection As New Collection
Sub DefineNewTruck()
Dim tempTruck As clsTrucks
Dim i As Long
'Add 5 trucks
For i = 1 To 5
Set tempTruck = New clsTrucks
'Random data
tempTruck.truckID = "Truck" & i
tempTruck.truckAxleSpacings = 13.5 + i
tempTruck.truckNumberOfAxles = 20.5 + i
'tempTruck.truckID is the collection key
TruckCollection.Add tempTruck, tempTruck.truckID
Next i
'retrieve 5 trucks
For i = 1 To 5
'retrieve by collection index
Debug.Print TruckCollection(i).truckAxleSpacings
'retrieve by key
Debug.Print TruckCollection("Truck" & i).truckAxleSpacings
Next i
End Sub
There are several ways of doing this so it really depends on how you intend to use the data as to whether an a class/collection is the best setup or arrays/dictionaries etc.
Using a custom typeface in Android
@majinboo's answer is revised for performance and memory management. Any more than one font need related Activity can use this Font class by giving the constructor itself as a parameter.
@Override
public void onCreate(Bundle savedInstanceState)
{
Font font = new Font(this);
}
Revised Fonts class is as below:
public class Fonts
{
private HashMap<AssetTypefaces, Typeface> hashMapFonts;
private enum AssetTypefaces
{
RobotoLight,
RobotoThin,
RobotoCondensedBold,
RobotoCondensedLight,
RobotoCondensedRegular
}
public Fonts(Context context)
{
AssetManager mngr = context.getAssets();
hashMapFonts = new HashMap<AssetTypefaces, Typeface>();
hashMapFonts.put(AssetTypefaces.RobotoLight, Typeface.createFromAsset(mngr, "fonts/Roboto-Light.ttf"));
hashMapFonts.put(AssetTypefaces.RobotoThin, Typeface.createFromAsset(mngr, "fonts/Roboto-Thin.ttf"));
hashMapFonts.put(AssetTypefaces.RobotoCondensedBold, Typeface.createFromAsset(mngr, "fonts/RobotoCondensed-Bold.ttf"));
hashMapFonts.put(AssetTypefaces.RobotoCondensedLight, Typeface.createFromAsset(mngr, "fonts/RobotoCondensed-Light.ttf"));
hashMapFonts.put(AssetTypefaces.RobotoCondensedRegular, Typeface.createFromAsset(mngr, "fonts/RobotoCondensed-Regular.ttf"));
}
private Typeface getTypeface(String fontName)
{
try
{
AssetTypefaces typeface = AssetTypefaces.valueOf(fontName);
return hashMapFonts.get(typeface);
}
catch (IllegalArgumentException e)
{
// e.printStackTrace();
return Typeface.DEFAULT;
}
}
public void setupLayoutTypefaces(View v)
{
try
{
if (v instanceof ViewGroup)
{
ViewGroup vg = (ViewGroup) v;
for (int i = 0; i < vg.getChildCount(); i++)
{
View child = vg.getChildAt(i);
setupLayoutTypefaces(child);
}
}
else if (v instanceof TextView)
{
((TextView) v).setTypeface(getTypeface(v.getTag().toString()));
}
}
catch (Exception e)
{
e.printStackTrace();
// ignore
}
}
}
How do you launch the JavaScript debugger in Google Chrome?
Now google chrome has introduce new feature. By Using this feature You can edit you code in chrome browse. (Permanent change on code location)
For that Press F12 --> Source Tab -- (right side) --> File System - in that please select your location of code. and then chrome browser
will ask you permission and after that code will be sink with green color. and you can modify your code and it will also reflect on you code location (It means it will Permanent change)
Thanks
Writing an mp4 video using python opencv
The problem such as OpenCV: FFMPEG: tag 0x5634504d/'MP4V' is not supported with codec id 13 and format 'mp4 / MP4 (MPEG-4 Part 14)' OpenCV: FFMPEG: fallback to use tag 0x00000020/' ???'
maybe that your output video size is not the same as original video. You can look over the frame size of video first.
Parsing JSON objects for HTML table
You can use KnockoutJS with jQuery. KnockoutJS have smart data-binding features. By using the foreach binding feature you can write your code like this example:
HTML:
<table>
<thead>
<tr>
<th>User Name</th>
<th>Score</th>
<th>Team</th>
</tr>
</thead>
<tbody data-bind="foreach: teams">
<tr>
<td data-bind="text: User_Name"></td>
<td data-bind="text: score "></td>
<td data-bind="text: team "></td>
</tr>
</tbody>
</table>
JavaScript:
$(document).ready(function () {
$.getJSON(url,function (json) {
ko.applyBindings({
teams: json
});
}
});
});
Fiddle Demo with your dummy data
How do I use Node.js Crypto to create a HMAC-SHA1 hash?
A few years ago it was said that update()
and digest()
were legacy methods and the new streaming API approach was introduced. Now the docs say that either method can be used. For example:
var crypto = require('crypto');
var text = 'I love cupcakes';
var secret = 'abcdeg'; //make this your secret!!
var algorithm = 'sha1'; //consider using sha256
var hash, hmac;
// Method 1 - Writing to a stream
hmac = crypto.createHmac(algorithm, secret);
hmac.write(text); // write in to the stream
hmac.end(); // can't read from the stream until you call end()
hash = hmac.read().toString('hex'); // read out hmac digest
console.log("Method 1: ", hash);
// Method 2 - Using update and digest:
hmac = crypto.createHmac(algorithm, secret);
hmac.update(text);
hash = hmac.digest('hex');
console.log("Method 2: ", hash);
Tested on node v6.2.2 and v7.7.2
See https://nodejs.org/api/crypto.html#crypto_class_hmac. Gives more examples for using the streaming approach.
Windows-1252 to UTF-8 encoding
UTF-8 does not have a BOM as it is both superfluous and invalid. Where a BOM is helpful is in UTF-16 which may be byte swapped as in the case of Microsoft. UTF-16 if for internal representation in a memory buffer. Use UTF-8 for interchange. By default both UTF-8, anything else derived from US-ASCII and UTF-16 are natural/network byte order. The Microsoft UTF-16 requires a BOM as it is byte swapped.
To covert Windows-1252 to ISO8859-15, I first convert ISO8859-1 to US-ASCII for codes with similar glyphs. I then convert Windows-1252 up to ISO8859-15, other non-ISO8859-15 glyphs to multiple US-ASCII characters.
Django - "no module named django.core.management"
I got the same problem trying to use the python manage.py runserver. In my case I just use sudo su. Use the terminal as a root and try it again an it works partially. So I use python manage.py migrate comand and it fix it.
Stop executing further code in Java
There are two way to stop current method/process :
- Throwing Exception.
- returnning the value even if it is void method.
Option : you can also kill the current thread to stop it.
For example :
public void onClick(){
if(condition == true){
return;
<or>
throw new YourException();
}
string.setText("This string should not change if condition = true");
}
Yahoo Finance All Currencies quote API Documentation
As NT3RP told us that:
... we (Yahoo!) don't have a Finance API. It appears some have reverse engineered an API that they use to pull Finance data, but they are breaking our Terms of Service...
So I just thought of sharing this site with you:
http://josscrowcroft.github.com/open-exchange-rates/
[update: site has moved to - http://openexchangerates.org]
This site says:
No access fees, no rate limits, no ugly XML - just free, hourly updated exchange rates in JSON format
[update: Free for personal use, a bargain for your business.]
I hope I've helped and this is of some use to you (and others too). : )
Get first and last day of month using threeten, LocalDate
Try this:
LocalDate initial = LocalDate.of(2014, 2, 13);
LocalDate start = initial.withDayOfMonth(1);
LocalDate end = initial.withDayOfMonth(initial.getMonthOfYear().getLastDayOfMonth(false));
System.out.println(start);
System.out.println(end);
you can find the desire output but need to take care of parameter true/false for getLastDayOfMonth method
that parameter denotes leap year
How to change btn color in Bootstrap
You can add custom colors using bootstrap theming in your config file for example variables.scss
and make sure you import that file before bootstrap when compiling.
$theme-colors: (
"whatever": #900
);
Now you can do .btn-whatever
Copy/duplicate database without using mysqldump
In PHP:
function cloneDatabase($dbName, $newDbName){
global $admin;
$db_check = @mysql_select_db ( $dbName );
$getTables = $admin->query("SHOW TABLES");
$tables = array();
while($row = mysql_fetch_row($getTables)){
$tables[] = $row[0];
}
$createTable = mysql_query("CREATE DATABASE `$newDbName` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;") or die(mysql_error());
foreach($tables as $cTable){
$db_check = @mysql_select_db ( $newDbName );
$create = $admin->query("CREATE TABLE $cTable LIKE ".$dbName.".".$cTable);
if(!$create) {
$error = true;
}
$insert = $admin->query("INSERT INTO $cTable SELECT * FROM ".$dbName.".".$cTable);
}
return !isset($error);
}
// usage
$clone = cloneDatabase('dbname','newdbname'); // first: toCopy, second: new database
How to call a php script/function on a html button click
You can also use
$(document).ready(function() {
//some even that will run ajax request - for example click on a button
var uname = $('#username').val();
$.ajax({
type: 'POST',
url: 'func.php', //this should be url to your PHP file
dataType: 'html',
data: {func: 'toptable', user_id: uname},
beforeSend: function() {
$('#right').html('checking');
},
complete: function() {},
success: function(html) {
$('#right').html(html);
}
});
});
And your func.php:
function toptable()
{
echo 'something happens in here';
}
Hope it helps somebody
How do I update an entity using spring-data-jpa?
Identity of entities is defined by their primary keys. Since firstname
and lastname
are not parts of the primary key, you cannot tell JPA to treat User
s with the same firstname
s and lastname
s as equal if they have different userId
s.
So, if you want to update a User
identified by its firstname
and lastname
, you need to find that User
by a query, and then change appropriate fields of the object your found. These changes will be flushed to the database automatically at the end of transaction, so that you don't need to do anything to save these changes explicitly.
EDIT:
Perhaps I should elaborate on overall semantics of JPA. There are two main approaches to design of persistence APIs:
insert/update approach. When you need to modify the database you should call methods of persistence API explicitly: you call insert
to insert an object, or update
to save new state of the object to the database.
Unit of Work approach. In this case you have a set of objects managed by persistence library. All changes you make to these objects will be flushed to the database automatically at the end of Unit of Work (i.e. at the end of the current transaction in typical case). When you need to insert new record to the database, you make the corresponding object managed. Managed objects are identified by their primary keys, so that if you make an object with predefined primary key managed, it will be associated with the database record of the same id, and state of this object will be propagated to that record automatically.
JPA follows the latter approach. save()
in Spring Data JPA is backed by merge()
in plain JPA, therefore it makes your entity managed as described above. It means that calling save()
on an object with predefined id will update the corresponding database record rather than insert a new one, and also explains why save()
is not called create()
.
Scanner vs. StringTokenizer vs. String.Split
String.split seems to be much slower than StringTokenizer. The only advantage with split is that you get an array of the tokens. Also you can use any regular expressions in split.
org.apache.commons.lang.StringUtils has a split method which works much more faster than any of two viz. StringTokenizer or String.split.
But the CPU utilization for all the three is nearly the same. So we also need a method which is less CPU intensive, which I am still not able to find.
Zoom in on a point (using scale and translate)
I ran into this problem using c++, which I probably shouldn't have had i just used OpenGL matrices to begin with...anyways, if you're using a control whose origin is the top left corner, and you want pan/zoom like google maps, here's the layout (using allegro as my event handler):
// initialize
double originx = 0; // or whatever its base offset is
double originy = 0; // or whatever its base offset is
double zoom = 1;
.
.
.
main(){
// ...set up your window with whatever
// tool you want, load resources, etc
.
.
.
while (running){
/* Pan */
/* Left button scrolls. */
if (mouse == 1) {
// get the translation (in window coordinates)
double scroll_x = event.mouse.dx; // (x2-x1)
double scroll_y = event.mouse.dy; // (y2-y1)
// Translate the origin of the element (in window coordinates)
originx += scroll_x;
originy += scroll_y;
}
/* Zoom */
/* Mouse wheel zooms */
if (event.mouse.dz!=0){
// Get the position of the mouse with respect to
// the origin of the map (or image or whatever).
// Let us call these the map coordinates
double mouse_x = event.mouse.x - originx;
double mouse_y = event.mouse.y - originy;
lastzoom = zoom;
// your zoom function
zoom += event.mouse.dz * 0.3 * zoom;
// Get the position of the mouse
// in map coordinates after scaling
double newx = mouse_x * (zoom/lastzoom);
double newy = mouse_y * (zoom/lastzoom);
// reverse the translation caused by scaling
originx += mouse_x - newx;
originy += mouse_y - newy;
}
}
}
.
.
.
draw(originx,originy,zoom){
// NOTE:The following is pseudocode
// the point is that this method applies so long as
// your object scales around its top-left corner
// when you multiply it by zoom without applying a translation.
// draw your object by first scaling...
object.width = object.width * zoom;
object.height = object.height * zoom;
// then translating...
object.X = originx;
object.Y = originy;
}
R - argument is of length zero in if statement
The same error message results not only for null
but also for e.g. factor(0)
. In this case, the query must be if(length(element) > 0 & otherCondition)
or better check both cases with if(!is.null(element) & length(element) > 0 & otherCondition)
.
bootstrap initially collapsed element
If removing the in
class doesn't work for you, such was my case, you can force the collapsed initial state using the CSS display property:
...
<div id="collapseOne" class="accordion-body collapse" style="display: none;">
...
How can I recover a lost commit in Git?
Before answering, let's add some background, explaining what this HEAD
is.
First of all what is HEAD?
HEAD
is simply a reference to the current commit (latest) on the current branch.
There can only be a single HEAD
at any given time (excluding git worktree
).
The content of HEAD
is stored inside .git/HEAD
and it contains the 40 bytes SHA-1 of the current commit.
detached HEAD
If you are not on the latest commit - meaning that HEAD
is pointing to a prior commit in history it's called detached HEAD
.
On the command line, it will look like this - SHA-1 instead of the branch name since the HEAD
is not pointing to the tip of the current branch:
A few options on how to recover from a detached HEAD:
git checkout <commit_id>
git checkout -b <new branch> <commit_id>
git checkout HEAD~X // x is the number of commits t go back
This will checkout new branch pointing to the desired commit.
This command will checkout to a given commit.
At this point, you can create a branch and start to work from this point on.
# Checkout a given commit.
# Doing so will result in a `detached HEAD` which mean that the `HEAD`
# is not pointing to the latest so you will need to checkout branch
# in order to be able to update the code.
git checkout <commit-id>
# Create a new branch forked to the given commit
git checkout -b <branch name>
You can always use the reflog
as well.
git reflog
will display any change which updated the HEAD
and checking out the desired reflog entry will set the HEAD
back to this commit.
Every time the HEAD is modified there will be a new entry in the reflog
git reflog
git checkout HEAD@{...}
This will get you back to your desired commit
"Move" your HEAD back to the desired commit.
# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32
# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts if you've modified things which were
# changed since the commit you reset to.
- Note: (Since Git 2.7) you can also use the
git rebase --no-autostash
as well.
"Undo" the given commit or commit range.
The reset command will "undo" any changes made in the given commit.
A new commit with the undo patch will be committed while the original commit will remain in the history as well.
# Add a new commit with the undo of the original one.
# The <sha-1> can be any commit(s) or commit range
git revert <sha-1>
This schema illustrates which command does what.
As you can see there, reset && checkout
modify the HEAD
.
Get an image extension from an uploaded file in Laravel
Do something like this:
if($request->hasFile('video')){
$video=$request->file('video');
$filename=str_random(20).".".$video->extension();
$path = Storage::putFileAs(
'/', $video, $filename
);
$data['video']=$filename;
}
best way to get folder and file list in Javascript
fs/promises and fs.Dirent
Here's an efficient, non-blocking ls
program using Node's fast fs.Dirent objects and fs/promises module. This approach allows you to skip wasteful fs.exist
or fs.stat
calls on every path -
// main.js
import { readdir } from "fs/promises"
import { join } from "path"
async function* ls (path = ".")
{ yield path
for (const dirent of await readdir(path, { withFileTypes: true }))
if (dirent.isDirectory())
yield* ls(join(path, dirent.name))
else
yield join(path, dirent.name)
}
async function* empty () {}
async function toArray (iter = empty())
{ let r = []
for await (const x of iter)
r.push(x)
return r
}
toArray(ls(".")).then(console.log, console.error)
Let's get some sample files so we can see ls
working -
$ yarn add immutable # (just some example package)
$ node main.js
[
'.',
'main.js',
'node_modules',
'node_modules/.yarn-integrity',
'node_modules/immutable',
'node_modules/immutable/LICENSE',
'node_modules/immutable/README.md',
'node_modules/immutable/contrib',
'node_modules/immutable/contrib/cursor',
'node_modules/immutable/contrib/cursor/README.md',
'node_modules/immutable/contrib/cursor/__tests__',
'node_modules/immutable/contrib/cursor/__tests__/Cursor.ts.skip',
'node_modules/immutable/contrib/cursor/index.d.ts',
'node_modules/immutable/contrib/cursor/index.js',
'node_modules/immutable/dist',
'node_modules/immutable/dist/immutable-nonambient.d.ts',
'node_modules/immutable/dist/immutable.d.ts',
'node_modules/immutable/dist/immutable.es.js',
'node_modules/immutable/dist/immutable.js',
'node_modules/immutable/dist/immutable.js.flow',
'node_modules/immutable/dist/immutable.min.js',
'node_modules/immutable/package.json',
'package.json',
'yarn.lock'
]
For added explanation and other ways to leverage async generators, see this Q&A.
Convert seconds to hh:mm:ss in Python
Code that does what was requested, with examples, and showing how cases he didn't specify are handled:
def format_seconds_to_hhmmss(seconds):
hours = seconds // (60*60)
seconds %= (60*60)
minutes = seconds // 60
seconds %= 60
return "%02i:%02i:%02i" % (hours, minutes, seconds)
def format_seconds_to_mmss(seconds):
minutes = seconds // 60
seconds %= 60
return "%02i:%02i" % (minutes, seconds)
minutes = 60
hours = 60*60
assert format_seconds_to_mmss(7*minutes + 30) == "07:30"
assert format_seconds_to_mmss(15*minutes + 30) == "15:30"
assert format_seconds_to_mmss(1000*minutes + 30) == "1000:30"
assert format_seconds_to_hhmmss(2*hours + 15*minutes + 30) == "02:15:30"
assert format_seconds_to_hhmmss(11*hours + 15*minutes + 30) == "11:15:30"
assert format_seconds_to_hhmmss(99*hours + 15*minutes + 30) == "99:15:30"
assert format_seconds_to_hhmmss(500*hours + 15*minutes + 30) == "500:15:30"
You can--and probably should--store this as a timedelta rather than an int, but that's a separate issue and timedelta doesn't actually make this particular task any easier.
Rounding float in Ruby
When displaying, you can use (for example)
>> '%.2f' % 2.3465
=> "2.35"
If you want to store it rounded, you can use
>> (2.3465*100).round / 100.0
=> 2.35
Strings in C, how to get subString
I think it's easy way... but I don't know how I can pass the result variable directly then I create a local char array as temp and return it.
char* substr(char *buff, uint8_t start,uint8_t len, char* substr)
{
strncpy(substr, buff+start, len);
substr[len] = 0;
return substr;
}