Is a DIV inside a TD a bad idea?
As everyone mentioned, it might not be a good idea for layout purposes. I arrived to this question because I was wondering the same and I only wanted to know if it would be valid code.
Since it's valid, you can use it for other purposes. For example, what I'm going to use it for is to put some fancy "CSSed" divs inside table rows and then use a quick jQuery function to allow the user to sort the information by price, name, etc. This way, the only layout table will give me is the "vertical order", but I'll control width, height, background, etc of the divs by CSS.
Generating statistics from Git repository
Just want to add gitqlite
into the mix of answers here, which is a command-line tool that enables execution of SQL queries on git data, such as SELECT * FROM commits WHERE author_name = 'foo'
etc.
Full disclosure, I'm a creator/maintainer of the project!
Resolving ORA-4031 "unable to allocate x bytes of shared memory"
The following are not needed as they they not fix the error:
ps -ef|grep oracle
- Find the smon and kill the pid for it
SQL> startup mount
SQL> create pfile from spfile;
Restarting the database will flush your pool and that solves a effect not the problem.
Fixate your large_pool so it can not go lower then a certain point or add memory and set a higher max memory.
.htaccess rewrite to redirect root URL to subdirectory
A little googling, gives me these results:
RewriteEngine On
RewriteBase
/
RewriteRule ^index.(.*)?$
http://domain.com/subfolder/
[r=301]
This will redirect any attempt to
access a file named index.something to
your subfolder, whether the file
exists or not.
Or try this:
RewriteCond %{HTTP_HOST}
!^www.sample.com$ [NC]
RewriteRule ^(.*)$
%{HTTP_HOST}/samlse/$1 [R=301,L]
I haven't done much redirect in the .htaccess file, so I'm not sure if this will work.
How do you write multiline strings in Go?
Go and multiline strings
Using back ticks you can have multiline strings:
package main
import "fmt"
func main() {
message := `This is a
Multi-line Text String
Because it uses the raw-string back ticks
instead of quotes.
`
fmt.Printf("%s", message)
}
Instead of using either the double quote (“) or single quote symbols (‘), instead use back-ticks to define the start and end of the string. You can then wrap it across lines.
If you indent the string though, remember that the white space will
count.
Please check the playground and do experiments with it.
Difference between string object and string literal
The following are some comparisons:
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");
System.out.println(s1 == s2); //true
System.out.println(s1.equals(s2)); //true
System.out.println(s1 == s3); //false
System.out.println(s1.equals(s3)); //true
s3 = s3.intern();
System.out.println(s1 == s3); //true
System.out.println(s1.equals(s3)); //true
When intern()
is called the reference is changed.
Android: TextView: Remove spacing and padding on top and bottom
Since my requirement is override the existing textView get from findViewById(getResources().getIdentifier("xxx", "id", "android"));
, so I can't simply try onDraw()
of other answer.
But I just figure out the correct steps to fixed my problem, here is the final result from Layout Inspector:
Since what I wanted is merely remove the top spaces, so I don't have to choose other font to remove bottom spaces.
Here is the critical code to fixed it:
Typeface mfont = Typeface.createFromAsset(getResources().getAssets(), "fonts/myCustomFont.otf");
myTextView.setTypeface(mfont);
myTextView.setPadding(0, 0, 0, 0);
myTextView.setIncludeFontPadding(false);
The first key is set custom font "fonts/myCustomFont.otf" which has the space on bottom but not on the top, you can easily figure out this by open otf file and click any font in android Studio:
As you can see, the cursor on the bottom has extra spacing but not on the top, so it fixed my problem.
The second key is you can't simply skip any of the code, otherwise it might not works. That's the reason you can found some people comment that an answer is working and some other people comment that it's not working.
Let's illustrated what will happen if I remove one of them.
Without setTypeface(mfont);
:
Without setPadding(0, 0, 0, 0);
:
Without setIncludeFontPadding(false);
:
Without 3 of them (i.e. the original):
new Date() is working in Chrome but not Firefox
Simple Solution, This works with All Browsers,
var StringDate = "24-11-2017"
var DateVar = StringDate.split("-");
var DateVal = new Date(DateVar[1] + "/" + DateVar[0] + "/" + DateVar[2]);
alert(DateVal);
Get all LI elements in array
If you want all the li tags in an array even when they are in different ul tags then you can simply do
var lis = document.getElementByTagName('li');
and if you want to get particular div tag li's then:
var lis = document.getElementById('divID').getElementByTagName('li');
else if you want to search a ul first and then its li tags then you can do:
var uls = document.getElementsByTagName('ul');
for(var i=0;i<uls.length;i++){
var lis=uls[i].getElementsByTagName('li');
for(var j=0;j<lis.length;j++){
console.log(lis[j].innerHTML);
}
}
MySQL join with where clause
Try this
SELECT *
FROM categories
LEFT JOIN user_category_subscriptions
ON user_category_subscriptions.category_id = categories.category_id
WHERE user_category_subscriptions.user_id = 1
or user_category_subscriptions.user_id is null
bash assign default value
You can also use :=
construct to assign and decide on action in one step. Consider following example:
# Example of setting default server and reporting it's status
server=$1
if [[ ${server:=localhost} =~ [a-z] ]] # 'localhost' assigned here to $server
then echo "server is localhost" # echo is triggered since letters were found in $server
else
echo "server was set" # numbers were passed
fi
If $1
is not empty, localhost
will be assigned to server
in the if
condition field, trigger match and report match result. In this way you can assign on the fly and trigger appropriate action.
Merge two Excel tables Based on matching data in Columns
Put the table in the second image on Sheet2, columns D to F.
In Sheet1, cell D2 use the formula
=iferror(vlookup($A2,Sheet2!$D$1:$F$100,column(A1),false),"")
copy across and down.
Edit: here is a picture. The data is in two sheets. On Sheet1, enter the formula into cell D2. Then copy the formula across to F2 and then down as many rows as you need.
When to use pthread_exit() and when to use pthread_join() in Linux?
You don't need any calls to pthread_exit(3)
in your particular code.
In general, the main
thread should not call pthread_exit
, but should often call pthread_join(3)
to wait for some other thread to finish.
In your PrintHello
function, you don't need to call pthread_exit
because it is implicit after returning from it.
So your code should rather be:
void *PrintHello(void *threadid) {
long tid = (long)threadid;
printf("Hello World! It's me, thread #%ld!\n", tid);
return threadid;
}
int main (int argc, char *argv[]) {
pthread_t threads[NUM_THREADS];
int rc;
intptr_t t;
// create all the threads
for(t=0; t<NUM_THREADS; t++){
printf("In main: creating thread %ld\n", (long) t);
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
if (rc) { fprintf(stderr, "failed to create thread #%ld - %s\n",
(long)t, strerror(rc));
exit(EXIT_FAILURE);
};
}
pthread_yield(); // useful to give other threads more chance to run
// join all the threads
for(t=0; t<NUM_THREADS; t++){
printf("In main: joining thread #%ld\n", (long) t);
rc = pthread_join(&threads[t], NULL);
if (rc) { fprintf(stderr, "failed to join thread #%ld - %s\n",
(long)t, strerror(rc));
exit(EXIT_FAILURE);
}
}
}
Find unique rows in numpy.array
As of NumPy 1.13, one can simply choose the axis for selection of unique values in any N-dim array. To get unique rows, one can do:
unique_rows = np.unique(original_array, axis=0)
Interop type cannot be embedded
In most cases, this error is the result of code which tries to instantiate a COM object. For example, here is a piece of code starting up Excel:
Excel.ApplicationClass xlapp = new Excel.ApplicationClass();
Typically, in .NET 4 you just need to remove the 'Class' suffix and compile the code:
Excel.Application xlapp = new Excel.Application();
An MSDN explanation is here.
Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM
Sometimes in order to write less code it is used to have SQL server set fields like date, time and ID on insert by setting the default value for fields to GETDATE()
or NEWID()
.
In such cases Auto Generated Value property of those fields in entity classes should be set to true.
This way you do not need to set values in code (preventing energy consumption!!!) and never see that exception.
How to create a GUID in Excel?
for me it is correct, in Excel spanish
=CONCATENAR(
DEC.A.HEX(ALEATORIO.ENTRE(0,4294967295),8),"-",
DEC.A.HEX(ALEATORIO.ENTRE(0,65535),4),"-",
DEC.A.HEX(ALEATORIO.ENTRE(16384,20479),4),"-",
DEC.A.HEX(ALEATORIO.ENTRE(32768,49151),4),"-",
DEC.A.HEX(ALEATORIO.ENTRE(0,65535),4),
DEC.A.HEX(ALEATORIO.ENTRE(0,4294967295),8)
)
What does "if (rs.next())" mean?
The next()
moves the cursor froward one row from its current position in the resultset
. so its evident that if(rs.next())
means that if the next row is not null
(means if it exist), Go Ahead.
Now w.r.t your problem,
ResultSet rs = stmt.executeQuery(sql); //This is wrong
^
note that executeQuery(String) is used in case you use a sql-query as string.
Whereas when you use a PreparedStatement, use executeQuery() which executes the SQL query in this PreparedStatement
object and returns the ResultSet
object generated by the query.
Solution :
Use : ResultSet rs = stmt.executeQuery();
Before and After Suite execution hook in jUnit 4.x
Using annotations, you can do something like this:
import org.junit.*;
import static org.junit.Assert.*;
import java.util.*;
class SomethingUnitTest {
@BeforeClass
public static void runBeforeClass()
{
}
@AfterClass
public static void runAfterClass()
{
}
@Before
public void setUp()
{
}
@After
public void tearDown()
{
}
@Test
public void testSomethingOrOther()
{
}
}
Playing a MP3 file in a WinForm application
1) The most simple way would be using WMPLib
WMPLib.WindowsMediaPlayer Player;
private void PlayFile(String url)
{
Player = new WMPLib.WindowsMediaPlayer();
Player.PlayStateChange += Player_PlayStateChange;
Player.URL = url;
Player.controls.play();
}
private void Player_PlayStateChange(int NewState)
{
if ((WMPLib.WMPPlayState)NewState == WMPLib.WMPPlayState.wmppsStopped)
{
//Actions on stop
}
}
2) Alternatively you can use the open source library NAudio. It can play mp3 files using different methods and actually offers much more than just playing a file.
This is as simple as
using NAudio;
using NAudio.Wave;
IWavePlayer waveOutDevice = new WaveOut();
AudioFileReader audioFileReader = new AudioFileReader("Hadouken! - Ugly.mp3");
waveOutDevice.Init(audioFileReader);
waveOutDevice.Play();
Don't forget to dispose after the stop
waveOutDevice.Stop();
audioFileReader.Dispose();
waveOutDevice.Dispose();
Linq on DataTable: select specific column into datatable, not whole table
Try Access DataTable easiest way which can help you for getting perfect idea for accessing DataTable, DataSet using Linq...
Consider following example, suppose we have DataTable like below.
DataTable ObjDt = new DataTable("List");
ObjDt.Columns.Add("WorkName", typeof(string));
ObjDt.Columns.Add("Price", typeof(decimal));
ObjDt.Columns.Add("Area", typeof(string));
ObjDt.Columns.Add("Quantity",typeof(int));
ObjDt.Columns.Add("Breath",typeof(decimal));
ObjDt.Columns.Add("Length",typeof(decimal));
Here above is the code for DatTable, here we assume that there are some data are available in this DataTable, and we have to bind Grid view of particular by processing some data as shown below.
Area | Quantity | Breath | Length | Price = Quantity * breath *Length
Than we have to fire following query which will give us exact result as we want.
var data = ObjDt.AsEnumerable().Select
(r => new
{
Area = r.Field<string>("Area"),
Que = r.Field<int>("Quantity"),
Breath = r.Field<decimal>("Breath"),
Length = r.Field<decimal>("Length"),
totLen = r.Field<int>("Quantity") * (r.Field<decimal>("Breath") * r.Field<decimal>("Length"))
}).ToList();
We just have to assign this data variable as Data Source.
By using this simple Linq query we can get all our accepts, and also we can perform all other LINQ queries with this…
How to perform a fade animation on Activity transition?
you can also use this code in your style.xml file so you don't need to write anything else in your activity.java
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:windowAnimationStyle">@style/AppTheme.WindowTransition</item>
</style>
<!-- Setting window animation -->
<style name="AppTheme.WindowTransition">
<item name="android:windowEnterAnimation">@android:anim/fade_in</item>
<item name="android:windowExitAnimation">@android:anim/fade_out</item>
</style>
jQuery check if it is clicked or not
This is the one that i've tried & it works pretty well for me
$('.mybutton').on('click', function() {
if (!$(this).data('clicked')) {
//do your stuff here if the button is not clicked
$(this).data('clicked', true);
} else {
//do your stuff here if the button is clicked
$(this).data('clicked', false);
}
});
for more reference check this link
JQuery toggle click
PHP - auto refreshing page
This works with Firefox Quantum 60+ and Chrome v72 (2019)
//set a header to instruct the browser to call the page every 30 sec
header("Refresh: 30;");
It does not seem to be NECESSARY to pass the page url as well as the refresh period in order to (re)call the same page. I haven't tried this with Safari/Opera or IE/Edge.
Selecting element by data attribute with jQuery
Using $('[data-whatever="myvalue"]')
will select anything with html attributes, but in newer jQueries it seems that if you use $(...).data(...)
to attach data, it uses some magic browser thingy and does not affect the html, therefore is not discovered by .find
as indicated in the previous answer.
Verify (tested with 1.7.2+) (also see fiddle): (updated to be more complete)
var $container = $('<div><div id="item1"/><div id="item2"/></div>');
// add html attribute
var $item1 = $('#item1').attr('data-generated', true);
// add as data
var $item2 = $('#item2').data('generated', true);
// create item, add data attribute via jquery
var $item3 = $('<div />', {id: 'item3', data: { generated: 'true' }, text: 'Item 3' });
$container.append($item3);
// create item, "manually" add data attribute
var $item4 = $('<div id="item4" data-generated="true">Item 4</div>');
$container.append($item4);
// only returns $item1 and $item4
var $result = $container.find('[data-generated="true"]');
JavaScript string encryption and decryption?
Simple functions,
function Encrypt(value)
{
var result="";
for(i=0;i<value.length;i++)
{
if(i<value.length-1)
{
result+=value.charCodeAt(i)+10;
result+="-";
}
else
{
result+=value.charCodeAt(i)+10;
}
}
return result;
}
function Decrypt(value)
{
var result="";
var array = value.split("-");
for(i=0;i<array.length;i++)
{
result+=String.fromCharCode(array[i]-10);
}
return result;
}
Make file echo displaying "$PATH" string
In the manual for GNU make, they talk about this specific example when describing the value
function:
The value function provides a way for you to use the value of a
variable without having it expanded. Please note that this does not
undo expansions which have already occurred; for example if you create
a simply expanded variable its value is expanded during the
definition; in that case the value function will return the same
result as using the variable directly.
The syntax of the value function is:
$(value variable)
Note that variable is the name of a variable; not a reference to that variable. Therefore you would not normally use
a ‘$’ or parentheses when writing it. (You can, however, use a
variable reference in the name if you want the name not to be a
constant.)
The result of this function is a string containing the value of
variable, without any expansion occurring. For example, in this
makefile:
FOO = $PATH
all:
@echo $(FOO)
@echo $(value FOO)
The first output line would be ATH, since the “$P” would be expanded as a make variable, while the second
output line would be the current value of your $PATH environment
variable, since the value function avoided the expansion.
How to add title to subplots in Matplotlib?
ax.set_title()
should set the titles for separate subplots:
import matplotlib.pyplot as plt
if __name__ == "__main__":
data = [1, 2, 3, 4, 5]
fig = plt.figure()
fig.suptitle("Title for whole figure", fontsize=16)
ax = plt.subplot("211")
ax.set_title("Title for first plot")
ax.plot(data)
ax = plt.subplot("212")
ax.set_title("Title for second plot")
ax.plot(data)
plt.show()
Can you check if this code works for you? Maybe something overwrites them later?
Location of Django logs and errors
Add to your settings.py
:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': 'debug.log',
},
},
'loggers': {
'django': {
'handlers': ['file'],
'level': 'DEBUG',
'propagate': True,
},
},
}
And it will create a file called debug.log
in the root of your.
https://docs.djangoproject.com/en/1.10/topics/logging/
What does the "@" symbol do in Powershell?
PowerShell will actually treat any comma-separated list as an array:
"server1","server2"
So the @ is optional in those cases. However, for associative arrays, the @ is required:
@{"Key"="Value";"Key2"="Value2"}
Officially, @ is the "array operator." You can read more about it in the documentation that installed along with PowerShell, or in a book like "Windows PowerShell: TFM," which I co-authored.
How to turn IDENTITY_INSERT on and off using SQL Server 2008?
Via SQL as per MSDN
SET IDENTITY_INSERT sometableWithIdentity ON
INSERT INTO sometableWithIdentity
(IdentityColumn, col2, col3, ...)
VALUES
(AnIdentityValue, col2value, col3value, ...)
SET IDENTITY_INSERT sometableWithIdentity OFF
The complete error message tells you exactly what is wrong...
Cannot insert explicit value for identity column in table 'sometableWithIdentity' when IDENTITY_INSERT is set to OFF.
How to send data in request body with a GET when using jQuery $.ajax()
Just in case somebody ist still coming along this question:
There is a body query object in any request. You do not need to parse it yourself.
E.g. if you want to send an accessToken from a client with GET, you could do it like this:
_x000D_
_x000D_
const request = require('superagent');_x000D_
_x000D_
request.get(`http://localhost:3000/download?accessToken=${accessToken}`).end((err, res) => {_x000D_
if (err) throw new Error(err);_x000D_
console.log(res);_x000D_
});
_x000D_
_x000D_
_x000D_
The server request object then looks like {request: { ... query: { accessToken: abcfed } ... } }
How to center an iframe horizontally?
HTML:
<div id="all">
<div class="sub">div</div>
<iframe>ss</iframe>
</div>
CSS:
#all{
width:100%;
float:left;
text-align:center;
}
div.sub, iframe {
width: 100px;
height: 50px;
margin: 0 auto;
background-color: #777;
}
Why is there no Char.Empty like String.Empty?
Doesn't answer your first question - but for the specific problem you had, you can just use strings instead of chars, right?:
myString.Replace("c", "")
There a reason you wouldn't want to do that?
How do I set up IntelliJ IDEA for Android applications?
I've spent a day on trying to put all the pieces together, been in hundreds of sites and tutorials, but they all skip trivial steps.
So here's the full guide:
- Download and install Java JDK (Choose the Java platform)
- Download and install Android SDK (Installer is recommended)
- After android SD finishes installing, open SDK Manager under Android SDK Tools (sometimes needs to be opened under admin's privileges)
- Choose everything and mark Accept All and install.
- Download and install IntelliJ IDEA (The community edition is free)
- Wait for all downloads and installations and stuff to finish.
New Project:
- Run IntelliJ
- Create a new project (there's a tutorial here)
- Enter the name, choose Android type.
- There's a step missing in the tutorial, when you are asked to choose the JDK (before choosing the SDK) you need to choose the Java JDK you've installed earlier. Should be under
C:\Program Files\Java\jdk{version}
- Choose a New platform ( if there's not one selected ) , the SDK platform is the android platform at
C:\Program Files\Android\android-sdk-windows
.
- Choose the android version.
- Now you can write your program.
Compiling:
- Near the Run button you need to select the drop-down-list, choose Edit Configurations
- In the Prefer Android Virtual device select the ... button
- Click on create, give it a name, press OK.
- Double click the new device to choose it.
- Press OK.
- You're ready to run the program.
Image resolution for new iPhone 6 and 6+, @3x support added?
I have tested by making a sample project and all simulators seem to use @3x images , this is confusing.
Create different versions of an image in your asset catalog such that the image itself tells you what version it is:
Now run the app on each simulator in turn. You will see that the 3x image is used only on the iPhone 6 Plus.
The same thing is true if the images are drawn from the app bundle using their names (e.g. one.png, [email protected], and [email protected]) by calling imageNamed:
and assigning into an image view.
(However, there's a difference if you assign the image to an image view in Interface Builder - the 2x version is ignored on double-resolution devices. This is presumably a bug, apparently a bug in pathForResource:ofType:
.)
How can I perform an inspect element in Chrome on my Galaxy S3 Android device?
Update: 8-20-2015
Please note the instructions have changed since this question was asked 2 yrs ago.
So on Newer versions of Android and Chrome for Android. You need to use this.
https://developers.google.com/web/tools/setup/remote-debugging/remote-debugging?hl=en
Original Answer:
I have the S3 and it works fine. I have found that a common mistake is not enabling USB Debugging in Chrome mobile. Not only do you have to enable USB debugging on the device itself under developer options but you have to go to the Chrome Browser on your phone and enable it in the settings there too.
Try this with the SDK
- Chrome for Mobile - Settings > Developer Tools > [x] Enable USB Web debugging
- Device - Settings > Developer options > [x] USB debugging
- Connect Device to Computer
Enable port forwarding on your computer by doing the following command below
C:\adb forward tcp:9222 localabstract:chrome_devtools_remote
Go to http://localhost:9222
in Chrome on your Computer
TroubleShooting:
If you get command not found
when trying to run ADB
, make sure Platform-Tools is in your path or just use the whole path to your SDK and run it
C:\path-to-SDK\platform-tools\adb forward tcp:9222 localabstract:chrome_devtools_remote
If you get "device not found
", then run adb kill-server
and then try again.
Error: Cannot find module html
Install ejs if it is not.
npm install ejs
Then after just paste below two lines in your main file. (like app.js, main.js)
app.set('view engine', 'html');
app.engine('html', require('ejs').renderFile);
Combination of async function + await + setTimeout
Since Node 7.6, you can combine the functions promisify
function from the utils module with setTimeout()
.
Node.js
const sleep = require('util').promisify(setTimeout)
Javascript
const sleep = m => new Promise(r => setTimeout(r, m))
Usage
(async () => {
console.time("Slept for")
await sleep(3000)
console.timeEnd("Slept for")
})()
How to search for a string in text files?
If user wants to search for the word in given text file.
fopen = open('logfile.txt',mode='r+')
fread = fopen.readlines()
x = input("Enter the search string: ")
for line in fread:
if x in line:
print(line)
shell script to remove a file if it already exist
A one liner shell script to remove a file if it already exist (based on Jindra Helcl's answer):
[ -f file ] && rm file
or with a variable:
#!/bin/bash
file="/path/to/file.ext"
[ -f $file ] && rm $file
How to split a string between letters and digits (or between digits and letters)?
Didn't use Java for ages, so just some pseudo code, that should help get you started (faster for me than looking up everything :) ).
string a = "123abc345def";
string[] result;
while(a.Length > 0)
{
string part;
if((part = a.Match(/\d+/)).Length) // match digits
;
else if((part = a.Match(/\a+/)).Length) // match letters
;
else
break; // something invalid - neither digit nor letter
result.append(part);
a = a.SubStr(part.Length - 1); // remove the part we've found
}
How to handle change text of span
You could use the function that changes the text of span1 to change the text of the others.
As a work around, if you really want it to have a change
event, then don't asign text to span 1. Instead asign an input variable in jQuery, write a change event to it, and whever ur changing the text of span1 .. instead change the value of your input variable, thus firing change event, like so:
var spanChange = $("<input />");
function someFuncToCalculateAndSetTextForSpan1() {
// do work
spanChange.val($newText).change();
};
$(function() {
spanChange.change(function(e) {
var $val = $(this).val(),
$newVal = some*calc-$val;
$("#span1").text($val);
$("#spanWhatever").text($newVal);
});
});
Though I really feel this "work-around", while useful in some aspects of creating a simple change event, is very overextended, and you'd best be making the changes to other spans at the same time you change span1.
Insert line break in wrapped cell via code
Yes. The VBA equivalent of AltEnter is to use a linebreak character:
ActiveCell.Value = "I am a " & Chr(10) & "test"
Note that this automatically sets WrapText
to True.
Proof:
Sub test()
Dim c As Range
Set c = ActiveCell
c.WrapText = False
MsgBox "Activcell WrapText is " & c.WrapText
c.Value = "I am a " & Chr(10) & "test"
MsgBox "Activcell WrapText is " & c.WrapText
End Sub
Plotting dates on the x-axis with Python's matplotlib
I have too low reputation to add comment to @bernie response, with response to @user1506145. I have run in to same issue.
The answer to it is a interval parameter which fixes things up
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import datetime as dt
np.random.seed(1)
N = 100
y = np.random.rand(N)
now = dt.datetime.now()
then = now + dt.timedelta(days=100)
days = mdates.drange(now,then,dt.timedelta(days=1))
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=5))
plt.plot(days,y)
plt.gcf().autofmt_xdate()
plt.show()
How to print the current Stack Trace in .NET without any exception?
private void ExceptionTest()
{
try
{
int j = 0;
int i = 5;
i = 1 / j;
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
var stList = ex.StackTrace.ToString().Split('\\');
Console.WriteLine("Exception occurred at " + stList[stList.Count() - 1]);
}
}
Seems to work for me
want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format
Here's a simple snippet working in Java 8 and using the "new" date and time API LocalDateTime:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss.SS");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now));
Invalidating JSON Web Tokens
The following approach could give best of both worlds solution:
Let "immediate" mean "~1 minute".
Cases:
User attempts a successful login:
A. Add an "issue time" field to the token, and keep the expiry time as needed.
B. Store the hash of user's password's hash
or create a new field say tokenhash in the user's table.
Store the tokenhash in the generated token.
User accesses a url:
A. If the "issue time" is in the "immediate" range, process the token normally. Don't change the "issue time". Depending upon the duration of "immediate" this is the duration
one is vulnerable in. But a short duration like a minute or two shouldn't be
too risky. (This is a balance between performance and security). Three is no need to hit the db here.
B. If the token is not in the "immediate" range, check the tokenhash against the db. If its okay, update the "issue time" field. If not okay then don't process the request (Security is finally enforced).
User changes the tokenhash to secure the account. In the "immediate" future the account is secured.
We save the database lookups in the "immediate" range.
This is most beneficial if there are a bursts of requests from the client in the "immediate" time duration.
JavaScript before leaving the page
Most of the solutions here did not work for me so I used the one found here
I also added a variable to allow the confirm box or not
window.hideWarning = false;
window.addEventListener('beforeunload', (event) => {
if (!hideWarning) {
event.preventDefault();
event.returnValue = '';
}
});
php error: Class 'Imagick' not found
Docker container installation for php:XXX
Debian based images:
RUN apt-get update && apt-get install -y --no-install-recommends libmagickwand-dev
RUN pecl install imagick && docker-php-ext-enable imagick
RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* || true
Get current value when change select option - Angular2
In angular 4, this worked for me
template.html
<select (change)="filterChanged($event.target.value)">
<option *ngFor="let type of filterTypes" [value]="type.value">{{type.display}}
</option>
</select>
component.ts
export class FilterComponent implements OnInit {
selectedFilter:string;
public filterTypes = [
{ value: 'percentage', display: 'percentage' },
{ value: 'amount', display: 'amount' }
];
constructor() {
this.selectedFilter = 'percentage';
}
filterChanged(selectedValue:string){
console.log('value is ', selectedValue);
}
ngOnInit() {
}
}
How do I run a class in a WAR from the command line?
the best way if you use Spring Boot is :
1/ Create a ServletInitializer extends SpringBootServletInitializer Class
. With method configure which run your Application Class
2/ Generate always a maven install WAR file
3/ With this artefact you can even :
. start application from war file with java -jar file.war
. put your war file in your favorite Web App server (like tomcat, ...)
Convert ascii char[] to hexadecimal char[] in C
void atoh(char *ascii_ptr, char *hex_ptr,int len)
{
int i;
for(i = 0; i < (len / 2); i++)
{
*(hex_ptr+i) = (*(ascii_ptr+(2*i)) <= '9') ? ((*(ascii_ptr+(2*i)) - '0') * 16 ) : (((*(ascii_ptr+(2*i)) - 'A') + 10) << 4);
*(hex_ptr+i) |= (*(ascii_ptr+(2*i)+1) <= '9') ? (*(ascii_ptr+(2*i)+1) - '0') : (*(ascii_ptr+(2*i)+1) - 'A' + 10);
}
}
Why is 1/1/1970 the "epoch time"?
Early versions of unix measured system time in 1/60 s intervals. This meant that a 32-bit unsigned integer could only represent a span of time less than 829 days. For this reason, the time represented by the number 0
(called the epoch) had to be set in the very recent past. As this was in the early 1970s, the epoch was set to 1971-1-1.
Later, the system time was changed to increment every second, which increased the span of time that could be represented by a 32-bit unsigned integer to around 136 years. As it was no longer so important to squeeze every second out of the counter, the epoch was rounded down to the nearest decade, thus becoming 1970-1-1. One must assume that this was considered a bit neater than 1971-1-1.
Note that a 32-bit signed integer using 1970-1-1 as its epoch can represent dates up to 2038-1-19, on which date it will wrap around to 1901-12-13.
How to escape indicator characters (i.e. : or - ) in YAML
I came here trying to get my Azure DevOps Command Line task working. The thing that worked for me was using the pipe (|
) character. Using >
did not work.
Example:
steps:
- task: CmdLine@2
inputs:
script: |
echo "Selecting Mono version..."
/bin/bash -c "sudo $AGENT_HOMEDIRECTORY/scripts/select-xamarin-sdk.sh 5_18_1"
echo "Selecting Xcode version..."
/bin/bash -c "echo '##vso[task.setvariable variable=MD_APPLE_SDK_ROOT;]'/Applications/Xcode_10.2.1.app;sudo xcode-select --switch /Applications/Xcode_10.2.1.app/Contents/Developer"
Adobe Acrobat Pro make all pages the same dimension
You have to use the Print to a New PDF option using the PDF printer. Once in the dialog box, set the page scaling to 100% and set your page size. Once you do that, your new PDF will be uniform in page sizes.
How do I see the commit differences between branches in git?
If you want to compare based on the commit messages, you can do the following:
git fetch
git log --oneline origin/master | cut -d' ' -f2- > master_log
git log --oneline origin/branch-X | cut -d' ' -f2- > branchx_log
diff <(sort master_log) <(sort branchx_log)
tar: Error is not recoverable: exiting now
Try to get your archive using wget
, I had the same issue when I was downloading archive through browser. Than I just copy archive link and in terminal use the command:
wget http://PATH_TO_ARCHIVE
jQuery click anywhere in the page except on 1 div
You can apply click
on body
of document and cancel click
processing if the click
event is generated by div with id menu_content
, This will bind event to single element and saving binding of click
with every element except menu_content
$('body').click(function(evt){
if(evt.target.id == "menu_content")
return;
//For descendants of menu_content being clicked, remove this check if you do not want to put constraint on descendants.
if($(evt.target).closest('#menu_content').length)
return;
//Do processing of click event here for every element except with id menu_content
});
How can I get the concatenation of two lists in Python without modifying either one?
The simplest method is just to use the +
operator, which returns the concatenation of the lists:
concat = first_list + second_list
One disadvantage of this method is that twice the memory is now being used . For very large lists, depending on how you're going to use it once it's created, itertools.chain
might be your best bet:
>>> import itertools
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = itertools.chain(a, b)
This creates a generator for the items in the combined list, which has the advantage that no new list needs to be created, but you can still use c
as though it were the concatenation of the two lists:
>>> for i in c:
... print i
1
2
3
4
5
6
If your lists are large and efficiency is a concern then this and other methods from the itertools
module are very handy to know.
Note that this example uses up the items in c
, so you'd need to reinitialise it before you can reuse it. Of course you can just use list(c)
to create the full list, but that will create a new list in memory.
Why dividing two integers doesn't get a float?
Chapter and verse
6.5.5 Multiplicative operators
...
6 When integers are divided, the result of the /
operator is the algebraic quotient with any
fractional part discarded.105) If the quotient a/b
is representable, the expression
(a/b)*b + a%b
shall equal a
; otherwise, the behavior of both a/b
and a%b
is
unde?ned.
105) This is often called ‘‘truncation toward zero’’.
Dividing an integer by an integer gives an integer result. 1/2 yields 0; assigning this result to a floating-point variable gives 0.0. To get a floating-point result, at least one of the operands must be a floating-point type. b = a / 350.0f;
should give you the result you want.
Difference between DOMContentLoaded and load events
DOMContentLoaded
==window.onDomReady()
Load
==window.onLoad()
A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $(document).ready()
will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $(window).load(function() { ... })
will run once the entire page (images or iframes), not just the DOM, is ready.
See: Using JQuery Core's document-ready documentation.
Java method to swap primitives
AFAIS, no one mentions of atomic reference.
Integer
public void swap(AtomicInteger a, AtomicInteger b){
a.set(b.getAndSet(a.get()));
}
String
public void swap(AtomicReference<String> a, AtomicReference<String> b){
a.set(b.getAndSet(a.get()));
}
Copy a variable's value into another
I do not understand why the answers are so complex. In Javascript, primitives (strings, numbers, etc) are passed by value, and copied. Objects, including arrays, are passed by reference. In any case, assignment of a new value or object reference to 'a' will not change 'b'. But changing the contents of 'a' will change the contents of 'b'.
var a = 'a'; var b = a; a = 'c'; // b === 'a'
var a = {a:'a'}; var b = a; a = {c:'c'}; // b === {a:'a'} and a = {c:'c'}
var a = {a:'a'}; var b = a; a.a = 'c'; // b.a === 'c' and a.a === 'c'
Paste any of the above lines (one at a time) into node or any browser javascript console. Then type any variable and the console will show it's value.
Sending the bearer token with axios
If you want to some data after passing token in header so that try this code
const api = 'your api';
const token = JSON.parse(sessionStorage.getItem('data'));
const token = user.data.id; /*take only token and save in token variable*/
axios.get(api , { headers: {"Authorization" : `Bearer ${token}`} })
.then(res => {
console.log(res.data);
.catch((error) => {
console.log(error)
});
Spring JDBC Template for calling Stored Procedures
There are a number of ways to call stored procedures in Spring.
If you use CallableStatementCreator
to declare parameters, you will be using Java's standard interface of CallableStatement
, i.e register out parameters and set them separately. Using SqlParameter
abstraction will make your code cleaner.
I recommend you looking at SimpleJdbcCall
. It may be used like this:
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(package)
.withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);
For simple procedures you may use jdbcTemplate
's update
method:
jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);
Can I run CUDA on Intel's integrated graphics processor?
Intel HD Graphics is usually the on-CPU graphics chip in newer Core i3/i5/i7 processors.
As far as I know it doesn't support CUDA (which is a proprietary NVidia technology), but OpenCL is supported by NVidia, ATi and Intel.
How to change shape color dynamically?
Maybe someone else need to change color in the XML without create multiple drawables like I needed. Then make a circle drawable without color and then specify backgroundTint for the ImageView.
circle.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
</shape>
And in your layout:
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:background="@drawable/circle"
android:backgroundTint="@color/red"/>
Edit:
There is a bug regarding this method that prevents it from working on Android Lollipop 5.0 (API level 21). But have been fixed in newer versions.
Convert hex to binary
no=raw_input("Enter your number in hexa decimal :")
def convert(a):
if a=="0":
c="0000"
elif a=="1":
c="0001"
elif a=="2":
c="0010"
elif a=="3":
c="0011"
elif a=="4":
c="0100"
elif a=="5":
c="0101"
elif a=="6":
c="0110"
elif a=="7":
c="0111"
elif a=="8":
c="1000"
elif a=="9":
c="1001"
elif a=="A":
c="1010"
elif a=="B":
c="1011"
elif a=="C":
c="1100"
elif a=="D":
c="1101"
elif a=="E":
c="1110"
elif a=="F":
c="1111"
else:
c="invalid"
return c
a=len(no)
b=0
l=""
while b<a:
l=l+convert(no[b])
b+=1
print l
#include errors detected in vscode
The error message "Please update your includePath" does not necessarily mean there is actually a problem with the includePath
. The problem may be that VSCode is using the wrong compiler or wrong IntelliSense mode. I have written instructions in this answer on how to troubleshoot and align your VSCode C++ configuration with your compiler and project.
Is Django for the frontend or backend?
(a) Django is a framework, not a language
(b) I'm not sure what you're missing - there is no reason why you can't have business logic in a web application. In Django, you would normally expect presentation logic to be separated from business logic. Just because it is hosted in the same application server, it doesn't follow that the two layers are entangled.
(c) Django does provide templating, but it doesn't provide rich libraries for generating client-side content.
How do the post increment (i++) and pre increment (++i) operators work in Java?
++a
increments a
before it is evaluated.
a++
evaluates a
and then increments it.
Related to your expression given:
i = ((++a) + (++a) + (a++)) == ((6) + (7) + (7)); // a is 8 at the end
i = ((a++) + (++a) + (++a)) == ((5) + (7) + (8)); // a is 8 at the end
The parenteses I used above are implicitly used by Java. If you look at the terms this way you can easily see, that they are both the same as they are commutative.
Get the current file name in gulp.src()
For my case gulp-ignore was perfect.
As option you may pass a function there:
function condition(file) {
// do whatever with file.path
// return boolean true if needed to exclude file
}
And the task would look like this:
var gulpIgnore = require('gulp-ignore');
gulp.task('task', function() {
gulp.src('./**/*.js')
.pipe(gulpIgnore.exclude(condition))
.pipe(gulp.dest('./dist/'));
});
When and where to use GetType() or typeof()?
typeof
is an operator to obtain a type known at compile-time (or at least a generic type parameter). The operand of typeof
is always the name of a type or type parameter - never an expression with a value (e.g. a variable). See the C# language specification for more details.
GetType()
is a method you call on individual objects, to get the execution-time type of the object.
Note that unless you only want exactly instances of TextBox
(rather than instances of subclasses) you'd usually use:
if (myControl is TextBox)
{
// Whatever
}
Or
TextBox tb = myControl as TextBox;
if (tb != null)
{
// Use tb
}
How to add a default "Select" option to this ASP.NET DropDownList control?
The reason it is not working is because you are adding an item to the list and then overriding the whole list with a new DataSource
which will clear and re-populate your list, losing the first manually added item.
So, you need to do this in reverse like this:
Status status = new Status();
DropDownList1.DataSource = status.getData();
DropDownList1.DataValueField = "ID";
DropDownList1.DataTextField = "Description";
DropDownList1.DataBind();
// Then add your first item
DropDownList1.Items.Insert(0, "Select");
How to break out of a loop from inside a switch?
AFAIK there is no "double break" or similar construct in C++. The closest would be a goto
- which, while it has a bad connotation to its name, exists in the language for a reason - as long as it's used carefully and sparingly, it's a viable option.
frequent issues arising in android view, Error parsing XML: unbound prefix
As you mention, you need to specify the right namespace. You also see this error with an incorrect namespace.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip">
will not work.
Change:
xmlns="http://schemas.android.com/apk/res/android"
to
xmlns:android="http://schemas.android.com/apk/res/android"
The error message is referring to everything that starts "android:" as the XML does not know what the "android:
" namespace is.
xmlns:android
defines it.
Landscape printing from HTML
Quoted from CSS-Discuss Wiki
The @page rule has been cut down in
scope from CSS2 to CSS2.1. The full
CSS2 @page rule was reportedly
implemented only in Opera (and buggily
even then). My own testing shows that
IE and Firefox don't support @page at
all. According to the now-obsolescent
CSS2 spec section 13.2.2 it is
possible to override the user's
setting of orientation and (for
example) force printing in Landscape
but the relevant "size" property has
been dropped from CSS2.1, consistent
with the fact that no current browser
supports it. It has been reinstated in
the CSS3 Paged Media module but note
that this is only a Working Draft (as
at July 2009).
Conclusion: forget
about @page for the present. If you
feel your document needs to be printed
in Landscape orientation, ask yourself
if you can instead make your design
more fluid. If you really can't
(perhaps because the document contains
data tables with many columns, for
example), you will need to advise the
user to set the orientation to
Landscape and perhaps outline how to
do it in the most common browsers. Of
course, some browsers have a print
fit-to-width (shrink-to-fit) feature
(e.g. Opera, Firefox, IE7) but it's
inadvisable to rely on users having
this facility or having it switched
on.
Does static constexpr variable inside a function make sense?
In addition to given answer, it's worth noting that compiler is not required to initialize constexpr
variable at compile time, knowing that the difference between constexpr
and static constexpr
is that to use static constexpr
you ensure the variable is initialized only once.
Following code demonstrates how constexpr
variable is initialized multiple times (with same value though), while static constexpr
is surely initialized only once.
In addition the code compares the advantage of constexpr
against const
in combination with static
.
#include <iostream>
#include <string>
#include <cassert>
#include <sstream>
const short const_short = 0;
constexpr short constexpr_short = 0;
// print only last 3 address value numbers
const short addr_offset = 3;
// This function will print name, value and address for given parameter
void print_properties(std::string ref_name, const short* param, short offset)
{
// determine initial size of strings
std::string title = "value \\ address of ";
const size_t ref_size = ref_name.size();
const size_t title_size = title.size();
assert(title_size > ref_size);
// create title (resize)
title.append(ref_name);
title.append(" is ");
title.append(title_size - ref_size, ' ');
// extract last 'offset' values from address
std::stringstream addr;
addr << param;
const std::string addr_str = addr.str();
const size_t addr_size = addr_str.size();
assert(addr_size - offset > 0);
// print title / ref value / address at offset
std::cout << title << *param << " " << addr_str.substr(addr_size - offset) << std::endl;
}
// here we test initialization of const variable (runtime)
void const_value(const short counter)
{
static short temp = const_short;
const short const_var = ++temp;
print_properties("const", &const_var, addr_offset);
if (counter)
const_value(counter - 1);
}
// here we test initialization of static variable (runtime)
void static_value(const short counter)
{
static short temp = const_short;
static short static_var = ++temp;
print_properties("static", &static_var, addr_offset);
if (counter)
static_value(counter - 1);
}
// here we test initialization of static const variable (runtime)
void static_const_value(const short counter)
{
static short temp = const_short;
static const short static_var = ++temp;
print_properties("static const", &static_var, addr_offset);
if (counter)
static_const_value(counter - 1);
}
// here we test initialization of constexpr variable (compile time)
void constexpr_value(const short counter)
{
constexpr short constexpr_var = constexpr_short;
print_properties("constexpr", &constexpr_var, addr_offset);
if (counter)
constexpr_value(counter - 1);
}
// here we test initialization of static constexpr variable (compile time)
void static_constexpr_value(const short counter)
{
static constexpr short static_constexpr_var = constexpr_short;
print_properties("static constexpr", &static_constexpr_var, addr_offset);
if (counter)
static_constexpr_value(counter - 1);
}
// final test call this method from main()
void test_static_const()
{
constexpr short counter = 2;
const_value(counter);
std::cout << std::endl;
static_value(counter);
std::cout << std::endl;
static_const_value(counter);
std::cout << std::endl;
constexpr_value(counter);
std::cout << std::endl;
static_constexpr_value(counter);
std::cout << std::endl;
}
Possible program output:
value \ address of const is 1 564
value \ address of const is 2 3D4
value \ address of const is 3 244
value \ address of static is 1 C58
value \ address of static is 1 C58
value \ address of static is 1 C58
value \ address of static const is 1 C64
value \ address of static const is 1 C64
value \ address of static const is 1 C64
value \ address of constexpr is 0 564
value \ address of constexpr is 0 3D4
value \ address of constexpr is 0 244
value \ address of static constexpr is 0 EA0
value \ address of static constexpr is 0 EA0
value \ address of static constexpr is 0 EA0
As you can see yourself constexpr
is initilized multiple times (address is not the same) while static
keyword ensures that initialization is performed only once.
In SQL, how can you "group by" in ranges?
An alternative approach would involve storing the ranges in a table, instead of embedding them in the query. You would end up with a table, call it Ranges, that looks like this:
LowerLimit UpperLimit Range
0 9 '0-9'
10 19 '10-19'
20 29 '20-29'
30 39 '30-39'
And a query that looks like this:
Select
Range as [Score Range],
Count(*) as [Number of Occurences]
from
Ranges r inner join Scores s on s.Score between r.LowerLimit and r.UpperLimit
group by Range
This does mean setting up a table, but it would be easy to maintain when the desired ranges change. No code changes necessary!
How to customize the background color of a UITableViewCell?
Customizing the background of a table view cell eventually becomes and "all or nothing" approach. It's very difficult to change the color or image used for the background of a content cell in a way that doesn't look strange.
The reason is that the cell actually spans the width of the view. The rounded corners are just part of its drawing style and the content view sits in this area.
If you change the color of the content cell you will end up with white bits visible at the corners. If you change the color of the entire cell, you will have a block of color spanning the width of the view.
You can definitely customize a cell, but it's not quite as easy as you may think at first.
How to insert a string which contains an "&"
I've found that using either of the following options works:
SET DEF OFF
or
SET SCAN OFF
I don't know enough about databases to know if one is better or "more right" than the other. Also, if there's something better than either of these, please let me know.
How to wait for the 'end' of 'resize' event and only then perform an action?
ResizeStart and ResizeEnd events for window
http://jsfiddle.net/04fLy8t4/
I implemented function which trig two events on user DOM element:
- resizestart
- resizeend
Code:
var resizeEventsTrigger = (function () {
function triggerResizeStart($el) {
$el.trigger('resizestart');
isStart = !isStart;
}
function triggerResizeEnd($el) {
clearTimeout(timeoutId);
timeoutId = setTimeout(function () {
$el.trigger('resizeend');
isStart = !isStart;
}, delay);
}
var isStart = true;
var delay = 200;
var timeoutId;
return function ($el) {
isStart ? triggerResizeStart($el) : triggerResizeEnd($el);
};
})();
$("#my").on('resizestart', function () {
console.log('resize start');
});
$("#my").on('resizeend', function () {
console.log('resize end');
});
window.onresize = function () {
resizeEventsTrigger( $("#my") );
};
How do I see if Wi-Fi is connected on Android?
The following code (in Kotlin) works from API 21 until at least current API version (API 29).
The function getWifiState() returns one of 3 possible values for the WiFi network state:
Disable, EnabledNotConnected and Connected that were defined in an enum class.
This allows to take more granular decisions like informing the user to enable WiFi or, if already enabled, to connect to one of the available networks.
But if all that is needed is a boolean indicating if the WiFi interface is connected to a network, then the other function isWifiConnected() will give you that. It uses the previous one and compares the result to Connected.
It's inspired in some of the previous answers but trying to solve the problems introduced by the evolution of Android API's or the slowly increasing availability of IP V6.
The trick was to use:
wifiManager.connectionInfo.bssid != null
instead of:
- getIpAddress() == 0 that is only valid for IP V4 or
- getNetworkId() == -1 that now requires another special permission (Location)
According to the documentation: https://developer.android.com/reference/kotlin/android/net/wifi/WifiInfo.html#getbssid
it will return null if not connected to a network. And even if we do not have permission to get the real value, it will still return something other than null if we are connected.
Also have the following in mind:
On releases before android.os.Build.VERSION_CODES#N, this object
should only be obtained from an Context#getApplicationContext(), and
not from any other derived context to avoid memory leaks within the
calling process.
In the Manifest, do not forget to add:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
Proposed code is:
class MyViewModel(application: Application) : AndroidViewModel(application) {
// Get application context
private val myAppContext: Context = getApplication<Application>().applicationContext
// Define the different possible states for the WiFi Connection
internal enum class WifiState {
Disabled, // WiFi is not enabled
EnabledNotConnected, // WiFi is enabled but we are not connected to any WiFi network
Connected, // Connected to a WiFi network
}
// Get the current state of the WiFi network
private fun getWifiState() : WifiState {
val wifiManager : WifiManager = myAppContext.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
return if (wifiManager.isWifiEnabled) {
if (wifiManager.connectionInfo.bssid != null)
WifiState.Connected
else
WifiState.EnabledNotConnected
} else {
WifiState.Disabled
}
}
// Returns true if we are connected to a WiFi network
private fun isWiFiConnected() : Boolean {
return (getWifiState() == WifiState.Connected)
}
}
Visibility of global variables in imported modules
Since I haven't seen it in the answers above, I thought I would add my simple workaround, which is just to add a global_dict
argument to the function requiring the calling module's globals, and then pass the dict into the function when calling; e.g:
# external_module
def imported_function(global_dict=None):
print(global_dict["a"])
# calling_module
a = 12
from external_module import imported_function
imported_function(global_dict=globals())
>>> 12
Razor view engine - How can I add Partial Views
You partial looks much like an editor template so you could include it as such (assuming of course that your partial is placed in the ~/views/controllername/EditorTemplates
subfolder):
@Html.EditorFor(model => model.SomePropertyOfTypeLocaleBaseModel)
Or if this is not the case simply:
@Html.Partial("nameOfPartial", Model)
How to change Vagrant 'default' machine name?
I specify the name by defining inside the VagrantFile and also specify the hostname so i enjoy seeing the name of my project while executing Linux commands independently from my device's OS. ??
config.vm.define "abc"
config.vm.hostname = "abc"
using facebook sdk in Android studio
Create build.gradle file in facebook sdk project:
apply plugin: 'android-library'
dependencies {
compile 'com.android.support:support-v4:18.0.+'
}
android {
compileSdkVersion 8
buildToolsVersion "19.0.0"
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
// Move the build types to build-types/<type>
// For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
// This moves them out of them default location under src/<type>/... which would
// conflict with src/ being used by the main source set.
// Adding new build types or product flavors should be accompanied
// by a similar customization.
debug.setRoot('build-types/debug')
release.setRoot('build-types/release')
}
}
Then add include ':libs:facebook'
equals <project_directory>/libs/facebook
(path to library) in settings.gradle
.
How do you iterate through every file/directory recursively in standard C++?
You don't. The C++ standard has no concept of directories. It is up to the implementation to turn a string into a file handle. The contents of that string and what it maps to is OS dependent. Keep in mind that C++ can be used to write that OS, so it gets used at a level where asking how to iterate through a directory is not yet defined (because you are writing the directory management code).
Look at your OS API documentation for how to do this. If you need to be portable, you will have to have a bunch of #ifdefs for various OSes.
What data is stored in Ephemeral Storage of Amazon EC2 instance?
Basically, root volume (your entire virtual system disk) is ephemeral, but only if you choose to create AMI backed by Amazon EC2 instance store.
If you choose to create AMI backed by EBS then your root volume is backed by EBS and everything you have on your root volume will be saved between reboots.
If you are not sure what type of volume you have, look under EC2->Elastic Block Store->Volumes in your AWS console and if your AMI root volume is listed there then you are safe. Also, if you go to EC2->Instances and then look under column "Root device type" of your instance and if it says "ebs", then you don't have to worry about data on your root device.
More details here: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/RootDeviceStorage.html
Get escaped URL parameter
Below is what I have created from the comments here, as well as fixing bugs not mentioned (such as actually returning null, and not 'null'):
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
Disable Proximity Sensor during call
I also had problem with proximity sensor (I shattered screen in that region on my Nexus 6, Android Marshmallow) and none of proposed solutions / third party apps worked when I tried to disable proximity sensor. What worked for me was to calibrate the sensor using Proximity Sensor Reset/Repair. You have to follow the instruction in app (cover sensor and uncover it) and then restart your phone. Although my sensor is no longer behind the glass, it still showed slightly different results when covered / uncovered and recalibration did the job.
What I tried and didn't work? Proximity Screen Off Lite, Macrodroid and KinScreen.
What would've I tried had it still not worked?[XPOSED] Sensor Disabler, but it requires you to be rooted and have Xposed Framework, so I'm really glad I've found the easier way.
int object is not iterable?
As ghills had already mentioned
inp = int(input("Enter a number:"))
n = 0
for i in str(inp):
n = n + int(i);
print n
When you are looping through something, keyword is "IN", just always think of it as a list of something. You cannot loop through a plain integer. Therefore, it is not iterable.
Invalid length parameter passed to the LEFT or SUBSTRING function
CHARINDEX
will return 0
if no spaces are in the string and then you look for a substring of -1
length.
You can tack a trailing space on to the end of the string to ensure there is always at least one space and avoid this problem.
SELECT SUBSTRING(PostCode, 1 , CHARINDEX(' ', PostCode + ' ' ) -1)
Difference between core and processor
A core is usually the basic computation unit of the CPU - it can run a single program context (or multiple ones if it supports hardware threads such as hyperthreading on Intel CPUs), maintaining the correct program state, registers, and correct execution order, and performing the operations through ALUs. For optimization purposes, a core can also hold on-core caches with copies of frequently used memory chunks.
A CPU may have one or more cores to perform tasks at a given time. These tasks are usually software processes and threads that the OS schedules. Note that the OS may have many threads to run, but the CPU can only run X such tasks at a given time, where X = number cores * number of hardware threads per core. The rest would have to wait for the OS to schedule them whether by preempting currently running tasks or any other means.
In addition to the one or many cores, the CPU will include some interconnect that connects the cores to the outside world, and usually also a large "last-level" shared cache. There are multiple other key elements required to make a CPU work, but their exact locations may differ according to design. You'll need a memory controller to talk to the memory, I/O controllers (display, PCIe, USB, etc..). In the past these elements were outside the CPU, in the complementary "chipset", but most modern design have integrated them into the CPU.
In addition the CPU may have an integrated GPU, and pretty much everything else the designer wanted to keep close for performance, power and manufacturing considerations. CPU design is mostly trending in to what's called system on chip (SoC).
This is a "classic" design, used by most modern general-purpose devices (client PC, servers, and also tablet and smartphones). You can find more elaborate designs, usually in the academy, where the computations is not done in basic "core-like" units.
Could not find module FindOpenCV.cmake ( Error in configuration process)
I had this exact same problem. I fixed it by adding the following line to my FindOpenCV.cmake
file. Put it anywhere at the top before the rest of the code.
set (OpenCV_DIR /home/cmake/opencv/compiled) #change the path to match your complied directory of opencv
Basically you are telling FindOpenCV.cmake
where to find opencv files assuming the other compilation can find the FindOpenCV.cmake
Close application and launch home screen on Android
Keep in mind that when working with applications that use persistent socket connections, the finish()
method does not release the connection. Under normal circumstances, finish()
is the best option, but if you absolutely need to exit an app and release all resource it's using then use killProcess
. I've had no problems using it.
How to run server written in js with Node.js
Nodejs is a scripting language (like Python or Ruby, and unlike PHP or C++). To run your code, you need to enter a command in the terminal / shell / command prompt. Look for an application shortcut in your operating system by one of those names.
The command to run in the terminal will be
node server.js
But you will first need to browse in the terminal to the same folder as the file server.js
. The syntax for using the terminal varies by operating system, look for its documentation.
How to put a jar in classpath in Eclipse?
Right click on the project in which you want to put jar file. A window will open like this
Click on the AddExternal Jars there you can give the path to that jar file
Wait for a void async method
The best solution is to use async Task
. You should avoid async void
for several reasons, one of which is composability.
If the method cannot be made to return Task
(e.g., it's an event handler), then you can use SemaphoreSlim
to have the method signal when it is about to exit. Consider doing this in a finally
block.
How to add a RequiredFieldValidator to DropDownList control?
For the most part you treat it as if you are validating any other kind of control but use the InitialValue property of the required field validator.
<asp:RequiredFieldValidator ID="rfv1" runat="server" ControlToValidate="your-dropdownlist" InitialValue="Please select" ErrorMessage="Please select something" />
Basically what it's saying is that validation will succeed if any other value than the 1 set in InitialValue is selected in the dropdownlist.
If databinding you will need to insert the "Please select" value afterwards as follows
this.ddl1.Items.Insert(0, "Please select");
Using $state methods with $stateChangeStart toState and fromState in Angular ui-router
Suggestion 1
When you add an object to $stateProvider.state
that object is then passed with the state. So you can add additional properties which you can read later on when needed.
Example route configuration
$stateProvider
.state('public', {
abstract: true,
module: 'public'
})
.state('public.login', {
url: '/login',
module: 'public'
})
.state('tool', {
abstract: true,
module: 'private'
})
.state('tool.suggestions', {
url: '/suggestions',
module: 'private'
});
The $stateChangeStart
event gives you acces to the toState
and fromState
objects. These state objects will contain the configuration properties.
Example check for the custom module property
$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
if (toState.module === 'private' && !$cookies.Session) {
// If logged out and transitioning to a logged in page:
e.preventDefault();
$state.go('public.login');
} else if (toState.module === 'public' && $cookies.Session) {
// If logged in and transitioning to a logged out page:
e.preventDefault();
$state.go('tool.suggestions');
};
});
I didn't change the logic of the cookies because I think that is out of scope for your question.
Suggestion 2
You can create a Helper to get you this to work more modular.
Value publicStates
myApp.value('publicStates', function(){
return {
module: 'public',
routes: [{
name: 'login',
config: {
url: '/login'
}
}]
};
});
Value privateStates
myApp.value('privateStates', function(){
return {
module: 'private',
routes: [{
name: 'suggestions',
config: {
url: '/suggestions'
}
}]
};
});
The Helper
myApp.provider('stateshelperConfig', function () {
this.config = {
// These are the properties we need to set
// $stateProvider: undefined
process: function (stateConfigs){
var module = stateConfigs.module;
$stateProvider = this.$stateProvider;
$stateProvider.state(module, {
abstract: true,
module: module
});
angular.forEach(stateConfigs, function (route){
route.config.module = module;
$stateProvider.state(module + route.name, route.config);
});
}
};
this.$get = function () {
return {
config: this.config
};
};
});
Now you can use the helper to add the state configuration to your state configuration.
myApp.config(['$stateProvider', '$urlRouterProvider',
'stateshelperConfigProvider', 'publicStates', 'privateStates',
function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) {
helper.config.$stateProvider = $stateProvider;
helper.process(publicStates);
helper.process(privateStates);
}]);
This way you can abstract the repeated code, and come up with a more modular solution.
Note: the code above isn't tested
How to get next/previous record in MySQL?
If you want to feed more than one id
to your query and get next_id
for all of them...
Assign cur_id
in your select field and then feed it to subquery getting next_id
inside select field. And then select just next_id
.
Using longneck answer to calc next_id
:
select next_id
from (
select id as cur_id, (select min(id) from `foo` where id>cur_id) as next_id
from `foo`
) as tmp
where next_id is not null;
MySQL INNER JOIN Alias
You'll need to join twice:
SELECT home.*, away.*, g.network, g.date_start
FROM game AS g
INNER JOIN team AS home
ON home.importid = g.home
INNER JOIN team AS away
ON away.importid = g.away
ORDER BY g.date_start DESC
LIMIT 7
PostgreSQL JOIN data from 3 tables
Maybe the following is what you are looking for:
SELECT name, pathfilename
FROM table1
NATURAL JOIN table2
NATURAL JOIN table3
WHERE name = 'John';
How to get image size (height & width) using JavaScript?
You can only really do this using a callback of the load event as the size of the image is not known until it has actually finished loading. Something like the code below...
var imgTesting = new Image();
function CreateDelegate(contextObject, delegateMethod)
{
return function()
{
return delegateMethod.apply(contextObject, arguments);
}
}
function imgTesting_onload()
{
alert(this.width + " by " + this.height);
}
imgTesting.onload = CreateDelegate(imgTesting, imgTesting_onload);
imgTesting.src = 'yourimage.jpg';
How to send FormData objects with Ajax-requests in jQuery?
You can send the FormData object in ajax request using the following code,
$("form#formElement").submit(function(){
var formData = new FormData($(this)[0]);
});
This is very similar to the accepted answer but an actual answer to the question topic. This will submit the form elements automatically in the FormData and you don't need to manually append the data to FormData variable.
The ajax method looks like this,
$("form#formElement").submit(function(){
var formData = new FormData($(this)[0]);
//append some non-form data also
formData.append('other_data',$("#someInputData").val());
$.ajax({
type: "POST",
url: postDataUrl,
data: formData,
processData: false,
contentType: false,
dataType: "json",
success: function(data, textStatus, jqXHR) {
//process data
},
error: function(data, textStatus, jqXHR) {
//process error msg
},
});
You can also manually pass the form element inside the FormData object as a parameter like this
var formElem = $("#formId");
var formdata = new FormData(formElem[0]);
Hope it helps. ;)
Git Pull While Ignoring Local Changes?
For me the following worked:
(1) First fetch all changes:
$ git fetch --all
(2) Then reset the master:
$ git reset --hard origin/master
(3) Pull/update:
$ git pull
How to convert number to words in java
class NumberToWord {
private static Map<Integer, String> numbers = new HashMap<Integer, String>();
private static Set<Integer> numberSet = new TreeSet<Integer>(new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
static {
init();
numberSet.addAll(numbers.keySet());
}
public static void main(String[] args) {
System.out.println(getNumberInWord(1898765));
}
/*
* convert positive numbers in word format number > 0 only
*/
static String getNumberInWord(int number) {
StringBuilder word = new StringBuilder();
for (Integer n : numberSet) {
if (number > 0 && number >= n) {
int div = number / n;
String strNum = numbers.get(div);
if (strNum == null) {
word.append(getNumberInWord(div));
}
// for less than 100, we don't need to say 1
if (strNum != null && (div > 1 || n > 100))
word.append(strNum + " ");
word.append(numbers.get(n) + " ");
number = number % n;
}
}
return word.toString();
}
static void init() {
numbers.put(0, "Zero");
numbers.put(1, "One");
numbers.put(2, "Two");
numbers.put(3, "Three");
numbers.put(4, "Four");
numbers.put(5, "Five");
numbers.put(6, "Six");
numbers.put(7, "Seven");
numbers.put(8, "Eight");
numbers.put(9, "Nine");
numbers.put(10, "Ten");
numbers.put(11, "Eleven");
numbers.put(12, "Twelve");
numbers.put(13, "Thirteen");
numbers.put(14, "Fourteen");
numbers.put(15, "Fifteen");
numbers.put(16, "Sixteen");
numbers.put(17, "Seventeen");
numbers.put(18, "Eighteeen");
numbers.put(19, "Nineteen");
numbers.put(20, "Twenty");
numbers.put(30, "Thirty");
numbers.put(40, "Forty");
numbers.put(50, "Fifty");
numbers.put(60, "Sixty");
numbers.put(70, "Seventy");
numbers.put(80, "Eighty");
numbers.put(90, "Ninty");
numbers.put(100, "Hundred");
numbers.put(1000, "Thousand");
numbers.put(1000000, "Million");
numbers.put(100000000, "Billion");
}
}
Hibernate Error executing DDL via JDBC Statement
I have got this error when trying to create JPA entity with the name "User" (in Postgres) that is reserved.
So the way it is resolved is to change the table name by @Table annotation:
@Entity
@Table(name="users")
public class User {..}
Or change the table name manually.
NSURLConnection Using iOS Swift
An abbreviated version of your code worked for me,
class Remote: NSObject {
var data = NSMutableData()
func connect(query:NSString) {
var url = NSURL.URLWithString("http://www.google.com")
var request = NSURLRequest(URL: url)
var conn = NSURLConnection(request: request, delegate: self, startImmediately: true)
}
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
println("didReceiveResponse")
}
func connection(connection: NSURLConnection!, didReceiveData conData: NSData!) {
self.data.appendData(conData)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
println(self.data)
}
deinit {
println("deiniting")
}
}
This is the code I used in the calling class,
class ViewController: UIViewController {
var remote = Remote()
@IBAction func downloadTest(sender : UIButton) {
remote.connect("/apis")
}
}
You didn't specify in your question where you had this code,
var remote = Remote()
remote.connect("/apis")
If var is a local variable, then the Remote class will be deallocated right after the connect(query:NSString) method finishes, but before the data returns. As you can see by my code, I usually implement reinit (or dealloc up to now) just to make sure when my instances go away. You should add that to your Remote class to see if that's your problem.
Consistency of hashCode() on a Java string
The hashcode will be calculated based on the ASCII values of the characters in the String.
This is the implementation in the String Class is as follows
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
hash = h = isLatin1() ? StringLatin1.hashCode(value)
: StringUTF16.hashCode(value);
}
return h;
}
Collisions in hashcode are unavoidable. For example, the strings "Ea" and "FB" give the same hashcode as 2236
Javascript | Set all values of an array
map
is the most logical solution for this problem.
let xs = [1, 2, 3];
xs = xs.map(x => 42);
xs // -> [42, 42, 42]
However, if there is a chance that the array is sparse, you'll need to use for
or, even better, for .. of
.
See:
Load json from local file with http.get() in angular 2
I found that the simplest way to achieve this is by adding the file.json under folder: assets.
No need to edit: .angular-cli.json
Service
@Injectable()
export class DataService {
getJsonData(): Promise<any[]>{
return this.http.get<any[]>('http://localhost:4200/assets/data.json').toPromise();
}
}
Component
private data: any[];
constructor(private dataService: DataService) {}
ngOnInit() {
data = [];
this.dataService.getJsonData()
.then( result => {
console.log('ALL Data: ', result);
data = result;
})
.catch( error => {
console.log('Error Getting Data: ', error);
});
}
Extra:
Ideally, you only want to have this in a dev environment so to be bulletproof. create a variable on your environment.ts
export const environment = {
production: false,
baseAPIUrl: 'http://localhost:4200/assets/data.json'
};
Then replace the URL on the http.get for ${environment.baseAPIUrl}
And the environment.prod.ts
can have the production API URL.
Hope this helps!
What is the meaning of the word logits in TensorFlow?
Just adding this clarification so that anyone who scrolls down this much can at least gets it right, since there are so many wrong answers upvoted.
Diansheng's answer and JakeJ's answer get it right.
A new answer posted by Shital Shah is an even better and more complete answer.
Yes, logit
as a mathematical function in statistics, but the logit
used in context of neural networks is different. Statistical logit
doesn't even make any sense here.
I couldn't find a formal definition anywhere, but logit
basically means:
The raw predictions which come out of the last layer of the neural network.
1. This is the very tensor on which you apply the argmax
function to get the predicted class.
2. This is the very tensor which you feed into the softmax
function to get the probabilities for the predicted classes.
Also, from a tutorial on official tensorflow website:
Logits Layer
The final layer in our neural network is the logits layer, which will return the raw values for our predictions. We create a dense layer with 10 neurons (one for each target class 0–9), with linear activation (the default):
logits = tf.layers.dense(inputs=dropout, units=10)
If you are still confused, the situation is like this:
raw_predictions = neural_net(input_layer)
predicted_class_index_by_raw = argmax(raw_predictions)
probabilities = softmax(raw_predictions)
predicted_class_index_by_prob = argmax(probabilities)
where, predicted_class_index_by_raw
and predicted_class_index_by_prob
will be equal.
Another name for raw_predictions
in the above code is logit
.
As for the why logit
... I have no idea. Sorry.
[Edit: See this answer for the historical motivations behind the term.]
Trivia
Although, if you want to, you can apply statistical logit
to probabilities
that come out of the softmax
function.
If the probability of a certain class is p
,
Then the log-odds of that class is L = logit(p)
.
Also, the probability of that class can be recovered as p = sigmoid(L)
, using the sigmoid
function.
Not very useful to calculate log-odds though.
MySQL trigger if condition exists
Try to do...
DELIMITER $$
CREATE TRIGGER aumentarsalario
BEFORE INSERT
ON empregados
FOR EACH ROW
BEGIN
if (NEW.SALARIO < 900) THEN
set NEW.SALARIO = NEW.SALARIO + (NEW.SALARIO * 0.1);
END IF;
END $$
DELIMITER ;
How to compute precision, recall, accuracy and f1-score for the multiclass case with scikit learn?
First of all it's a little bit harder using just counting analysis to tell if your data is unbalanced or not. For example: 1 in 1000 positive observation is just a noise, error or a breakthrough in science? You never know.
So it's always better to use all your available knowledge and choice its status with all wise.
Okay, what if it's really unbalanced?
Once again — look to your data. Sometimes you can find one or two observation multiplied by hundred times. Sometimes it's useful to create this fake one-class-observations.
If all the data is clean next step is to use class weights in prediction model.
So what about multiclass metrics?
In my experience none of your metrics is usually used. There are two main reasons.
First: it's always better to work with probabilities than with solid prediction (because how else could you separate models with 0.9 and 0.6 prediction if they both give you the same class?)
And second: it's much easier to compare your prediction models and build new ones depending on only one good metric.
From my experience I could recommend logloss or MSE (or just mean squared error).
How to fix sklearn warnings?
Just simply (as yangjie noticed) overwrite average
parameter with one of these
values: 'micro'
(calculate metrics globally), 'macro'
(calculate metrics for each label) or 'weighted'
(same as macro but with auto weights).
f1_score(y_test, prediction, average='weighted')
All your Warnings came after calling metrics functions with default average
value 'binary'
which is inappropriate for multiclass prediction.
Good luck and have fun with machine learning!
Edit:
I found another answerer recommendation to switch to regression approaches (e.g. SVR) with which I cannot agree. As far as I remember there is no even such a thing as multiclass regression. Yes there is multilabel regression which is far different and yes it's possible in some cases switch between regression and classification (if classes somehow sorted) but it pretty rare.
What I would recommend (in scope of scikit-learn) is to try another very powerful classification tools: gradient boosting, random forest (my favorite), KNeighbors and many more.
After that you can calculate arithmetic or geometric mean between predictions and most of the time you'll get even better result.
final_prediction = (KNNprediction * RFprediction) ** 0.5
numpy: most efficient frequency counts for unique values in an array
As of Numpy 1.9, the easiest and fastest method is to simply use numpy.unique
, which now has a return_counts
keyword argument:
import numpy as np
x = np.array([1,1,1,2,2,2,5,25,1,1])
unique, counts = np.unique(x, return_counts=True)
print np.asarray((unique, counts)).T
Which gives:
[[ 1 5]
[ 2 3]
[ 5 1]
[25 1]]
A quick comparison with scipy.stats.itemfreq
:
In [4]: x = np.random.random_integers(0,100,1e6)
In [5]: %timeit unique, counts = np.unique(x, return_counts=True)
10 loops, best of 3: 31.5 ms per loop
In [6]: %timeit scipy.stats.itemfreq(x)
10 loops, best of 3: 170 ms per loop
What is a JavaBean exactly?
POJO (plain old Java object): POJOs are ordinary Java objects, with no restriction other than those forced by the Java Language.
Serialization: It is used to save state of an object and send it across a network. It converts the state of an object into a byte stream. We can recreate a Java object from the byte stream by process called deserialization.
Make your class implement java.io.Serializable interface. And use writeObject() method of ObjectOutputStream class to achive Serialization.
JavaBean class: It is a special POJO which have some restriction (or convention).
- Implement serialization
- Have public no-arg constructor
- All properties private with public getters & setter methods.
Many frameworks - like Spring - use JavaBean objects.
Ignoring upper case and lower case in Java
You have to use the String method .toLowerCase()
or .toUpperCase()
on both the input and the string you are trying to match it with.
Example:
public static void findPatient() {
System.out.print("Enter part of the patient name: ");
String name = sc.nextLine();
System.out.print(myPatientList.showPatients(name));
}
//the other class
ArrayList<String> patientList;
public void showPatients(String name) {
boolean match = false;
for(String matchingname : patientList) {
if (matchingname.toLowerCase().contains(name.toLowerCase())) {
match = true;
}
}
}
Create list of single item repeated N times
As others have pointed out, using the * operator for a mutable object duplicates references, so if you change one you change them all. If you want to create independent instances of a mutable object, your xrange syntax is the most Pythonic way to do this. If you are bothered by having a named variable that is never used, you can use the anonymous underscore variable.
[e for _ in xrange(n)]
Python set to list
Try using combination of map and lambda functions:
aList = map( lambda x: x, set ([1, 2, 6, 9, 0]) )
It is very convenient approach if you have a set of numbers in string and you want to convert it to list of integers:
aList = map( lambda x: int(x), set (['1', '2', '3', '7', '12']) )
Select rows where column is null
for some reasons IS NULL may not work with some column data type
i was in need to get all the employees that their English full name is missing ,I've used :
**SELECT emp_id ,Full_Name_Ar,Full_Name_En from employees where Full_Name_En = ' ' or Full_Name_En is null **
How do I redirect a user when a button is clicked?
Just as an addition to the other answers, here is the razor engine syntax:
<input type="button" value="Some text" onclick="@("window.location.href='" + @Url.Action("actionName", "controllerName") + "'");" />
or
window.location.href = '@Url.Action("actionName", "controllerName")';
How can I get input radio elements to horizontally align?
This also works like a charm
_x000D_
_x000D_
<form>_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="optradio" checked>Option 1_x000D_
</label>_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="optradio">Option 2_x000D_
</label>_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="optradio">Option 3_x000D_
</label>_x000D_
</form>
_x000D_
_x000D_
_x000D_
How to detect orientation change?
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(OrientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
}
-(void)OrientationDidChange:(NSNotification*)notification {
UIDeviceOrientation Orientation=[[UIDevice currentDevice]orientation];
if(Orientation==UIDeviceOrientationLandscapeLeft || Orientation==UIDeviceOrientationLandscapeRight) {
NSLog(@"Landscape");
} else if(Orientation==UIDeviceOrientationPortrait) {
NSLog(@"Potrait Mode");
}
}
NOTE: Just use this code to identify UIViewController is in which orientation
How to use glyphicons in bootstrap 3.0
If you're using less , and it's not loading the icons font you must check out the font path
go to the file variable.less and change the @icon-font-path path , that worked for me.
Whitespaces in java
Why don't you check if text.trim() has a different length? :
if(text.length() == text.trim().length() || otherConditions){
//your code
}
Evaluate if list is empty JSTL
There's also the function tags, a bit more flexible:
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<c:if test="${fn:length(list) > 0}">
And here's the tag documentation.
WPF loading spinner
With Images
Visual summary of options for spinning icons. Recorded using Screen To Gif.
Font-Awesome-WPF
Documentation on GitHub.
Install via NuGet:
PM> Install-Package FontAwesome.WPF
Looks like this:
XAML:
<fa:ImageAwesome Icon="Spinner" Spin="True" SpinDuration="4" />
Icons pictured are Spinner
, CircleOutlineNotch
, Refresh
and Cog
. There are many others.
XAML copy/paste.
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
To avoid an array index out-of-bounds exception, one should use the enhanced-for
statement where and when they can.
The primary motivation (and use case) is when you are iterating and you do not require any complicated iteration steps. You would not be able to use an enhanced-for
to move backwards in an array or only iterate on every other element.
You're guaranteed not to run out of elements to iterate over when doing this, and your [corrected] example is easily converted over.
The code below:
String[] name = {"tom", "dick", "harry"};
for(int i = 0; i< name.length; i++) {
System.out.print(name[i] + "\n");
}
...is equivalent to this:
String[] name = {"tom", "dick", "harry"};
for(String firstName : name) {
System.out.println(firstName + "\n");
}
Returning JSON object as response in Spring Boot
You can either return a response as String
as suggested by @vagaasen or you can use ResponseEntity
Object provided by Spring as below. By this way you can also return Http status code
which is more helpful in webservice call.
@RestController
@RequestMapping("/api")
public class MyRestController
{
@GetMapping(path = "/hello", produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> sayHello()
{
//Get data from service layer into entityList.
List<JSONObject> entities = new ArrayList<JSONObject>();
for (Entity n : entityList) {
JSONObject entity = new JSONObject();
entity.put("aa", "bb");
entities.add(entity);
}
return new ResponseEntity<Object>(entities, HttpStatus.OK);
}
}
Get content of a cell given the row and column numbers
You don't need the CELL() part of your formulas:
=INDIRECT(ADDRESS(B1,B2))
or
=OFFSET($A$1, B1-1,B2-1)
will both work. Note that both INDIRECT
and OFFSET
are volatile functions. Volatile functions can slow down calculation because they are calculated at every single recalculation.
How do I convert a double into a string in C++?
Heh, I just wrote this (unrelated to this question):
string temp = "";
stringstream outStream;
double ratio = (currentImage->width*1.0f)/currentImage->height;
outStream << " R: " << ratio;
temp = outStream.str();
/* rest of the code */
How to call Android contacts list?
To my surprise you do not need users-permission CONTACT_READ to read the names and some basic information (Is the contact starred, what was the last calling time).
However you do need permission to read the details of the contact like phone number.
endforeach in loops?
It's the end statement for the alternative syntax:
foreach ($foo as $bar) :
...
endforeach;
Useful to make code more readable if you're breaking out of PHP:
<?php foreach ($foo as $bar) : ?>
<div ...>
...
</div>
<?php endforeach; ?>
What is the 'open' keyword in Swift?
open come to play when dealing with multiple modules.
open class is accessible and subclassable outside of the defining module. An open class member is accessible and overridable outside of the defining module.
How to make Twitter bootstrap modal full screen
For bootstrap 4 I have to add media query with max-width: none
@media (min-width: 576px) {
.modal-dialog { max-width: none; }
}
.modal-dialog {
width: 98%;
height: 92%;
padding: 0;
}
.modal-content {
height: 99%;
}
How do I split a string with multiple separators in JavaScript?
Not the best way but works to Split with Multiple and Different seperators/delimiters
html
<button onclick="myFunction()">Split with Multiple and Different seperators/delimiters</button>
<p id="demo"></p>
javascript
<script>
function myFunction() {
var str = "How : are | you doing : today?";
var res = str.split(' | ');
var str2 = '';
var i;
for (i = 0; i < res.length; i++) {
str2 += res[i];
if (i != res.length-1) {
str2 += ",";
}
}
var res2 = str2.split(' : ');
//you can add countless options (with or without space)
document.getElementById("demo").innerHTML = res2;
</script>
How to reverse a 'rails generate'
Before reverting the rails generate
, please make sure you rollback the migration first.
Case 1: if you want to revert scaffold then run this command:
rails destroy scaffold MODEL_NAME
Case 2: if you want to revert model then run this command:
rails destroy model MODEL_NAME
Case 3: if you want to revert controller then run this command:
rails destroy controller CONTROLLER_NAME
Note: you can also use shortcut d
instead of destroy
.
SQL Server 2008 Row Insert and Update timestamps
As an alternative to using a trigger, you might like to consider creating a stored procedure to handle the INSERT
s that takes most of the columns as arguments and gets the CURRENT_TIMESTAMP
which it includes in the final INSERT
to the database. You could do the same for the CREATE
. You may also be able to set things up so that users cannot execute INSERT
and CREATE
statements other than via the stored procedures.
I have to admit that I haven't actually done this myself so I'm not at all sure of the details.
Kotlin Ternary Conditional Operator
There is no ternary operator in Kotlin, the most closed are the below two cases,
- If else as expression statement
val a = true if(a) print("A is true") else print("A is false")
If the expression to the left of ?: is not null, the elvis operator
returns it, otherwise it returns the expression to the right. Note
that the right-hand side expression is evaluated only if the left-hand
side is null.
val name = node.getName() ?: throw IllegalArgumentException("name expected")
Reference docs
Android Calling JavaScript functions in WebView
Modification of @Ilya_Gazman answer
private void callJavaScript(WebView view, String methodName, Object...params){
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("javascript:try{");
stringBuilder.append(methodName);
stringBuilder.append("(");
String separator = "";
for (Object param : params) {
stringBuilder.append(separator);
separator = ",";
if(param instanceof String){
stringBuilder.append("'");
}
stringBuilder.append(param.toString().replace("'", "\\'"));
if(param instanceof String){
stringBuilder.append("'");
}
}
stringBuilder.append(")}catch(error){console.error(error.message);}");
final String call = stringBuilder.toString();
Log.i(TAG, "callJavaScript: call="+call);
view.loadUrl(call);
}
will correctly create JS calls e.g.
callJavaScript(mBrowser, "alert", "abc", "def");
//javascript:try{alert('abc','def')}catch(error){console.error(error.message);}
callJavaScript(mBrowser, "alert", 1, true, "abc");
//javascript:try{alert(1,true,'abc')}catch(error){console.error(error.message);}
Note that objects will not be passed correctly - but you can serialize them before passing as an argument.
Also I've changed where the error goes, I've diverted it to the console log which can be listened by:
webView.setWebChromeClient(new CustomWebChromeClient());
and client
class CustomWebChromeClient extends WebChromeClient {
private static final String TAG = "CustomWebChromeClient";
@Override
public boolean onConsoleMessage(ConsoleMessage cm) {
Log.d(TAG, String.format("%s @ %d: %s", cm.message(),
cm.lineNumber(), cm.sourceId()));
return true;
}
}
Retrieving a property of a JSON object by index?
Objects in JavaScript are collections of unordered properties. Objects are hashtables.
If you want your properties to be in alphabetical order, one possible solution would be to create an index for your properties in a separate array. Just a few hours ago, I answered a question on Stack Overflow which you may want to check out:
Here's a quick adaptation for your object1:
var obj = {
"set1": [1, 2, 3],
"set2": [4, 5, 6, 7, 8],
"set3": [9, 10, 11, 12]
};
var index = [];
// build the index
for (var x in obj) {
index.push(x);
}
// sort the index
index.sort(function (a, b) {
return a == b ? 0 : (a > b ? 1 : -1);
});
Then you would be able to do the following:
console.log(obj[index[1]]);
The answer I cited earlier proposes a reusable solution to iterate over such an object. That is unless you can change your JSON to as @Jacob Relkin suggested in the other answer, which could be easier.
1 You may want to use the hasOwnProperty()
method to ensure that the properties belong to your object and are not inherited from Object.prototype
.
Writing file to web server - ASP.NET
protected void TestSubmit_ServerClick(object sender, EventArgs e)
{
using (StreamWriter _testData = new StreamWriter(Server.MapPath("~/data.txt"), true))
{
_testData.WriteLine(TextBox1.Text); // Write the file.
}
}
Server.MapPath takes a virtual path and returns an absolute one. "~" is used to resolve to the application root.
$(document).ready not Working
I had copy pasted my inline js
from some other .php
project, inside that block of code there was some php
code outputting some value, now since the variable wasn't defined in my new file, it was producing the typical php
undefined warning/error
, and because of that the js
code was being messed up, and wasn't responding to any event, even alert("xyz");
would fail silently!! Although the erronous line was way near the end of the file, still the js
would just die that too,
without any errors!!! >:(
Now one thing confusing is that debugger console/output gave no hint/error/warning whatsoever, the js
was dying silently.
So try checking if you have php
inline coded with the js
, and see if it is outputting any error. Once removed/sorted your js
should work fine.
remove legend title in ggplot
Another option using labs
and setting colour to NULL
.
ggplot(df, aes(x, y, colour = g)) +
geom_line(stat = "identity") +
theme(legend.position = "bottom") +
labs(colour = NULL)
How to merge a Series and DataFrame
If I could suggest setting up your dataframes like this (auto-indexing):
df = pd.DataFrame({'a':[np.nan, 1, 2], 'b':[4, 5, 6]})
then you can set up your s1 and s2 values thus (using shape() to return the number of rows from df):
s = pd.DataFrame({'s1':[5]*df.shape[0], 's2':[6]*df.shape[0]})
then the result you want is easy:
display (df.merge(s, left_index=True, right_index=True))
Alternatively, just add the new values to your dataframe df:
df = pd.DataFrame({'a':[nan, 1, 2], 'b':[4, 5, 6]})
df['s1']=5
df['s2']=6
display(df)
Both return:
a b s1 s2
0 NaN 4 5 6
1 1.0 5 5 6
2 2.0 6 5 6
If you have another list of data (instead of just a single value to apply), and you know it is in the same sequence as df, eg:
s1=['a','b','c']
then you can attach this in the same way:
df['s1']=s1
returns:
a b s1
0 NaN 4 a
1 1.0 5 b
2 2.0 6 c
Input type=password, don't let browser remember the password
Here's the best answer, and the easiest! Put an extra password field in front of your input
field and set the display:none
, so that when the browser fills it in, it does it in an input
that you don't care about.
Change this:
<input type="password" name="password" size="25" class="input" id="password" value="">
to this:
<input type="password" style="display:none;">
<input type="password" name="password" size="25" class="input" id="password" value="">