macro - open all files in a folder
You can use Len(StrFile) > 0
in loop check statement !
Sub openMyfile()
Dim Source As String
Dim StrFile As String
'do not forget last backslash in source directory.
Source = "E:\Planning\03\"
StrFile = Dir(Source)
Do While Len(StrFile) > 0
Workbooks.Open Filename:=Source & StrFile
StrFile = Dir()
Loop
End Sub
Using Google Translate in C#
I found this code works for me:
public String Translate(String word)
{
var toLanguage = "en";//English
var fromLanguage = "de";//Deutsch
var url = $"https://translate.googleapis.com/translate_a/single?client=gtx&sl={fromLanguage}&tl={toLanguage}&dt=t&q={HttpUtility.UrlEncode(word)}";
var webClient = new WebClient
{
Encoding = System.Text.Encoding.UTF8
};
var result = webClient.DownloadString(url);
try
{
result = result.Substring(4, result.IndexOf("\"", 4, StringComparison.Ordinal) - 4);
return result;
}
catch
{
return "Error";
}
}
How to cat <<EOF >> a file containing code?
I know this is a two year old question, but this is a quick answer for those searching for a 'how to'.
If you don't want to have to put quotes around anything you can simply write a block of text to a file, and escape variables you want to export as text (for instance for use in a script) and not escape one's you want to export as the value of the variable.
#!/bin/bash
FILE_NAME="test.txt"
VAR_EXAMPLE="\"string\""
cat > ${FILE_NAME} << EOF
\${VAR_EXAMPLE}=${VAR_EXAMPLE} in ${FILE_NAME}
EOF
Will write "${VAR_EXAMPLE}="string" in test.txt" into test.txt
This can also be used to output blocks of text to the console with the same rules by omitting the file name
#!/bin/bash
VAR_EXAMPLE="\"string\""
cat << EOF
\${VAR_EXAMPLE}=${VAR_EXAMPLE} to console
EOF
Will output "${VAR_EXAMPLE}="string" to console" to the console
Changing Shell Text Color (Windows)
This is extremely simple! Rather than importing odd modules for python or trying long commands you can take advantage of windows OS commands.
In windows, commands exist to change the command prompt text color. You can use this in python by starting with a: import os
Next you need to have a line changing the text color, place it were you want in your code.
os.system('color 4')
You can figure out the other colors by starting cmd.exe and typing color help.
The good part? Thats all their is to it, to simple lines of code.
-Day
Throw away local commits in Git
If you just want to throw away local commits and keep the modifications done in files then do
git reset @~
Other answers addressed the hard reset
From Arraylist to Array
There are two styles to convert a collection to an array: either using a pre-sized array (like c.toArray(new String[c.size()])
) or using an empty array (like c.toArray(new String[0])
).
In older Java versions using pre-sized array was recommended, as the reflection call which is necessary to create an array of proper size was quite slow. However since late updates of OpenJDK 6 this call was intrinsified, making the performance of the empty array version the same and sometimes even better, compared to the pre-sized version. Also passing pre-sized array is dangerous for a concurrent or synchronized collection as a data race is possible between the size and toArray call which may result in extra nulls at the end of the array, if the collection was concurrently shrunk during the operation.
You can follow the uniform style: either using an empty array (which is recommended in modern Java) or using a pre-sized array (which might be faster in older Java versions or non-HotSpot based JVMs).
How to access ssis package variables inside script component
I had the same problem as the OP except I remembered to declare the ReadOnlyVariables.
After some playing around, I discovered it was the name of my variable that was the issue. "File_Path" in SSIS somehow got converted to "FilePath". C# does not play nicely with underscores in variable names.
So to access the variable, I type
string fp = Variables.FilePath;
In the PreExecute() method of the Script Component.
How to find an object in an ArrayList by property
You can't without an iteration.
Option 1
Carnet findCarnet(String codeIsIn) {
for(Carnet carnet : listCarnet) {
if(carnet.getCodeIsIn().equals(codeIsIn)) {
return carnet;
}
}
return null;
}
Option 2
Override the equals()
method of Carnet
.
Option 3
Storing your List
as a Map
instead, using codeIsIn
as the key:
HashMap<String, Carnet> carnets = new HashMap<>();
// setting map
Carnet carnet = carnets.get(codeIsIn);
How to run cron job every 2 hours
Just do:
0 */2 * * * /home/username/test.sh
The 0 at the beginning means to run at the 0th minute. (If it were an *, the script would run every minute during every second hour.)
Don't forget, you can check syslog to see if it ever actually ran!
How to check if String value is Boolean type in Java?
Something you should also take into consideration is character casing...
Instead of:
return value.equals("false") || value.equals("true");
Do this:
return value.equalsIgnoreCase("false") || value.equalsIgnoreCase("true");
how to get text from textview
I haven't tested this - but it should give you a general idea of the direction you need to take.
For this to work, I'm going to assume a few things about the text of the TextView
:
- The
TextView
consists of lines delimited with "\n"
.
- The first line will not include an operator (+, -, * or /).
- After the first line there can be a variable number of lines in the
TextView
which will all include one operator and one number.
- An operator will allways be the first
Char
of a line.
First we get the text:
String input = tv1.getText().toString();
Then we split it up for each line:
String[] lines = input.split( "\n" );
Now we need to calculate the total value:
int total = Integer.parseInt( lines[0].trim() ); //We know this is a number.
for( int i = 1; i < lines.length(); i++ ) {
total = calculate( lines[i].trim(), total );
}
The method calculate should look like this, assuming that we know the first Char
of a line is the operator:
private int calculate( String input, int total ) {
switch( input.charAt( 0 ) )
case '+':
return total + Integer.parseInt( input.substring( 1, input.length() );
case '-':
return total - Integer.parseInt( input.substring( 1, input.length() );
case '*':
return total * Integer.parseInt( input.substring( 1, input.length() );
case '/':
return total / Integer.parseInt( input.substring( 1, input.length() );
}
EDIT
So the above as stated in the comment below does "left-to-right" calculation, ignoring the normal order ( + and / before + and -).
The following does the calculation the right way:
String input = tv1.getText().toString();
input = input.replace( "\n", "" );
input = input.replace( " ", "" );
int total = getValue( input );
The method getValue
is a recursive method and it should look like this:
private int getValue( String line ) {
int value = 0;
if( line.contains( "+" ) ) {
String[] lines = line.split( "\\+" );
value += getValue( lines[0] );
for( int i = 1; i < lines.length; i++ )
value += getValue( lines[i] );
return value;
}
if( line.contains( "-" ) ) {
String[] lines = line.split( "\\-" );
value += getValue( lines[0] );
for( int i = 1; i < lines.length; i++ )
value -= getValue( lines[i] );
return value;
}
if( line.contains( "*" ) ) {
String[] lines = line.split( "\\*" );
value += getValue( lines[0] );
for( int i = 1; i < lines.length; i++ )
value *= getValue( lines[i] );
return value;
}
if( line.contains( "/" ) ) {
String[] lines = line.split( "\\/" );
value += getValue( lines[0] );
for( int i = 1; i < lines.length; i++ )
value /= getValue( lines[i] );
return value;
}
return Integer.parseInt( line );
}
Special cases that the recursive method does not handle:
- If the first number is negative e.g. -3+5*8.
- Double operators e.g. 3*-6 or 5/-4.
Also the fact the we're using Integers
might give some "odd" results in some cases as e.g. 5/3 = 1.
Run batch file as a Windows service
As Doug Currie says use RunAsService.
From my past experience you must remember that the Service you generate will
- have a completely different set of environment variables
- have to be carefully inspected for rights/permissions issues
- might cause havoc if it opens dialogs asking for any kind of input
not sure if the last one still applies ... it was one big night mare in a project I worked on some time ago.
Difference between x86, x32, and x64 architectures?
As the 64bit version is an x86
architecture and was accordingly first called x86-64
, that would be the most appropriate name, IMO. Also, x32
is a thing (as mentioned before)—‘x64’, however, is not a continuation of that, so is (theoretically) missleading (even though many people will know what you are talking about) and should thus only be recognised as a marketing thing, not an ‘official’ architecture (again, IMO–obviously, others disagree).
printf formatting (%d versus %u)
If I understand your question correctly, you need %p
to show the address that a pointer is using, for example:
int main() {
int a = 5;
int *p = &a;
printf("%d, %u, %p", p, p, p);
return 0;
}
will output something like:
-1083791044, 3211176252, 0xbf66a93c
#define in Java
Most readable solution is using Static Import. Then you will not need to use AnotherClass.constant
.
Write a class with the constant as public static
field.
package ConstantPackage;
public class Constant {
public static int PROTEINS = 1;
}
Then just use Static Import where you need the constant.
import static ConstantPackage.Constant.PROTEINS;
public class StaticImportDemo {
public static void main(String[]args) {
int[] myArray = new int[5];
myArray[PROTEINS] = 0;
}
}
To know more about Static Import please see this stack overflow question.
Can a JSON value contain a multiline string
As I could understand the question is not about how pass a string with control symbols using json
but how to store and restore json in file where you can split a string with editor control symbols.
If you want to store multiline string in a file then your file will not store the valid json
object. But if you use your json
files in your program only, then you can store the data as you wanted and remove all newlines from file manually each time you load it to your program and then pass to json parser.
Or, alternatively, which would be better, you can have your json
data source files where you edit a sting as you want and then remove all new lines with some utility to the valid json
file which your program will use.
Adding a right click menu to an item
This is a comprehensive answer to this question. I have done this because this page is high on the Google search results and the answer does not go into enough detail. This post assumes that you are competent at using Visual Studio C# forms. This is based on VS2012.
Start by simply dragging a ContextMenuStrip onto the form. It will just put it into the top left corner where you can add your menu items and rename it as you see fit.
You will have to view code and enter in an event yourself on the form. Create a mouse down event for the item in question and then assign a right click event for it like so (I have called the ContextMenuStrip "rightClickMenuStrip"):
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
switch (e.Button)
{
case MouseButtons.Right:
{
rightClickMenuStrip.Show(this, new Point(e.X, e.Y));//places the menu at the pointer position
}
break;
}
}
Assign the event handler manually to the form.designer (you may need to add a "using" for System.Windows.Forms; You can just resolve it):
this.pictureBox1.MouseDown += new MouseEventHandler(this.pictureBox1_MouseDown);
All that is needed at this point is to simply double click each menu item and do the desired operations for each click event in the same way you would for any other button.
This is the basic code for this operation. You can obviously modify it to fit in with your coding practices.
Why maven? What are the benefits?
Maven can be considered as complete project development tool not just build tool like Ant.
You should use Eclipse IDE with maven plugin to fix all your problems.
Here are few advantages of Maven, quoted from the Benefits of using Maven page:
Henning
- quick project setup, no complicated build.xml files, just a POM and go
- all developers in a project use the same jar dependencies due to
centralized POM.
- getting a number of reports and metrics for a project "for free"
- reduce the size of source distributions, because jars can be
pulled from a central location
Emmanuel Venisse
- a lot of goals are available so it isn't necessary to develop some
specific build process part contrary
to ANT we can reuse existing ANT tasks
in build process with antrun plugin
Jesse Mcconnell
- Promotes modular design of code. by making it simple to manage mulitple
projects it allows the design to be
laid out into muliple logical parts,
weaving these parts together through
the use of dependency tracking in pom
files.
- Enforces modular design of code. it is easy to pay lipservice to modular
code, but when the code is in seperate
compiling projects it is impossible to
cross pollinate references between
modules of code unless you
specifically allow for it in your
dependency management... there is no
'I'll just do this now and fix it
later' implementations.
- Dependency Management is clearly declared. with the dependency
management mechanism you have to try
to screw up your jar
versioning...there is none of the
classic problem of 'which version of
this vendor jar is this?' And setting
it up on an existing project rips the
top off of the existing mess if it
exists when you are forced to make
'unknown' versions in your repository
to get things up and running...that or
lie to yourself that you know the
actual version of ABC.jar.
- strong typed life cycle there is a strong defined lifecycle that a
software system goes thru from the
initiation of a build to the end...
and the users are allowed to mix and
match their system to the lifecycle
instead of cobble together their own
lifecycle.. this has the additional
benefit of allowing people to move
from one project to another and speak
using the same vocabulary in terms of
software building
Vincent Massol
- Greater momentum: Ant is now legacy and not moving fast ahead. Maven is
forging ahead fast and there's a
potential of having lots of high-value
tools around Maven (CI, Dashboard
project, IDE integration, etc).
How to write DataFrame to postgres table?
Pandas 0.24.0+ solution
In Pandas 0.24.0 a new feature was introduced specifically designed for fast writes to Postgres. You can learn more about it here: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#io-sql-method
import csv
from io import StringIO
from sqlalchemy import create_engine
def psql_insert_copy(table, conn, keys, data_iter):
# gets a DBAPI connection that can provide a cursor
dbapi_conn = conn.connection
with dbapi_conn.cursor() as cur:
s_buf = StringIO()
writer = csv.writer(s_buf)
writer.writerows(data_iter)
s_buf.seek(0)
columns = ', '.join('"{}"'.format(k) for k in keys)
if table.schema:
table_name = '{}.{}'.format(table.schema, table.name)
else:
table_name = table.name
sql = 'COPY {} ({}) FROM STDIN WITH CSV'.format(
table_name, columns)
cur.copy_expert(sql=sql, file=s_buf)
engine = create_engine('postgresql://myusername:mypassword@myhost:5432/mydatabase')
df.to_sql('table_name', engine, method=psql_insert_copy)
RegEx to exclude a specific string constant
This isn't easy, unless your regexp engine has special support for it. The easiest way would be to use a negative-match option, for example:
$var !~ /^foo$/
or die "too much foo";
If not, you have to do something evil:
$var =~ /^(($)|([^f].*)|(f[^o].*)|(fo[^o].*)|(foo.+))$/
or die "too much foo";
That one basically says "if it starts with non-f
, the rest can be anything; if it starts with f
, non-o
, the rest can be anything; otherwise, if it starts fo
, the next character had better not be another o
".
spacing between form fields
<form>
<div class="form-group">
<label for="nameLabel">Name</label>
<input id="name" name="name" class="form-control" type="text" />
</div>
<div class="form-group">
<label for="PhoneLabel">Phone</label>
<input id="phone" name="phone" class="form-control" type="text" />
</div>
<div class="form-group">
<label for="yearLabel">Year</label>
<input id="year" name="year" class="form-control" type="text" />
</div>
</form>
How to define a variable in a Dockerfile?
You can use ARG variable defaultValue
and during the run command you can even update this value using --build-arg variable=value
. To use these variables in the docker file you can refer them as $variable
in run command.
Note: These variables would be available for Linux commands like RUN echo $variable
and they wouldn't persist in the image.
How do I get the current timezone name in Postgres 9.3?
I don't think this is possible using PostgreSQL alone in the most general case. When you install PostgreSQL, you pick a time zone. I'm pretty sure the default is to use the operating system's timezone. That will usually be reflected in postgresql.conf as the value of the parameter "timezone". But the value ends up as "localtime". You can see this setting with the SQL statement.
show timezone;
But if you change the timezone in postgresql.conf to something like "Europe/Berlin", then show timezone;
will return that value instead of "localtime".
So I think your solution will involve setting "timezone" in postgresql.conf to an explicit value rather than the default "localtime".
isPrime Function for Python Language
Every code you write should be efficient.For a beginner like you the easiest way is to check the divisibility of the number 'n' from 2 to (n-1). This takes a lot of time when you consider very big numbers. The square root method helps us make the code faster by less number of comparisons. Read about complexities in Design and Analysis of Algorithms.
Add a dependency in Maven
I'll assume that you're asking how to push a dependency out to a "well-known repository," and not simply asking how to update your POM.
If yes, then this is what you want to read.
And for anyone looking to set up an internal repository server, look here (half of the problem with using Maven 2 is finding the docs)
How do I restore a dump file from mysqldump?
If you want to view the progress of the dump try this:
pv -i 1 -p -t -e /path/to/sql/dump | mysql -u USERNAME -p DATABASE_NAME
You'll of course need 'pv' installed. This command works only on *nix.
Add item to array in VBScript
Slight change to the FastArray from above:
'pushtest.vbs
imax = 10000000
value = "Testvalue"
s = imax & " of """ & value & """"
t0 = timer 'Fast array
a = array()
ub = UBound(a)
For i = 0 To imax
If i>ub Then
ReDim Preserve a(Int((ub+10)*1.1))
ub = UBound(a)
End If
a(i) = value
Next
ReDim Preserve a(i-1)
s = s & "[FastArr " & FormatNumber(timer - t0, 3, -1) & "]"
MsgBox s
There is no point in checking UBound(a)
in every cycle of the for if we know exactly when it changes.
I've changed it so that it checks does UBound(a)
just before the for starts and then only every time the ReDim
is called
On my computer the old method took 7.52 seconds for an imax of 10 millions.
The new method took 5.29 seconds for an imax of also 10 millions, which signifies a performance increase of over 20% (for 10 millions tries, obviously this percentage has a direct relationship to the number of tries)
Unix command to find lines common in two files
To easily apply the comm command to unsorted files, use Bash's process substitution:
$ bash --version
GNU bash, version 3.2.51(1)-release
Copyright (C) 2007 Free Software Foundation, Inc.
$ cat > abc
123
567
132
$ cat > def
132
777
321
So the files abc and def have one line in common, the one with "132".
Using comm on unsorted files:
$ comm abc def
123
132
567
132
777
321
$ comm -12 abc def # No output! The common line is not found
$
The last line produced no output, the common line was not discovered.
Now use comm on sorted files, sorting the files with process substitution:
$ comm <( sort abc ) <( sort def )
123
132
321
567
777
$ comm -12 <( sort abc ) <( sort def )
132
Now we got the 132 line!
How do you access a website running on localhost from iPhone browser
In my case
first i connected my pc and mobile on the same network, you can ping your mobile from pc to test the connection.
I running my project with GGTS(Groovy/Grails Tool Suite) locally then accessing website from mobile using PC IP address and it's work very well.
PS. running from local it would give url like (http://localhost:8080/projectname) you should replace localhost with PC IP address if you are trying to access your local website from mobile
What is the best way to get the minimum or maximum value from an Array of numbers?
Unless the array is sorted, that's the best you're going to get. If it is sorted, just take the first and last elements.
Of course, if it's not sorted, then sorting first and grabbing the first and last is guaranteed to be less efficient than just looping through once. Even the best sorting algorithms have to look at each element more than once (an average of O(log N) times for each element. That's O(N*Log N) total. A simple scan once through is only O(N).
If you are wanting quick access to the largest element in a data structure, take a look at heaps for an efficient way to keep objects in some sort of order.
How to complete the RUNAS command in one line
The runas command does not allow a password on its command line. This is by design (and also the reason you cannot pipe a password to it as input). Raymond Chen says it nicely:
The RunAs program demands that you type the password manually. Why doesn't it accept a password on the command line?
This was a conscious decision. If it were possible to pass the password on the command line, people would start embedding passwords into batch files and logon scripts, which is laughably insecure.
In other words, the feature is missing to remove the temptation to use the feature insecurely.
Include another HTML file in a HTML file
I know this is a very old post, so some methods were not available back then.
But here is my very simple take on it (based on Lolo's answer).
It relies on the HTML5 data-* attributes and therefore is very generic in that is uses jQuery's for-each function to get every .class matching "load-html" and uses its respective 'data-source' attribute to load the content:
<div class="container-fluid">
<div class="load-html" id="NavigationMenu" data-source="header.html"></div>
<div class="load-html" id="MainBody" data-source="body.html"></div>
<div class="load-html" id="Footer" data-source="footer.html"></div>
</div>
<script src="js/jquery.min.js"></script>
<script>
$(function () {
$(".load-html").each(function () {
$(this).load(this.dataset.source);
});
});
</script>
How to implement a lock in JavaScript
Some addition to JoshRiver's answer according to my case;
var functionCallbacks = [];
var functionLock = false;
var getData = function (url, callback) {
if (functionLock) {
functionCallbacks.push(callback);
} else {
functionLock = true;
functionCallbacks.push(callback);
$.getJSON(url, function (data) {
while (functionCallbacks.length) {
var thisCallback = functionCallbacks.pop();
thisCallback(data);
}
functionLock = false;
});
}
};
// Usage
getData("api/orders",function(data){
barChart(data);
});
getData("api/orders",function(data){
lineChart(data);
});
There will be just one api call and these two function will consume same result.
#if DEBUG vs. Conditional("DEBUG")
With the first example, SetPrivateValue
won't exist in the build if DEBUG
is not defined, with the second example, calls to SetPrivateValue
won't exist in the build if DEBUG
is not defined.
With the first example, you'll have to wrap any calls to SetPrivateValue
with #if DEBUG
as well.
With the second example, the calls to SetPrivateValue
will be omitted, but be aware that SetPrivateValue
itself will still be compiled. This is useful if you're building a library, so an application referencing your library can still use your function (if the condition is met).
If you want to omit the calls and save the space of the callee, you could use a combination of the two techniques:
[System.Diagnostics.Conditional("DEBUG")]
public void SetPrivateValue(int value){
#if DEBUG
// method body here
#endif
}
Visual Studio Code pylint: Unable to import 'protorpc'
The visual studio default setting should be the same as the interpreter path.
Change VS code default setting: windows: File > Preferences > Settings
{
"python.pythonPath": "C:\\Users\\Anaconda3\\pythonw.exe",
"workbench.startupEditor": "newUntitledFile"
}
Find the right interpreter:
windows: Ctrl+Shift+P->select interpreter:
the path of that interpreter should be same as the version you are working on.
How do you check if a string is not equal to an object or other string value in java?
you'll want to use && to see that it is not equal to "AM" AND not equal to "PM"
if(!TimeOfDayStringQ.equals("AM") && !TimeOfDayStringQ.equals("PM")) {
System.out.println("Sorry, incorrect input.");
System.exit(1);
}
to be clear you can also do
if(!(TimeOfDayStringQ.equals("AM") || TimeOfDayStringQ.equals("PM"))){
System.out.println("Sorry, incorrect input.");
System.exit(1);
}
to have the not (one or the other)
phrase in the code (remember the (silent) brackets)
How to add an object to an array
Performance
Today 2020.12.04 I perform tests on MacOs HighSierra 10.13.6 on Chrome v86, Safari v13.1.2 and Firefox v83 for chosen solutions.
Results
For all browsers
- in-place solution based on
length
(B) is fastest for small arrays, and in Firefox for big too and for Chrome and Safari is fast
- in-place solution based on
push
(A) is fastest for big arrays on Chrome and Safari, and fast for Firefox and small arrays
- in-place solution C is slow for big arrays and medium fast for small
- non-in-place solutions D and E are slow for big arrays
- non-in-place solutions E,F and D(on Firefox) are slow for small arrays
Details
I perform 2 tests cases:
- for small array with 10 elements - you can run it HERE
- for big array with 1M elements - you can run it HERE
Below snippet presents differences between solutions
A,
B,
C,
D,
E,
F
PS: Answer B was deleted - but actually it was the first answer which use this technique so if you have access to see it please click on "undelete".
_x000D_
_x000D_
// https://stackoverflow.com/a/6254088/860099
function A(a,o) {
a.push(o);
return a;
}
// https://stackoverflow.com/a/47506893/860099
function B(a,o) {
a[a.length] = o;
return a;
}
// https://stackoverflow.com/a/6254088/860099
function C(a,o) {
return a.concat(o);
}
// https://stackoverflow.com/a/50933891/860099
function D(a,o) {
return [...a,o];
}
// https://stackoverflow.com/a/42428064/860099
function E(a,o) {
const frozenObj = Object.freeze(o);
return Object.freeze(a.concat(frozenObj));
}
// https://stackoverflow.com/a/6254088/860099
function F(a,o) {
a.unshift(o);
return a;
}
// -------
// TEST
// -------
[A,B,C,D,E,F].map(f=> {
console.log(`${f.name} ${JSON.stringify(f([1,2],{}))}`)
})
_x000D_
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"> </script>
This shippet only presents functions used in performance tests - it not perform tests itself!
_x000D_
_x000D_
_x000D_
And here are example results for chrome
Handle spring security authentication exceptions with @ExceptionHandler
The best way I've found is to delegate the exception to the HandlerExceptionResolver
@Component("restAuthenticationEntryPoint")
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Autowired
private HandlerExceptionResolver resolver;
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
resolver.resolveException(request, response, null, exception);
}
}
then you can use @ExceptionHandler to format the response the way you want.
How to add scroll bar to the Relative Layout?
hi see the following sample code of xml file.
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:id="@+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dip"
android:text="@+id/TextView01" >
</TextView>
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dip"
android:text="@+id/TextView01" >
</TextView>
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dip"
android:text="@+id/TextView01" >
</TextView>
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dip"
android:text="@+id/TextView01" >
</TextView>
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dip"
android:text="@+id/TextView01" >
</TextView>
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dip"
android:text="@+id/TextView01" >
</TextView>
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dip"
android:text="@+id/TextView01" >
</TextView>
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dip"
android:text="@+id/TextView01" >
</TextView>
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dip"
android:text="@+id/TextView01" >
</TextView>
</LinearLayout>
</RelativeLayout>
</ScrollView>
javascript check for not null
This should work fine..
if(val!= null)
{
alert("value is "+val.length); //-- this returns 4
}
else
{
alert("value* is null");
}
Day Name from Date in JS
Easiest and simplest way:
var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var dayName = days[new Date().getDay()];
How to set environment variable for everyone under my linux system?
Every process running under the Linux kernel receives its own, unique environment that it inherits from its parent. In this case, the parent will be either a shell itself (spawning a sub shell), or the 'login' program (on a typical system).
As each process' environment is protected, there is no way to 'inject' an environmental variable to every running process, so even if you modify the default shell .rc / profile, it won't go into effect until each process exits and reloads its start up settings.
Look in /etc/ to modify the default start up variables for any particular shell. Just realize that users can (and often do) change them in their individual settings.
Unix is designed to obey the user, within limits.
NB: Bash is not the only shell on your system. Pay careful attention to what the /bin/sh symbolic link actually points to. On many systems, this could actually be dash which is (by default, with no special invocation) POSIXLY correct. Therefore, you should take care to modify both defaults, or scripts that start with /bin/sh will not inherit your global defaults. Similarly, take care to avoid syntax that only bash understands when editing both, aka avoiding bashisms
.
Code line wrapping - how to handle long lines
This is how I do it, and Google does it my way.
- Break before the symbol for non-assignment operators.
- Break after the symbol for
=
and for ,
.
In your case, since you're using 120 characters, you can break it after the assignment operator resulting in
private static final Map<Class<? extends Persistent>, PersistentHelper> class2helper =
new HashMap<Class<? extends Persistent>, PersistentHelper>();
In Java, and for this particular case, I would give two tabs (or eight spaces) after the break, depending on whether tabs or spaces are used for indentation.
This is of course a personal preference and if your project has its own convention for line-wrapping then that is what you should follow whether you like it or not.
Java regex to extract text between tags
You're on the right track. Now you just need to extract the desired group, as follows:
final Pattern pattern = Pattern.compile("<tag>(.+?)</tag>", Pattern.DOTALL);
final Matcher matcher = pattern.matcher("<tag>String I want to extract</tag>");
matcher.find();
System.out.println(matcher.group(1)); // Prints String I want to extract
If you want to extract multiple hits, try this:
public static void main(String[] args) {
final String str = "<tag>apple</tag><b>hello</b><tag>orange</tag><tag>pear</tag>";
System.out.println(Arrays.toString(getTagValues(str).toArray())); // Prints [apple, orange, pear]
}
private static final Pattern TAG_REGEX = Pattern.compile("<tag>(.+?)</tag>", Pattern.DOTALL);
private static List<String> getTagValues(final String str) {
final List<String> tagValues = new ArrayList<String>();
final Matcher matcher = TAG_REGEX.matcher(str);
while (matcher.find()) {
tagValues.add(matcher.group(1));
}
return tagValues;
}
However, I agree that regular expressions are not the best answer here. I'd use XPath to find elements I'm interested in. See The Java XPath API for more info.
Get values from a listbox on a sheet
Take selected value:
worksheet name = ordls
form control list box name = DEPDB1
selectvalue = ordls.Shapes("DEPDB1").ControlFormat.List(ordls.Shapes("DEPDB1").ControlFormat.Value)
How to add custom validation to an AngularJS form?
You can use Angular-Validator.
Example: using a function to validate a field
<input type = "text"
name = "firstName"
ng-model = "person.firstName"
validator = "myCustomValidationFunction(form.firstName)">
Then in your controller you would have something like
$scope.myCustomValidationFunction = function(firstName){
if ( firstName === "John") {
return true;
}
You can also do something like this:
<input type = "text"
name = "firstName"
ng-model = "person.firstName"
validator = "'!(field1 && field2 && field3)'"
invalid-message = "'This field is required'">
(where field1 field2, and field3 are scope variables. You might also want to check if the fields do not equal the empty string)
If the field does not pass the validator
then the field will be marked as invalid and the user will not be able to submit the form.
For more use cases and examples see: https://github.com/turinggroup/angular-validator
Disclaimer: I am the author of Angular-Validator
IIS7 folder permissions for web application
- Working on IIS 7.5 and Windows 7 i couldnt give permission
APPPOOL/Mypool
- IUSR and IIS_IUSRS permissions not working for me
I got to problem this way:
-Created console application with C#
-This appliaction using createeventsource like this
if(!System.Diagnostics.EventLog.SourceExists(sourceName)) System.Diagnostics.EventLog.CreateEventSource(sourceName,logName);
-Build solution and get .exe file
-Run exe as administator.This create log file.
NOTE: Dont remember Event viewer must be refresh for see the log.
I hope this solution helps someone :)
Wait for a void async method
I know this is an old question, but this is still a problem I keep walking into, and yet there is still no clear solution to do this correctly when using async/await in an async void signature method.
However, I noticed that .Wait() is working properly inside the void method.
and since async void and void have the same signature, you might need to do the following.
void LoadBlahBlah()
{
blah().Wait(); //this blocks
}
Confusingly enough async/await does not block on the next code.
async void LoadBlahBlah()
{
await blah(); //this does not block
}
When you decompile your code, my guess is that async void creates an internal Task (just like async Task), but since the signature does not support to return that internal Tasks
this means that internally the async void method will still be able to "await" internally async methods. but externally unable to know when the internal Task is complete.
So my conclusion is that async void is working as intended, and if you need feedback from the internal Task, then you need to use the async Task signature instead.
hopefully my rambling makes sense to anybody also looking for answers.
Edit:
I made some example code and decompiled it to see what is actually going on.
static async void Test()
{
await Task.Delay(5000);
}
static async Task TestAsync()
{
await Task.Delay(5000);
}
Turns into (edit: I know that the body code is not here but in the statemachines, but the statemachines was basically identical, so I didn't bother adding them)
private static void Test()
{
<Test>d__1 stateMachine = new <Test>d__1();
stateMachine.<>t__builder = AsyncVoidMethodBuilder.Create();
stateMachine.<>1__state = -1;
AsyncVoidMethodBuilder <>t__builder = stateMachine.<>t__builder;
<>t__builder.Start(ref stateMachine);
}
private static Task TestAsync()
{
<TestAsync>d__2 stateMachine = new <TestAsync>d__2();
stateMachine.<>t__builder = AsyncTaskMethodBuilder.Create();
stateMachine.<>1__state = -1;
AsyncTaskMethodBuilder <>t__builder = stateMachine.<>t__builder;
<>t__builder.Start(ref stateMachine);
return stateMachine.<>t__builder.Task;
}
neither AsyncVoidMethodBuilder or AsyncTaskMethodBuilder actually have any code in the Start method that would hint of them to block, and would always run asynchronously after they are started.
meaning without the returning Task, there would be no way to check if it is complete.
as expected, it only starts the Task running async, and then it continues in the code.
and the async Task, first it starts the Task, and then it returns it.
so I guess my answer would be to never use async void, if you need to know when the task is done, that is what async Task is for.
Passing an array/list into a Python function
You don't need to use the asterisk to accept a list.
Simply give the argument a name in the definition, and pass in a list like
def takes_list(a_list):
for item in a_list:
print item
How to remove square brackets from list in Python?
Yes, there are several ways to do it. For instance, you can convert the list to a string and then remove the first and last characters:
l = ['a', 2, 'c']
print str(l)[1:-1]
'a', 2, 'c'
If your list contains only strings and you want remove the quotes too then you can use the join
method as has already been said.
IIS7 URL Redirection from root to sub directory
I could not get this working with the accepted answer, mainly because I did not know where to enter that code. I looked everywhere for some explanation of the URL Rewrite tool that made sense, but could not find any. I ended up using the HTTP Redirect tool in IIS.
- Choose your site
- Click HTTP Redirect in the IIS section (Make sure the Role Service is installed)
- Check "Redirect requests to this destination"
- Enter where you want to redirect. In your case "wwww.mysite.com/menu_1/MainScreen.aspx"
- In Redirect Behavior, I found I had to check "Only redirect requests to content in this directory (not subdirectories), or it would go into a loop. See what works for you.
Hope this helps.
AngularJS Error: $injector:unpr Unknown Provider
This error is also appears when one accidntally injects $scope into theirs factory:
angular.module('m', [])
.factory('util', function ($scope) { // <-- this '$scope' gives 'Unknown provider' when one attempts to inject 'util'
// ...
});
Why doesn't Mockito mock static methods?
As an addition to the Gerold Broser's answer, here an example of mocking a static method with arguments:
class Buddy {
static String addHello(String name) {
return "Hello " + name;
}
}
...
@Test
void testMockStaticMethods() {
assertThat(Buddy.addHello("John")).isEqualTo("Hello John");
try (MockedStatic<Buddy> theMock = Mockito.mockStatic(Buddy.class)) {
theMock.when(() -> Buddy.addHello("John")).thenReturn("Guten Tag John");
assertThat(Buddy.addHello("John")).isEqualTo("Guten Tag John");
}
assertThat(Buddy.addHello("John")).isEqualTo("Hello John");
}
Descending order by date filter in AngularJs
Descending Sort by date
It will help to filter records with date in descending order.
$scope.logData = [
{ event: 'Payment', created_at: '04/05/17 6:47 PM PST' },
{ event: 'Payment', created_at: '04/06/17 12:47 AM PST' },
{ event: 'Payment', created_at: '04/05/17 1:50 PM PST' }
];
<div ng-repeat="logs in logData | orderBy: '-created_at'" >
{{logs.event}}
</div>
What steps are needed to stream RTSP from FFmpeg?
Another streaming command I've had good results with is piping the ffmpeg output to vlc to create a stream. If you don't have these installed, you can add them:
sudo apt install vlc ffmpeg
In the example I use an mpeg transport stream (ts) over http, instead of rtsp. I've tried both, but the http ts stream seems to work glitch-free on my playback devices.
I'm using a video capture HDMI>USB device that sets itself up on the video4linux2 driver as input. Piping through vlc must be CPU-friendly, because my old dual-core Pentium CPU is able to do the real-time encoding with no dropped frames. I've also had audio-sync issues with some of the other methods, where this method always has perfect audio-sync.
You will have to adjust the command for your device or file. If you're using a file as input, you won't need all that v4l2 and alsa stuff. Here's the ffmpeg|vlc command:
ffmpeg -thread_queue_size 1024 -f video4linux2 -input_format mjpeg -i /dev/video0 -r 30 -f alsa -ac 1 -thread_queue_size 1024 -i hw:1,0 -acodec aac -vcodec libx264 -preset ultrafast -crf 18 -s hd720 -vf format=yuv420p -profile:v main -threads 0 -f mpegts -|vlc -I dummy - --sout='#std{access=http,mux=ts,dst=:8554}'
For example, lets say your server PC IP is 192.168.0.10, then the stream can be played by this command:
ffplay http://192.168.0.10:8554
#or
vlc http://192.168.0.10:8554
Including dependencies in a jar with Maven
Thanks
I have added below snippet in POM.xml file and Mp problem resolved and
create fat jar file that include all dependent jars.
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
<configuration>
<descriptorRefs>
<descriptorRef>dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
VS 2017 Metadata file '.dll could not be found
For me cleaning and building didn't work. Unloading the project didn't work. Restarting Visual Studio or even the pc didn't work. This is what did work:
Go to each of the projects that are throwing the error, and in References, delete the reference to the problematic project and add it again. That solves the issue.
The problem seems to be related to moving a project around (Move it inside a folder for example), then a different project that references it, have its path wrong and can't find it.
How do I solve this "Cannot read property 'appendChild' of null" error?
For all those facing a similar issue, I came across this same issue when i was trying to run a particular code snippet, shown below.
<html>
<head>
<script>
var div, container = document.getElementById("container")
for(var i=0;i<5;i++){
div = document.createElement("div");
div.onclick = function() {
alert("This is a box #"+i);
};
container.appendChild(div);
}
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
https://codepen.io/pcwanderer/pen/MMEREr
Looking at the error in the console for the above code.
Since the document.getElementById is returning a null and as null does not have a attribute named appendChild, therefore a error is thrown. To solve the issue see the code below.
<html>
<head>
<style>
#container{
height: 200px;
width: 700px;
background-color: red;
margin: 10px;
}
div{
height: 100px;
width: 100px;
background-color: purple;
margin: 20px;
display: inline-block;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
var div, container = document.getElementById("container")
for(let i=0;i<5;i++){
div = document.createElement("div");
div.onclick = function() {
alert("This is a box #"+i);
};
container.appendChild(div);
}
</script>
</body>
</html>
https://codepen.io/pcwanderer/pen/pXWBQL
I hope this helps. :)
How do I `jsonify` a list in Flask?
This is working for me. Which version of Flask are you using?
from flask import jsonify
...
@app.route('/test/json')
def test_json():
list = [
{'a': 1, 'b': 2},
{'a': 5, 'b': 10}
]
return jsonify(results = list)
What is /var/www/html?
In the most shared hosts you can't set it.
On a VPS or dedicated server, you can set it, but everything has its price.
On shared hosts, in general you receive a Linux account, something such as /home/(your username)/, and the equivalent of /var/www/html turns to /home/(your username)/public_html/ (or something similar, such as /home/(your username)/www)
If you're accessing your account via FTP, you automatically has accessing the your */home/(your username)/ folder, just find the www or public_html and put your site in it.
If you're using absolute path in the code, bad news, you need to refactor it to use relative paths in the code, at least in a shared host.
How to position a div scrollbar on the left hand side?
Here is what I have done to make the right scroll bar work. The only thing needed to be considered is when using 'direction: rtl' and whole table also need to be changed. Hopefully this gives you an idea how to do it.
Example:
<table dir='rtl'><tr><td>Display Last</td><td>Display Second</td><td>Display First</td></table>
Check this: JSFiddle
Substitute a comma with a line break in a cell
Windows (unlike some other OS's, like Linux), uses CR+LF for line breaks:
The characters need to be in that order, if you want the line breaks to be consistently visible when copied to other Windows programs. So the Excel function would be:
=SUBSTITUTE(A1,",",CHAR(13) & CHAR(10))
Remove leading comma from a string
remove leading or trailing characters:
function trimLeadingTrailing(inputStr, toRemove) {
// use a regex to match toRemove at the start (^)
// and at the end ($) of inputStr
const re = new Regex(`/^${toRemove}|{toRemove}$/`);
return inputStr.replace(re, '');
}
How do I output text without a newline in PowerShell?
desired o/p:
Enabling feature XYZ......Done
you can use below command
$a = "Enabling feature XYZ"
Write-output "$a......Done"
you have to add variable and statement inside quotes. hope this is helpful :)
Thanks
Techiegal
Pandas groupby month and year
Why not keep it simple?!
GB=DF.groupby([(DF.index.year),(DF.index.month)]).sum()
giving you,
print(GB)
abc xyz
2013 6 80 250
8 40 -5
2014 1 25 15
2 60 80
and then you can plot like asked using,
GB.plot('abc','xyz',kind='scatter')
Django upgrading to 1.9 error "AppRegistryNotReady: Apps aren't loaded yet."
Got this error while trying to access model objects in apps.py
:
class QuizConfig(AppConfig):
name = 'quiz'
def ready(self):
print('===============> Django just started....')
questions_by_category = Question.objects.filter(category=2) # <=== Guilty line of code.
Trying to access Question
before the app has loaded the model class caused the error for me.
prevent iphone default keyboard when focusing an <input>
Since I can't comment on the top comment, I'm forced to submit an "answer."
The problem with the selected answer is that setting the field to readonly takes the field out of the tab order on the iPhone. So if you like entering forms by hitting "next", you'll skip right over the field.
How do you cast a List of supertypes to a List of subtypes?
You can use the selectInstances
method in Eclipse Collections. This will involved creating a new collection however so will not be as efficient as the accepted solution which uses casting.
List<CharSequence> parent =
Arrays.asList("1","2","3", new StringBuffer("4"));
List<String> strings =
Lists.adapt(parent).selectInstancesOf(String.class);
Assert.assertEquals(Arrays.asList("1","2","3"), strings);
I included StringBuffer
in the example to show that selectInstances
not only downcasts the type, but will also filter if the collection contains mixed types.
Note: I am a committer for Eclipse Collections.
apply drop shadow to border-top only?
.item .content{
width: 94.1%;
background: #2d2d2d;
padding: 3%;
border-top: solid 1px #000;
position: relative;
}
.item .content:before{
content: "";
display: block;
position: absolute;
top: 0px;
left: 0;
width: 100%;
height: 1px;
-webkit-box-shadow: 0px 1px 13px rgba(255,255,255,1);
-moz-box-shadow: 0px 1px 13px rgba(255,255,255,1);
box-shadow: 0px 1px 13px rgba(255,255,255,1);
z-index: 100;
}
I am like using something like it for it.
Android:java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM
Soluton try this in your Manifest File and use Glide Library
compile 'com.github.bumptech.glide:glide:3.7.0'
**Use Glide Library and Override size to less size;**
if (!TextUtils.isEmpty(message.getPicture())) {
Glide.with(mContext).load(message.getPicture())
.thumbnail(0.5f)
.crossFade()
.transform(new CircleTransform(mContext))
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(holder.imgProfile);
}
android:hardwareAccelerated="false"
android:largeHeap="true"
<application
android:allowBackup="true"
android:hardwareAccelerated="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:largeHeap="true"
android:supportsRtl="true"
android:theme="@style/AppTheme">
Use this library
compile 'com.github.bumptech.glide:glide:3.7.0'
Its Working Happy Coding
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
public class CircleTransform extends BitmapTransformation {
public CircleTransform(Context context) {
super(context);
}
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
return circleCrop(pool, toTransform);
}
private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
if (source == null) return null;
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
// TODO this could be acquired from the pool too
Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
if (result == null) {
result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
paint.setAntiAlias(true);
float r = size / 2f;
canvas.drawCircle(r, r, r, paint);
return result;
}
@Override
public String getId() {
return getClass().getName();
}
}
C++ initial value of reference to non-const must be an lvalue
When you call test
with &nKByte
, the address-of operator creates a temporary value, and you can't normally have references to temporary values because they are, well, temporary.
Either do not use a reference for the argument, or better yet don't use a pointer.
surface plots in matplotlib
This is not a general solution but might help many of those who just typed "matplotlib surface plot" in Google and landed here.
Suppose you have data = [(x1,y1,z1),(x2,y2,z2),.....,(xn,yn,zn)]
, then you can get three 1-d lists using x, y, z = zip(*data)
. Now you can of course create 3d scatterplot using three 1-d lists.
But, why can't in general this data be used to create surface plot? To understand that consider an empty 3-d plot :
Now, suppose for each possible value of (x, y) on a "discrete" regular grid, you have a z value, then there's no issue & you can in fact get a surface plot:
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
x = np.linspace(0, 10, 6) # [0, 2,..,10] : 6 distinct values
y = np.linspace(0, 20, 5) # [0, 5,..,20] : 5 distinct values
z = np.linspace(0, 100, 30) # 6 * 5 = 30 values, 1 for each possible combination of (x,y)
X, Y = np.meshgrid(x, y)
Z = np.reshape(z, X.shape) # Z.shape must be equal to X.shape = Y.shape
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()
What's happens when you haven't got z for all possible combinations of (x, y)? Then at the point (at intersection of two black lines on x-y plane on blank plot above), we don't know what is the value of z. It could be anything, we don't know how 'high' or 'low' our surface should be at that point (although it can be approximated using other functions, surface_plot
requires that you supply it arguments where X.shape = Y.shape = Z.shape).
How to sort a Collection<T>?
You can't if T is all you get. It must be injected by the provider:
Collection<T extends Comparable>
or pass in the Comparator
Collections.sort(...)
How to make canvas responsive
To change width is not that hard. Just remove the width
attribute from the tag and add width: 100%;
in the css for #canvas
#canvas{
border: solid 1px blue;
width: 100%;
}
Changing height is a bit harder: you need javascript. I have used jQuery because i'm more comfortable with.
you need to remove the height
attribute from the canvas tag and add this script:
<script>
function resize(){
$("#canvas").outerHeight($(window).height()-$("#canvas").offset().top- Math.abs($("#canvas").outerHeight(true) - $("#canvas").outerHeight()));
}
$(document).ready(function(){
resize();
$(window).on("resize", function(){
resize();
});
});
</script>
You can see this fiddle: https://jsfiddle.net/1a11p3ng/3/
EDIT:
To answer your second question. You need javascript
0) First of all i changed your #border id into a class since ids must be unique for an element inside an html page (you can't have 2 tags with the same id)
.border{
border: solid 1px black;
}
#canvas{
border: solid 1px blue;
width: 100%;
}
1) Changed your HTML to add ids where needed, two inputs and a button to set the values
<div class="row">
<div class="col-xs-2 col-sm-2 border">content left</div>
<div class="col-xs-6 col-sm-6 border" id="main-content">
<div class="row">
<div class="col-xs-6">
Width <input id="w-input" type="number" class="form-control">
</div>
<div class="col-xs-6">
Height <input id="h-input" type="number" class="form-control">
</div>
<div class="col-xs-12 text-right" style="padding: 3px;">
<button id="set-size" class="btn btn-primary">Set</button>
</div>
</div>
canvas
<canvas id="canvas"></canvas>
</div>
<div class="col-xs-2 col-sm-2 border">content right</div>
</div>
2) Set the canvas height and width so that it fits inside the container
$("#canvas").outerHeight($(window).height()-$("#canvas").offset().top-Math.abs( $("#canvas").outerHeight(true) - $("#canvas").outerHeight()));
3) Set the values of the width and height forms
$("#h-input").val($("#canvas").outerHeight());
$("#w-input").val($("#canvas").outerWidth());
4) Finally, whenever you click on the button you set the canvas width and height to the values set. If the width value is bigger than the container's width then it will resize the canvas to the container's width instead (otherwise it will break your layout)
$("#set-size").click(function(){
$("#canvas").outerHeight($("#h-input").val());
$("#canvas").outerWidth(Math.min($("#w-input").val(), $("#main-content").width()));
});
See a full example here https://jsfiddle.net/1a11p3ng/7/
UPDATE 2:
To have full control over the width you can use this:
<div class="container-fluid">
<div class="row">
<div class="col-xs-2 border">content left</div>
<div class="col-xs-8 border" id="main-content">
<div class="row">
<div class="col-xs-6">
Width <input id="w-input" type="number" class="form-control">
</div>
<div class="col-xs-6">
Height <input id="h-input" type="number" class="form-control">
</div>
<div class="col-xs-12 text-right" style="padding: 3px;">
<button id="set-size" class="btn btn-primary">Set</button>
</div>
</div>
canvas
<canvas id="canvas">
</canvas>
</div>
<div class="col-xs-2 border">content right</div>
</div>
</div>
<script>
$(document).ready(function(){
$("#canvas").outerHeight($(window).height()-$("#canvas").offset().top-Math.abs( $("#canvas").outerHeight(true) - $("#canvas").outerHeight()));
$("#h-input").val($("#canvas").outerHeight());
$("#w-input").val($("#canvas").outerWidth());
$("#set-size").click(function(){
$("#canvas").outerHeight($("#h-input").val());
$("#main-content").width($("#w-input").val());
$("#canvas").outerWidth($("#main-content").width());
});
});
</script>
https://jsfiddle.net/1a11p3ng/8/
the content left and content right columns will move above and belove the central div if the width is too high, but this can't be helped if you are using bootstrap. This is not, however, what responsive means. a truly responsive site will adapt its size to the user screen to keep the layout as you have intended without any external input, letting the user set any size which may break your layout does not mean making a responsive site.
Is there an easy way to convert jquery code to javascript?
The easiest way is to just learn how to do DOM traversing and manipulation with the plain DOM api (you would probably call this: normal JavaScript).
This can however be a pain for some things. (which is why libraries were invented in the first place).
Googling for "javascript DOM traversing/manipulation" should present you with plenty of helpful (and some less helpful) resources.
The articles on this website are pretty good: http://www.htmlgoodies.com/primers/jsp/
And as Nosredna points out in the comments: be sure to test in all browsers, because now jQuery won't be handling the inconsistencies for you.
CSS: Fix row height
You can also try this, if this is what you need:
<style type="text/css">
....
table td div {height:20px;overflow-y:hidden;}
table td.col1 div {width:100px;}
table td.col2 div {width:300px;}
</style>
<table>
<tbody>
<tr><td class="col1"><div>test</div></td></tr>
<tr><td class="col2"><div>test</div></td></tr>
</tbody>
</table>
Angular : Manual redirect to route
Angular Redirection manually: Import @angular/router
, Inject in constructor()
then call this.router.navigate()
.
import {Router} from '@angular/router';
...
...
constructor(private router: Router) {
...
}
onSubmit() {
...
this.router.navigate(['/profile']);
}
How do I manage conflicts with git submodules?
I had this problem with git rebase -i origin/master
to a branch. I wanted to take master's version of the submodule ref, so I simply did:
git reset master path/to/submodule
and then
git rebase --continue
That solved the problem for me.
MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource
I followed all the steps above indicated by Mihai-Andrei Dinculescu.
But in my case, I needed 1 more step because http OPTIONS was disabled in the Web.Config by the line below.
<remove name="OPTIONSVerbHandler" />
I just removed it from Web.Config (just comment it like below) and Cors works like a charm
<handlers>
<!-- remove name="OPTIONSVerbHandler" / -->
</handlers>
Build a basic Python iterator
If you looking for something short and simple, maybe it will be enough for you:
class A(object):
def __init__(self, l):
self.data = l
def __iter__(self):
return iter(self.data)
example of usage:
In [3]: a = A([2,3,4])
In [4]: [i for i in a]
Out[4]: [2, 3, 4]
Open the terminal in visual studio?
Not sure if this will help, but I usually pull the command prompt up by going into "Synchronization" tab in Team Explorer and clicking on "Actions"
When the command prompt opens it is in the directory of the project.
How to get the parent dir location
A simple way can be:
import os
current_dir = os.path.abspath(os.path.dirname(__file__))
parent_dir = os.path.abspath(current_dir + "/../")
print parent_dir
error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup
In case someone missed the obvious; note that if you build a GUI application and use
"-subsystem:windows" in the link-args, the application entry is WinMain@16. Not main(). Hence you can use this snippet to call your main():
#include <stdlib.h>
#include <windows.h>
#ifdef __GNUC__
#define _stdcall __attribute__((stdcall))
#endif
int _stdcall
WinMain (struct HINSTANCE__ *hInstance,
struct HINSTANCE__ *hPrevInstance,
char *lpszCmdLine,
int nCmdShow)
{
return main (__argc, __argv);
}
Programmatically center TextView text
if your text size is small, you should make the width of your text view to be "fill_parent". After that, you can set your TextView Gravity to center :
TextView textView = new TextView(this);
textView.setText(message);
textView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
textView.setGravity(Gravity.CENTER);
Postgresql - select something where date = "01/01/11"
With PostgreSQL there are a number of date/time functions available, see here.
In your example, you could use:
SELECT * FROM myTable WHERE date_trunc('day', dt) = 'YYYY-MM-DD';
If you are running this query regularly, it is possible to create an index using the date_trunc
function as well:
CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt) );
One advantage of this is there is some more flexibility with timezones if required, for example:
CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt at time zone 'Australia/Sydney') );
SELECT * FROM myTable WHERE date_trunc('day', dt at time zone 'Australia/Sydney') = 'YYYY-MM-DD';
Converting file into Base64String and back again
Another working example in VB.NET:
Public Function base64Encode(ByVal myDataToEncode As String) As String
Try
Dim myEncodeData_byte As Byte() = New Byte(myDataToEncode.Length - 1) {}
myEncodeData_byte = System.Text.Encoding.UTF8.GetBytes(myDataToEncode)
Dim myEncodedData As String = Convert.ToBase64String(myEncodeData_byte)
Return myEncodedData
Catch ex As Exception
Throw (New Exception("Error in base64Encode" & ex.Message))
End Try
'
End Function
How to convert HH:mm:ss.SSS to milliseconds?
If you want to use SimpleDateFormat
, you could write:
private final SimpleDateFormat sdf =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
{ sdf.setTimeZone(TimeZone.getTimeZone("GMT")); }
private long parseTimeToMillis(final String time) throws ParseException
{ return sdf.parse("1970-01-01 " + time).getTime(); }
But a custom method would be much more efficient. SimpleDateFormat
, because of all its calendar support, time-zone support, daylight-savings-time support, and so on, is pretty slow. The slowness is worth it if you actually need some of those features, but since you don't, it might not be. (It depends how often you're calling this method, and whether efficiency is a concern for your application.)
Also, SimpleDateFormat
is non-thread-safe, which is sometimes a pain. (Without knowing anything about your application, I can't guess whether that matters.)
Personally, I'd probably write a custom method.
Fast Linux file count for a large number of files
You should use "getdents" in place of ls/find
Here is one very good article which described the getdents approach.
http://be-n.com/spw/you-can-list-a-million-files-in-a-directory-but-not-with-ls.html
Here is the extract:
ls
and practically every other method of listing a directory (including Python's os.listdir and find .
) rely on libc readdir(). However, readdir() only reads 32K of directory entries at a time, which means that if you have a lot of files in the same directory (e.g., 500 million directory entries) it is going to take an insanely long time to read all the directory entries, especially on a slow disk. For directories containing a large number of files, you'll need to dig deeper than tools that rely on readdir(). You will need to use the getdents() system call directly, rather than helper methods from the C standard library.
We can find the C code to list the files using getdents() from here:
There are two modifications you will need to do in order quickly list all the files in a directory.
First, increase the buffer size from X to something like 5 megabytes.
#define BUF_SIZE 1024*1024*5
Then modify the main loop where it prints out the information about each file in the directory to skip entries with inode == 0. I did this by adding
if (dp->d_ino != 0) printf(...);
In my case I also really only cared about the file names in the directory so I also rewrote the printf() statement to only print the filename.
if(d->d_ino) printf("%sn ", (char *) d->d_name);
Compile it (it doesn't need any external libraries, so it's super simple to do)
gcc listdir.c -o listdir
Now just run
./listdir [directory with an insane number of files]
Use find command but exclude files in two directories
Here's how you can specify that with find
:
find . -type f -name "*_peaks.bed" ! -path "./tmp/*" ! -path "./scripts/*"
Explanation:
find .
- Start find from current working directory (recursively by default)
-type f
- Specify to find
that you only want files in the results
-name "*_peaks.bed"
- Look for files with the name ending in _peaks.bed
! -path "./tmp/*"
- Exclude all results whose path starts with ./tmp/
! -path "./scripts/*"
- Also exclude all results whose path starts with ./scripts/
Testing the Solution:
$ mkdir a b c d e
$ touch a/1 b/2 c/3 d/4 e/5 e/a e/b
$ find . -type f ! -path "./a/*" ! -path "./b/*"
./d/4
./c/3
./e/a
./e/b
./e/5
You were pretty close, the -name
option only considers the basename, where as -path
considers the entire path =)
How to combine results of two queries into a single dataset
The problem is that unless your tables are related you can't determine how to join them, so you'd have to arbitrarily join them, resulting in a cartesian product:
select Table1.col1, Table1.col2, Table2.col3, Table2.col4
from Table1
cross join Table2
If you had, for example, the following data:
col1 col2
a 1
b 2
col3 col4
y 98
z 99
You would end up with the following:
col1 col2 col3 col4
a 1 y 98
a 1 z 99
b 2 y 98
b 2 z 99
Is this what you're looking for? If not, and you have some means of relating the tables, then you'd need to include that in joining the two tables together, e.g.:
select Table1.col1, Table1.col2, Table2.col3, Table2.col4
from Table1
inner join Table2
on Table1.JoiningField = Table2.JoiningField
That would pull things together for you into however the data is related, giving you your result.
Display image at 50% of its "native" size
Set the image to be the background of a div, then set the background size to be half the width of the image.
<div class="myimage"></div>
Then in your css, if your image is 300px x 200px:
.myimage {
background: url('images/myimage.png') no-repeat;
background-size:150px;
width:150px;
height:100px;
}
Automatically enter SSH password with script
After looking for an answer for the question for months, I finally found a better solution: writing a simple script.
#!/usr/bin/expect
set timeout 20
set cmd [lrange $argv 1 end]
set password [lindex $argv 0]
eval spawn $cmd
expect "assword:"
send "$password\r";
interact
Put it to /usr/bin/exp
, then you can use:
exp <password> ssh <anything>
exp <password> scp <anysrc> <anydst>
Done!
How to get correlation of two vectors in python
The docs indicate that numpy.correlate
is not what you are looking for:
numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
Cross-correlation of two 1-dimensional sequences.
This function computes the correlation as generally defined in signal processing texts:
z[k] = sum_n a[n] * conj(v[n+k])
with a and v sequences being zero-padded where necessary and conj being the conjugate.
Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:
from scipy.stats.stats import pearsonr
a = [1,4,6]
b = [1,2,3]
print pearsonr(a,b)
This gives
(0.99339926779878274, 0.073186395040328034)
You can also use numpy.corrcoef
:
import numpy
print numpy.corrcoef(a,b)
This gives:
[[ 1. 0.99339927]
[ 0.99339927 1. ]]
How to create timer events using C++ 11?
If you are on Windows, you can use the CreateThreadpoolTimer function to schedule a callback without needing to worry about thread management and without blocking the current thread.
template<typename T>
static void __stdcall timer_fired(PTP_CALLBACK_INSTANCE, PVOID context, PTP_TIMER timer)
{
CloseThreadpoolTimer(timer);
std::unique_ptr<T> callable(reinterpret_cast<T*>(context));
(*callable)();
}
template <typename T>
void call_after(T callable, long long delayInMs)
{
auto state = std::make_unique<T>(std::move(callable));
auto timer = CreateThreadpoolTimer(timer_fired<T>, state.get(), nullptr);
if (!timer)
{
throw std::runtime_error("Timer");
}
ULARGE_INTEGER due;
due.QuadPart = static_cast<ULONGLONG>(-(delayInMs * 10000LL));
FILETIME ft;
ft.dwHighDateTime = due.HighPart;
ft.dwLowDateTime = due.LowPart;
SetThreadpoolTimer(timer, &ft, 0 /*msPeriod*/, 0 /*msWindowLength*/);
state.release();
}
int main()
{
auto callback = []
{
std::cout << "in callback\n";
};
call_after(callback, 1000);
std::cin.get();
}
Copy data into another table
If both tables are truly the same schema:
INSERT INTO newTable
SELECT * FROM oldTable
Otherwise, you'll have to specify the column names (the column list for newTable
is optional if you are specifying a value for all columns and selecting columns in the same order as newTable
's schema):
INSERT INTO newTable (col1, col2, col3)
SELECT column1, column2, column3
FROM oldTable
Authenticate with GitHub using a token
Normally I do like this
git push https://$(git_token)@github.com/user_name/repo_name.git
The git_token is reading from variable config in azure devops.
You can read my full blog here
Can't import database through phpmyadmin file size too large
For Upload large size data in using phpmyadmin
Do following steps.
- Open php.ini file from C:\wamp\bin\apache\Apache2.4.4\bin Update
following lines
max_execution_time = 259200
max_input_time = 259200
memory_limit = 1000M
upload_max_filesize = 750M
post_max_size = 750M
than after restart wamp server or restart all services Now Upload
data using import function in phymyadmin. Apply second step if
till not upload data.
- open config.default.php file in
c:\wamp\apps\phpmyadmin4.0.4\libraries (Open this file accoring
to phpmyadmin version)
Find $cfg['ExecTimeLimit'] = 300;
Replace to $cfg['ExecTimeLimit'] = 0;
Now you can upload data.
You can also upload large size database using MySQL Console as below.
- Click on WampServer Icon -> MySQL -> MySQL Consol
- Enter your database password like
root
in popup
- Select database name for insert data by writing command
USE DATABASENAME
- Then load source sql file as
SOURCE C:\FOLDER\database.sql
- Press enter for insert data.
Note: You can't load a compressed database file e.g. database.sql.zip
or database.sql.gz
, you have to extract it first. Otherwise the console will just crash.
How to use SVG markers in Google Maps API v3
You can render your icon using the SVG Path notation.
See Google documentation for more information.
Here is a basic example:
var icon = {
path: "M-20,0a20,20 0 1,0 40,0a20,20 0 1,0 -40,0",
fillColor: '#FF0000',
fillOpacity: .6,
anchor: new google.maps.Point(0,0),
strokeWeight: 0,
scale: 1
}
var marker = new google.maps.Marker({
position: event.latLng,
map: map,
draggable: false,
icon: icon
});
Here is a working example on how to display and scale a marker SVG icon:
JSFiddle demo
Edit:
Another example here with a complex icon:
JSFiddle demo
Edit 2:
And here is how you can have a SVG file as an icon:
JSFiddle demo
Replace one character with another in Bash
You could use tr
, like this:
tr " " .
Example:
# echo "hello world" | tr " " .
hello.world
From man tr
:
DESCRIPTION
Translate, squeeze, and/or delete characters from standard input, writ-
ing to standard output.
SQL - IF EXISTS UPDATE ELSE INSERT INTO
Try this:
INSERT INTO `center_course_fee` (`fk_course_id`,`fk_center_code`,`course_fee`) VALUES ('69', '4920153', '6000') ON DUPLICATE KEY UPDATE `course_fee` = '6000';
How do I concatenate text in a query in sql server?
If you are using SQL Server 2005 or greater, depending on the size of the data in the Notes field, you may want to consider casting to nvarchar(max) instead of casting to a specific length which could result in string truncation.
Select Cast(notes as nvarchar(max)) + 'SomeText' From NotesTable a
moment.js, how to get day of week number
If you are specifically looking for the 1-7 approach...
This is the ISO weekday number. moment.js has also taken this into account. Use isoWeekday()
_x000D_
_x000D_
console.log(moment().isoWeekday()); // returns 1-7 where 1 is Monday and 7 is Sunday
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
_x000D_
_x000D_
_x000D_
Seeing as I wrote this answer on a Tuesday, today this gives me a 2.
Open file dialog and select a file using WPF controls and C#
var ofd = new Microsoft.Win32.OpenFileDialog() {Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif"};
var result = ofd.ShowDialog();
if (result == false) return;
textBox1.Text = ofd.FileName;
How can I copy the output of a command directly into my clipboard?
Without using external tools, if you are connecting to the server view SSH, this is a relatively easy command:
From a Windows 7+ command prompt:
ssh user@server cat /etc/passwd | clip
This will put the content of the remote file to your local clipboard.
(The command requires running Pageant for the key, or it will ask you for a password.)
Unstage a deleted file in git
Assuming you're wanting to undo the effects of git rm <file>
or rm <file>
followed by git add -A
or something similar:
# this restores the file status in the index
git reset -- <file>
# then check out a copy from the index
git checkout -- <file>
To undo git add <file>
, the first line above suffices, assuming you haven't committed yet.
How to define static constant in a class in swift
Adding to @Martin's answer...
If anyone planning to keep an application level constant file, you can group the constant based on their type or nature
struct Constants {
struct MixpanelConstants {
static let activeScreen = "Active Screen";
}
struct CrashlyticsConstants {
static let userType = "User Type";
}
}
Call : Constants.MixpanelConstants.activeScreen
UPDATE 5/5/2019 (kinda off topic but ???)
After reading some code guidelines & from personal experiences it seems structs are not the best approach for storing global constants for a couple of reasons.
Especially the above code doesn't prevent initialization of the struct. We can achieve it by adding some boilerplate code but there is a better approach
ENUMS
The same can be achieved using an enum with a more secure & clear representation
enum Constants {
enum MixpanelConstants: String {
case activeScreen = "Active Screen";
}
enum CrashlyticsConstants: String {
case userType = "User Type";
}
}
print(Constants.MixpanelConstants.activeScreen.rawValue)
How to redirect back to form with input - Laravel 5
In your HTML you have to use value = {{ old('') }}
. Without using it, you can't get the value back because what session will store in their cache.
Like for a name validation, this will be-
<input type="text" name="name" value="{{ old('name') }}" />
Now, you can get the value after submitting it if there is error with redirect.
return redirect()->back()->withInput();
As @infomaniac says, you can also use the Input class
directly,
return Redirect::back()->withInput(Input::all());
Add:
If you only show the specific field, then use $request->only()
return redirect()->back()->withInput($request->only('name'));
Hope, it might work in all case, thanks.
ObjectiveC Parse Integer from String
NSArray *_returnedArguments = [serverOutput componentsSeparatedByString:@":"];
_returnedArguments
is an array of NSStrings
which the UITextField text
property is expecting. No need to convert.
Syntax error:
[_appDelegate loggedIn:usernameField.text:passwordField.text:(int)[[_returnedArguments objectAtIndex:2] intValue]];
If your _appDelegate has a passwordField
property, then you can set the text using the following
[[_appDelegate passwordField] setText:[_returnedArguments objectAtIndex:2]];
Multi-gradient shapes
You can layer gradient shapes in the xml using a layer-list.
Imagine a button with the default state as below, where the second item is semi-transparent. It adds a sort of vignetting. (Please excuse the custom-defined colours.)
<!-- Normal state. -->
<item>
<layer-list>
<item>
<shape>
<gradient
android:startColor="@color/grey_light"
android:endColor="@color/grey_dark"
android:type="linear"
android:angle="270"
android:centerColor="@color/grey_mediumtodark" />
<stroke
android:width="1dp"
android:color="@color/grey_dark" />
<corners
android:radius="5dp" />
</shape>
</item>
<item>
<shape>
<gradient
android:startColor="#00666666"
android:endColor="#77666666"
android:type="radial"
android:gradientRadius="200"
android:centerColor="#00666666"
android:centerX="0.5"
android:centerY="0" />
<stroke
android:width="1dp"
android:color="@color/grey_dark" />
<corners
android:radius="5dp" />
</shape>
</item>
</layer-list>
</item>
How to list imported modules?
This code lists modules imported by your module:
import sys
before = [str(m) for m in sys.modules]
import my_module
after = [str(m) for m in sys.modules]
print [m for m in after if not m in before]
It should be useful if you want to know what external modules to install on a new system to run your code, without the need to try again and again.
It won't list the sys
module or modules imported from it.
How can I use UserDefaults in Swift?
//Save
NSUserDefaults.standardUserDefaults().setObject("yourString", forKey: "YourStringKey")
//retrive
let yourStr : AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey("YourStringKey")
Remove header and footer from window.print()
@page { margin: 0; }
works fine in Chrome and Firefox. I haven't found a way to fix IE through css. But you can go into Page Setup in IE on your own machine at and set the margins to 0. Press alt and then the file menu in the top left corner and you'll find Page Setup. This only works for the one machine at a time...
.htaccess rewrite to redirect root URL to subdirectory
I think the main problems with the code you posted are:
the first line matches on a host beginning with strictly sample.com, so www.sample.com doesn't match.
the second line wants at least one character, followed by www.sample.com which also doesn't match (why did you escape the first w?)
none of the included rules redirect to the url you specified in your goal (plus, sample is misspelled as samle, but that's irrelevant).
For reference, here's the code you currently have:
Options +FollowSymlinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^sample.com$
RewriteRule (.*) http://www.sample.com/$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^(.+)\www.sample\.com$
RewriteRule ^/(.*)$ /samle/%1/$1 [L]
For files in directory, only echo filename (no path)
Another approach is to use ls
when reading the file list within a directory so as to give you what you want, i.e. "just the file name/s". As opposed to reading the full file path and then extracting the "file name" component in the body of the for loop.
Example below that follows your original:
for filename in $(ls /home/user/)
do
echo $filename
done;
If you are running the script in the same directory as the files, then it simply becomes:
for filename in $(ls)
do
echo $filename
done;
How to uninstall jupyter
If you installed Jupiter notebook through anaconda, this may help you:
conda uninstall jupyter notebook
"The remote certificate is invalid according to the validation procedure." using Gmail SMTP server
You can improve the code by asking the user when the certificate is not valid whether he wants to continue or not. Do you want to continue? As below:
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback(ValidateServerCertificate);
And add a method like this:
public static bool ValidateServerCertificate(object sender,X509Certificate certificate,X509Chain chain,SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
else
{
if (System.Windows.Forms.MessageBox.Show("The server certificate is not valid.\nAccept?", "Certificate Validation", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
return true;
else
return false;
}
}
Flask Python Buttons
In case anyone was still looking and came across this SO post like I did.
<input type="submit" name="open" value="Open">
<input type="submit" name="close" value="Close">
def contact():
if "open" in request.form:
pass
elif "close" in request.form:
pass
return render_template('contact.html')
Simple, concise, and it works. Don't even need to instantiate a form object.
Where can I find php.ini?
This works for me:
php -i | grep 'php.ini'
You should see something like:
Loaded Configuration File => /usr/local/lib/php.ini
p.s.
To get only the php.inin path
php -i | grep /.+/php.ini -oE
Escaping single quote in PHP when inserting into MySQL
You should be escaping each of these strings (in both snippets) with mysql_real_escape_string()
.
http://us3.php.net/mysql-real-escape-string
The reason your two queries are behaving differently is likely because you have magic_quotes_gpc
turned on (which you should know is a bad idea). This means that strings gathered from $_GET, $_POST and $_COOKIES are escaped for you (i.e., "O'Brien" -> "O\'Brien"
).
Once you store the data, and subsequently retrieve it again, the string you get back from the database will not be automatically escaped for you. You'll get back "O'Brien"
. So, you will need to pass it through mysql_real_escape_string()
.
permission denied - php unlink
The file permission is okay (0777) but i think your on the shared server, so to delete your file correctly use;
1. create a correct path to your file
// delete from folder
$filename = 'test.txt';
$ifile = '/newy/made/link/uploads/'. $filename; // this is the actual path to the file you want to delete.
unlink($_SERVER['DOCUMENT_ROOT'] .$ifile); // use server document root
// your file will be removed from the folder
That small code will do the magic and remove any selected file you want from any folder provided the actual file path is collect.
Adding Google Translate to a web site
<div id="google_translate_element"></div>
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({
pageLanguage: 'en',
includedLanguages: 'es',
layout: google.translate.TranslateElement.InlineLayout.SIMPLE
}, 'google_translate_element');
}
</script>
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
phpexcel to download
Instead of saving it to a file, save it to php://output
Docs:
$objWriter->save('php://output');
This will send it AS-IS to the browser.
You want to add some headersDocs first, like it's common with file downloads, so the browser knows which type that file is and how it should be named (the filename):
// We'll be outputting an excel file
header('Content-type: application/vnd.ms-excel');
// It will be called file.xls
header('Content-Disposition: attachment; filename="file.xls"');
// Write file to the browser
$objWriter->save('php://output');
First do the headers, then the save. For the excel headers see as well the following question: Setting mime type for excel document.
T-SQL to list all the user mappings with database roles/permissions for a Login
Is this the kind of thing you want?
You might want to extend it to get more info out of the sys tables.
use master
DECLARE @name VARCHAR(50) -- database name
DECLARE db_cursor CURSOR FOR
select name from sys.databases
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @name
WHILE @@FETCH_STATUS = 0
BEGIN
print @name
exec('USE ' + @name + '; select rp.name, mp.name from sys.database_role_members drm
join sys.database_principals rp on (drm.role_principal_id = rp.principal_id)
join sys.database_principals mp on (drm.member_principal_id = mp.principal_id)')
FETCH NEXT FROM db_cursor INTO @name
END
CLOSE db_cursor
DEALLOCATE db_cursor
Python, TypeError: unhashable type: 'list'
The problem is that you can't use a list
as the key in a dict
, since dict
keys need to be immutable. Use a tuple instead.
This is a list:
[x, y]
This is a tuple:
(x, y)
Note that in most cases, the (
and )
are optional, since ,
is what actually defines a tuple (as long as it's not surrounded by []
or {}
, or used as a function argument).
You might find the section on tuples in the Python tutorial useful:
Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.
And in the section on dictionaries:
Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().
In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.
How to program a fractal?
You should indeed start with the Mandelbrot set, and understand what it really is.
The idea behind it is relatively simple. You start with a function of complex variable
f(z) = z2 + C
where z is a complex variable and C is a complex constant. Now you iterate it starting from z = 0, i.e. you compute z1 = f(0), z2 = f(z1), z3 = f(z2) and so on. The set of those constants C for which the sequence z1, z2, z3, ... is bounded, i.e. it does not go to infinity, is the Mandelbrot set (the black set in the figure on the Wikipedia page).
In practice, to draw the Mandelbrot set you should:
- Choose a rectangle in the complex plane (say, from point -2-2i to point 2+2i).
- Cover the rectangle with a suitable rectangular grid of points (say, 400x400 points), which will be mapped to pixels on your monitor.
- For each point/pixel, let C be that point, compute, say, 20 terms of the corresponding iterated sequence z1, z2, z3, ... and check whether it "goes to infinity". In practice you can check, while iterating, if the absolute value of one of the 20 terms is greater than 2 (if one of the terms does, the subsequent terms are guaranteed to be unbounded). If some z_k does, the sequence "goes to infinity"; otherwise, you can consider it as bounded.
- If the sequence corresponding to a certain point C is bounded, draw the corresponding pixel on the picture in black (for it belongs to the Mandelbrot set). Otherwise, draw it in another color. If you want to have fun and produce pretty plots, draw it in different colors depending on the magnitude of abs(20th term).
The astounding fact about fractals is how we can obtain a tremendously complex set (in particular, the frontier of the Mandelbrot set) from easy and apparently innocuous requirements.
Enjoy!
Clean out Eclipse workspace metadata
The only way I know to deal with this is to create a new workspace,
import projects from the polluted workspace, reconstructing all my
settings (a major pain) and then delete the old workspace. Is there an
easier way to deal with this?
For synchronizing or restoring all our settings we use Workspace Mechanic. Once all the settings are recorded its one click and all settings are restored...
You can also setup a server which provides those settings for all users.
When to use static methods
No, static methods aren't associated with an instance; they belong to the class. Static methods are your second example; instance methods are the first.
iterrows pandas get next rows value
There is a pairwise()
function example in the itertools
document:
from itertools import tee, izip
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return izip(a, b)
import pandas as pd
df = pd.DataFrame(['AA', 'BB', 'CC'], columns = ['value'])
for (i1, row1), (i2, row2) in pairwise(df.iterrows()):
print i1, i2, row1["value"], row2["value"]
Here is the output:
0 1 AA BB
1 2 BB CC
But, I think iter rows in a DataFrame
is slow, if you can explain what's the problem you want to solve, maybe I can suggest some better method.
Add User to Role ASP.NET Identity
Below is an alternative implementation of a 'create user' controller method using Claims based roles.
The created claims then work with the Authorize attribute e.g. [Authorize(Roles = "Admin, User.*, User.Create")]
// POST api/User/Create
[Route("Create")]
public async Task<IHttpActionResult> Create([FromBody]CreateUserModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Generate long password for the user
var password = System.Web.Security.Membership.GeneratePassword(25, 5);
// Create the user
var user = new ApiUser() { UserName = model.UserName };
var result = await UserManager.CreateAsync(user, password);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
// Add roles (permissions) for the user
foreach (var perm in model.Permissions)
{
await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Role, perm));
}
return Ok<object>(new { UserName = user.UserName, Password = password });
}
Implement a loading indicator for a jQuery AJAX call
I'm guessing you're using jQuery.get or some other jQuery ajax function to load the modal. You can show the indicator before the ajax call, and hide it when the ajax completes. Something like
$('#indicator').show();
$('#someModal').get(anUrl, someData, function() { $('#indicator').hide(); });
SVN commit command
Command-line SVN
You need to add your files to your working copy, before you commit your changes to the repository:
svn add <file|folder>
Afterwards:
svn commit
See here for detailed information about svn add
.
TortoiseSVN
It works with TortoiseSVN, because it adds the file to your working copy automatically (commit dialog):
If you want to include an unversioned file, just check that file to add it to the commit.
See: TortoiseSVN: Committing Your Changes To The Repository
How to unsubscribe to a broadcast event in angularJS. How to remove function registered via $on
After debugging the code, i created my own function just like "blesh"'s answer. So this is what i did
MyModule = angular.module('FIT', [])
.run(function ($rootScope) {
// Custom $off function to un-register the listener.
$rootScope.$off = function (name, listener) {
var namedListeners = this.$$listeners[name];
if (namedListeners) {
// Loop through the array of named listeners and remove them from the array.
for (var i = 0; i < namedListeners.length; i++) {
if (namedListeners[i] === listener) {
return namedListeners.splice(i, 1);
}
}
}
}
});
so by attaching my function to $rootscope now it is available to all my controllers.
and in my code I am doing
$scope.$off("onViewUpdated", callMe);
Thanks
EDIT: The AngularJS way to do this is in @LiviuT's answer! But if you want to de-register the listener in another scope and at the same time want to stay away from creating local variables to keep references of de-registeration function. This is a possible solution.
github changes not staged for commit
WARNING! THIS WILL DELETE THE ENTIRE GIT HISTORY FOR YOUR SUBMODULE. ONLY DO THIS IF YOU CREATED THE SUBMODULE BY ACCIDENT. CERTAINLY NOT WHAT YOU WANT TO DO IN MOST CASES.
In my situation, there was a sub-directory which had a .git
directory.
What I do is simply remove that .git
directory from my sub-directory.
How to view table contents in Mysql Workbench GUI?
Open a connection to your server first (SQL IDE) from the home screen. Then use the context menu in the schema tree to run a query that simply selects rows from the selected table. The LIMIT attached to that is to avoid reading too many rows by accident. This limit can be switched off (or adjusted) in the preferences dialog.
This quick way to select rows is however not very flexible. Normally you would run a query (File / New Query Tab) in the editor with additional conditions, like a sort order:
Laravel migration default value
Might be a little too late to the party, but hope this helps someone with similar issue.
The reason why your default value doesnt't work is because the migration file sets up the default value in your database (MySQL or PostgreSQL or whatever), and not in your Laravel application.
Let me illustrate with an example.
This line means Laravel is generating a new Book instance, as specified in your model. The new Book
object will have properties according to the table associated with the model. Up until this point, nothing is written on the database.
$book = new Book();
Now the following lines are setting up the values of each property of the Book
object. Same still, nothing is written on the database yet.
$book->author = 'Test'
$book->title = 'Test'
This line is the one writing to the database. After passing on the object to the database, then the empty fields will be filled by the database (may be default value, may be null, or whatever you specify on your migration file).
$book->save();
And thus, the default value will not pop up before you save it to the database.
But, that is not enough. If you try to access $book->price
, it will still be null (or 0, i'm not sure). Saving it is only adding the defaults to the record in the database, and it won't affect the Object you are carrying around.
So, to get the instance with filled-in default values, you have to re-fetch the instance. You may use the
Book::find($book->id);
Or, a more sophisticated way by refreshing the instance
$book->refresh();
And then, the next time you try to access the object, it will be filled with the default values.
What's the difference between implementation and compile in Gradle?
Brief Solution:
The better approach is to replace all compile
dependencies with implementation
dependencies. And only where you leak a module’s interface, you should use api
. That should cause a lot less recompilation.
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:25.4.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
// …
testImplementation 'junit:junit:4.12'
androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
}
Explain More:
Before Android Gradle plugin 3.0: we had a big problem which is one code change causes all modules to be recompiled. The root cause for this is that Gradle doesn’t know if you leak the interface of a module through another one or not.
After Android Gradle plugin 3.0: the latest Android Gradle plugin now requires you to explicitly define if you leak a module’s interface. Based on that it can make the right choice on what it should recompile.
As such the compile
dependency has been deprecated and replaced by two new ones:
api
: you leak the interface of this module through your own interface, meaning exactly the same as the old compile
dependency
implementation
: you only use this module internally and does not leak it through your interface
So now you can explicitly tell Gradle to recompile a module if the interface of a used module changes or not.
Courtesy of Jeroen Mols blog
Programmatically close aspx page from code behind
UPDATE: I have taken all of your input and came up with the following solution:
In code behind:
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterOnSubmitStatement(typeof(Page), "closePage", "window.onunload = CloseWindow();");
}
In aspx page:
function CloseWindow() {
window.close();
}
C++ performance vs. Java/C#
Actually, C# does not really run in a virtual machine like Java does. IL is compiled into assembly language, which is entirely native code and runs at the same speed as native code. You can pre-JIT an .NET application which entirely removes the JIT cost and then you are running entirely native code.
The slowdown with .NET will come not because .NET code is slower, but because it does a lot more behind the scenes to do things like garbage collect, check references, store complete stack frames, etc. This can be quite powerful and helpful when building applications, but also comes at a cost. Note that you could do all these things in a C++ program as well (much of the core .NET functionality is actually .NET code which you can view in ROTOR). However, if you hand wrote the same functionality you would probably end up with a much slower program since the .NET runtime has been optimized and finely tuned.
That said, one of the strengths of managed code is that it can be fully verifiable, ie. you can verify that the code will never access another processes's memory or do unsage things before you execute it. Microsoft has a research prototype of a fully managed operating system that has suprisingly shown that a 100% managed environment can actually perform significantly faster than any modern operating system by taking advantage of this verification to turn off security features that are no longer needed by managed programs (we are talking like 10x in some cases). SE radio has a great episode talking about this project.
Deleting row from datatable in C#
There several different ways to do it. But You can use the following approach:
List<DataRow> RowsToDelete = new List<DataRow>();
for (int i = 0; i < drr.Length; i++)
{
if(condition to delete the row)
{
RowsToDelete.Add(drr[i]);
}
}
foreach(var dr in RowsToDelete)
{
drr.Rows.Remove(dr);
}
What does the "static" modifier after "import" mean?
the difference between "import static com.showboy.Myclass" and "import com.showboy.Myclass"?
The first should generate a compiler error since the static import only works for importing fields or member types. (assuming MyClass is not an inner class or member from showboy)
I think you meant
import static com.showboy.MyClass.*;
which makes all static fields and members from MyClass available in the actual compilation unit without having to qualify them... as explained above