You could use a dictionary. The definition is the same. But to save you time, Overhead is work required to do the productive work. For instance, an algorithm runs and does useful work, but requires memory to do its work. This memory allocation takes time, and is not directly related to the work being done, therefore is overhead.
Combining what Dick Lucas says and adding a reset autoincremental from other StackOverFlow posts, i think this can work:
fun clearAndResetAllTables(): Boolean {
val db = db ?: return false
// reset all auto-incrementalValues
val query = SimpleSQLiteQuery("DELETE FROM sqlite_sequence")
db.beginTransaction()
return try {
db.clearAllTables()
db.query(query)
db.setTransactionSuccessful()
true
} catch (e: Exception){
false
} finally {
db.endTransaction()
}
}
For those coming across this question more recently, .values
is deprecated as of Sequelize 3.0.0. Use .get()
instead to get the plain javascript object. So the above code would change to:
var nodedata = node.get({ plain: true });
Sequelize docs here
Calling window.setTimeout(function, delay)
will allow you to accomplish this. Here's an example that will automatically close the alert 2 seconds (or 2000 milliseconds) after it is displayed.
$(".alert-message").alert();
window.setTimeout(function() { $(".alert-message").alert('close'); }, 2000);
If you want to wrap it in a nifty function you could do this.
function createAutoClosingAlert(selector, delay) {
var alert = $(selector).alert();
window.setTimeout(function() { alert.alert('close') }, delay);
}
Then you could use it like so...
createAutoClosingAlert(".alert-message", 2000);
I am certain there are more elegant ways to accomplish this.
Here are the common characters which need to be escaped in XML, starting with double quotes:
"
) are escaped to "
&
) is escaped to &
'
) are escaped to '
<
) is escaped to <
>
) is escaped to >
Don't depends on builder or notification. Use custom code for vibrate.
public static void vibrate(Context context, int millis){
try {
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
v.vibrate(VibrationEffect.createOneShot(millis, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
v.vibrate(millis);
}
}catch(Exception ex){
}
}
I doubt anything is killing the process just because it takes a long time. Killed generically means something from the outside terminated the process, but probably not in this case hitting Ctrl-C since that would cause Python to exit on a KeyboardInterrupt exception. Also, in Python you would get MemoryError exception if that was the problem. What might be happening is you're hitting a bug in Python or standard library code that causes a crash of the process.
It's running every minute of the hour 22 I guess. Try the following to run it every first minute of the hour 22:
0 22 * * * ....
With Java 8 you can simply convert your list to a stream allowing you to write:
import java.util.List;
import java.util.stream.Collectors;
List<Sample> list = new ArrayList<Sample>();
List<Sample> result = list.stream()
.filter(a -> Objects.equals(a.value3, "three"))
.collect(Collectors.toList());
Note that
a -> Objects.equals(a.value3, "three")
is a lambda expressionresult
is a List
with a Sample
typelist.parallelStream()
instead of list.stream()
(read this)If you can't use Java 8, you can use Apache Commons library and write:
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
Collection result = CollectionUtils.select(list, new Predicate() {
public boolean evaluate(Object a) {
return Objects.equals(((Sample) a).value3, "three");
}
});
// If you need the results as a typed array:
Sample[] resultTyped = (Sample[]) result.toArray(new Sample[result.size()]);
Note that:
Object
to Sample
at each iterationSample[]
, you need extra code (as shown in my sample)Bonus: A nice blog article talking about how to find element in list.
Use getElementById()
if it's available.
Also, here's an easy way to do it with jQuery:
if ($('#elementId').length > 0) {
// Exists.
}
And if you can't use third-party libraries, just stick to base JavaScript:
var element = document.getElementById('elementId');
if (typeof(element) != 'undefined' && element != null)
{
// Exists.
}
1--> {Simple Insertion when table column sequence is known}
Insert into Table1
values(1,2,...)
2--> {Simple insertion mention column}
Insert into Table1(col2,col4)
values(1,2)
3--> {bulk insertion when num of selected collumns of a table(#table2) are equal to Insertion table(Table1) }
Insert into Table1 {Column sequence}
Select * -- column sequence should be same.
from #table2
4--> {bulk insertion when you want to insert only into desired column of a table(table1)}
Insert into Table1 (Column1,Column2 ....Desired Column from Table1)
Select Column1,Column2..desired column from #table2
The method I use is one of these or Hmisc::cut2(value, g=4)
:
temp$quartile <- with(temp, cut(value,
breaks=quantile(value, probs=seq(0,1, by=0.25), na.rm=TRUE),
include.lowest=TRUE))
An alternate might be:
temp$quartile <- with(temp, factor(
findInterval( val, c(-Inf,
quantile(val, probs=c(0.25, .5, .75)), Inf) , na.rm=TRUE),
labels=c("Q1","Q2","Q3","Q4")
))
The first one has the side-effect of labeling the quartiles with the values, which I consider a "good thing", but if it were not "good for you", or the valid problems raised in the comments were a concern you could go with version 2. You can use labels=
in cut
, or you could add this line to your code:
temp$quartile <- factor(temp$quartile, levels=c("1","2","3","4") )
Or even quicker but slightly more obscure in how it works, although it is no longer a factor, but rather a numeric vector:
temp$quartile <- as.numeric(temp$quartile)
I've found the solution in this thread
@(ViewContext.RouteData.Values["parameterName"])
git log --oneline | grep PATTERN
Here is my rendition....
function get_time_difference(earlierDate, laterDate)
{
var oDiff = new Object();
// Calculate Differences
// ------------------------------------------------------------------- //
var nTotalDiff = laterDate.getTime() - earlierDate.getTime();
oDiff.days = Math.floor(nTotalDiff / 1000 / 60 / 60 / 24);
nTotalDiff -= oDiff.days * 1000 * 60 * 60 * 24;
oDiff.hours = Math.floor(nTotalDiff / 1000 / 60 / 60);
nTotalDiff -= oDiff.hours * 1000 * 60 * 60;
oDiff.minutes = Math.floor(nTotalDiff / 1000 / 60);
nTotalDiff -= oDiff.minutes * 1000 * 60;
oDiff.seconds = Math.floor(nTotalDiff / 1000);
// ------------------------------------------------------------------- //
// Format Duration
// ------------------------------------------------------------------- //
// Format Hours
var hourtext = '00';
if (oDiff.days > 0){ hourtext = String(oDiff.days);}
if (hourtext.length == 1){hourtext = '0' + hourtext};
// Format Minutes
var mintext = '00';
if (oDiff.minutes > 0){ mintext = String(oDiff.minutes);}
if (mintext.length == 1) { mintext = '0' + mintext };
// Format Seconds
var sectext = '00';
if (oDiff.seconds > 0) { sectext = String(oDiff.seconds); }
if (sectext.length == 1) { sectext = '0' + sectext };
// Set Duration
var sDuration = hourtext + ':' + mintext + ':' + sectext;
oDiff.duration = sDuration;
// ------------------------------------------------------------------- //
return oDiff;
}
I've had success without the full package, do you know where the call chain is getting interrupted? If you debug with Log()
's, at what point does it no longer work?
I think it may be in your IntentService, this all looks fine.
When Python parses a function, it notes when a variable assignment is made. When there is an assignment, it assumes by default that that variable is a local variable. To declare that the assignment refers to a global variable, you must use the global
declaration.
When you access a variable in a function, its value is looked up using the LEGB scoping rules.
So, the first example
x = 1
def inc():
x += 5
inc()
produces an UnboundLocalError
because Python determined x
inside inc
to be a local variable,
while accessing x
works in your second example
def inc():
print x
because here, in accordance with the LEGB rule, Python looks for x
in the local scope, does not find it, then looks for it in the extended scope, still does not find it, and finally looks for it in the global scope successfully.
You can use exec
command to redirect all stdout/stderr output of any commands later.
sample script:
exec 2> your_file2 > your_file1
your other commands.....
Python documentation for sys.exit([arg])says:
The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise.
Moreover to retrieve the return value of the last executed program you could use the $? bash predefined variable.
Anyway if you put a string as arg in sys.exit() it should be printed at the end of your program output in a separate line, so that you can retrieve it just with a little bit of parsing. As an example consider this:
outputString=`python myPythonScript arg1 arg2 arg3 | tail -0`
You can traverse over the Getters of the Hibernate object in the same transaction to assure all lazy child objects are fetched eagerly with the following generic helper class:
HibernateUtil.initializeObject(myObject, "my.app.model");
package my.app.util;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
import org.aspectj.org.eclipse.jdt.core.dom.Modifier;
import org.hibernate.Hibernate;
public class HibernateUtil {
public static byte[] hibernateCollectionPackage = "org.hibernate.collection".getBytes();
public static void initializeObject( Object o, String insidePackageName ) {
Set<Object> seenObjects = new HashSet<Object>();
initializeObject( o, seenObjects, insidePackageName.getBytes() );
seenObjects = null;
}
private static void initializeObject( Object o, Set<Object> seenObjects, byte[] insidePackageName ) {
seenObjects.add( o );
Method[] methods = o.getClass().getMethods();
for ( Method method : methods ) {
String methodName = method.getName();
// check Getters exclusively
if ( methodName.length() < 3 || !"get".equals( methodName.substring( 0, 3 ) ) )
continue;
// Getters without parameters
if ( method.getParameterTypes().length > 0 )
continue;
int modifiers = method.getModifiers();
// Getters that are public
if ( !Modifier.isPublic( modifiers ) )
continue;
// but not static
if ( Modifier.isStatic( modifiers ) )
continue;
try {
// Check result of the Getter
Object r = method.invoke( o );
if ( r == null )
continue;
// prevent cycles
if ( seenObjects.contains( r ) )
continue;
// ignore simple types, arrays und anonymous classes
if ( !isIgnoredType( r.getClass() ) && !r.getClass().isPrimitive() && !r.getClass().isArray() && !r.getClass().isAnonymousClass() ) {
// ignore classes out of the given package and out of the hibernate collection
// package
if ( !isClassInPackage( r.getClass(), insidePackageName ) && !isClassInPackage( r.getClass(), hibernateCollectionPackage ) ) {
continue;
}
// initialize child object
Hibernate.initialize( r );
// traverse over the child object
initializeObject( r, seenObjects, insidePackageName );
}
} catch ( InvocationTargetException e ) {
e.printStackTrace();
return;
} catch ( IllegalArgumentException e ) {
e.printStackTrace();
return;
} catch ( IllegalAccessException e ) {
e.printStackTrace();
return;
}
}
}
private static final Set<Class<?>> IGNORED_TYPES = getIgnoredTypes();
private static boolean isIgnoredType( Class<?> clazz ) {
return IGNORED_TYPES.contains( clazz );
}
private static Set<Class<?>> getIgnoredTypes() {
Set<Class<?>> ret = new HashSet<Class<?>>();
ret.add( Boolean.class );
ret.add( Character.class );
ret.add( Byte.class );
ret.add( Short.class );
ret.add( Integer.class );
ret.add( Long.class );
ret.add( Float.class );
ret.add( Double.class );
ret.add( Void.class );
ret.add( String.class );
ret.add( Class.class );
ret.add( Package.class );
return ret;
}
private static Boolean isClassInPackage( Class<?> clazz, byte[] insidePackageName ) {
Package p = clazz.getPackage();
if ( p == null )
return null;
byte[] packageName = p.getName().getBytes();
int lenP = packageName.length;
int lenI = insidePackageName.length;
if ( lenP < lenI )
return false;
for ( int i = 0; i < lenI; i++ ) {
if ( packageName[i] != insidePackageName[i] )
return false;
}
return true;
}
}
Although this is a pretty old thread, I just found something out. I created a new database, then added a user, and finally went to use phpMyAdmin to upload the .sql file. total failure. The system doesn't recognize which DB I'm aiming at...
When I start fresh WITHOUT first attaching a new user, and then perform the same phpMyAdmin import, it works fine.
you can try writing the command using 'sudo':
sudo mkdir DirName
Try :
Configure in web config file
<system.web>
<globalization culture="ja-JP" uiCulture="zh-HK" />
</system.web>
eg: DateTime dt = DateTime.ParseExact("08/21/2013", "MM/dd/yyyy", null);
ref url : http://support.microsoft.com/kb/306162/
Please use parenthesis () to access the list elements list_name(index)
\n
is a line break. /n
is not.
use of \n
with
Now if you are trying to echo string to the page:
echo "kings \n garden";
output will be:
kings garden
you won't get garden
in new line because PHP is a server-side language, and you are sending output as HTML, you need to create line breaks in HTML. HTML doesn't understand \n
. You need to use the nl2br()
function for that.
What it does is:
Returns string with
<br />
or<br>
inserted before all newlines (\r\n, \n\r, \n and \r).
echo nl2br ("kings \n garden");
kings
garden
Note Make sure you're echoing/printing
\n
in double quotes, else it will be rendered literally as \n. because php interpreter parse string in single quote with concept of as is
so "\n" not '\n'
Now if you echo to text file you can use just \n
and it will echo to a new line, like:
$myfile = fopen("test.txt", "w+") ;
$txt = "kings \n garden";
fwrite($myfile, $txt);
fclose($myfile);
output will be:
kings
garden
def dir():
from glob import glob
dir = []
dir = glob("path")
def all_sub_dir(dir):
{
for item in dir:
{
b = "{}\*".format(item)
dir += glob(b)
}
print(dir)
}
This should work for all PHP versions. It determines the PHP version, then checks to see if the session is started based on the PHP version. Then if the session is not started it starts it.
function start_session() {
if(version_compare(phpversion(), "5.4.0") != -1){
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
} else {
if(session_id() == '') {
session_start();
}
}
}
Instead of RenderViewToString
I prefer a approach like
return Json(new { Url = Url.Action("Evil", model) });
then you can catch the result in your javascript and do something like
success: function(data) {
$.post(data.Url, function(partial) {
$('#IdOfDivToUpdate').html(partial);
});
}
Double quotes should work too... it should create a string, then it should APPEND/INSERT the casted STRING value of $myVar in between 2 empty strings.
Use .*
, and make sure you are using your implementations' equivalent of single-line so you will match on line endings.
There is a great explanation here -> http://www.regular-expressions.info/dot.html
I got a easy solution which will select from database table and let you do easily.
SELECT b.FirstName + b.LastName FROM tbl_Users b WHERE b.Id='11'
You can easily add a space there if you try
SELECT b.FirstName +' '+ b.LastName FROM Users b WHERE b.Id='23'
Here you can combine as much as your table have.
You can use run-as
shell command to access private application data.
If you only want to copy database you can use this snippet, provided in https://stackoverflow.com/a/31504263/998157
adb -d shell "run-as com.example.test cat /data/data/com.example.test/databases/data.db" > data.db
Vanilla JS
ES2016:
const found = arr1.some(r=> arr2.includes(r))
ES6:
const found = arr1.some(r=> arr2.indexOf(r) >= 0)
How it works
some(..)
checks each element of the array against a test function and returns true if any element of the array passes the test function, otherwise, it returns false. indexOf(..) >= 0
and includes(..)
both return true if the given argument is present in the array.
are you picky with using Unicode because with java its more simple if you write your program to use "dec" value or (HTML-Code) then you can simply cast data types between char and int
char a = 98;
char b = 'b';
char c = (char) (b+0002);
System.out.println(a);
System.out.println((int)b);
System.out.println((int)c);
System.out.println(c);
Gives this output
b
98
100
d
My goal was to pass a query string similar to:
protodb?sql=select * from protodb.prototab
to a Node.js 12 Lambda function via a URL from the API gateway. I tried a number of the ideas from the other answers but really wanted to do something in the most API gateway UI native way possible, so I came up with this that worked for me (as of the UI for API Gateway as of December 2020):
On the API Gateway console for a given API, under resources, select the get method. Then select its Integration Request and fill out the data for the lambda function at the top of the page.
Scroll to the bottom and open up the mapping templates section. Choose Request Body Passthrough when there are no templates defined (recommended).
Click on Add mapping templates and create one with the content-type of application/json and hit the check mark button.
For that mapping template, choose the Method Request passthrough on the drop down list for generate template which will fill the textbox under it with AWS' general way to pass everything.
Hit the save button.
Now when I tested it, I could not get the parameter to come through as event.sql under node JS in the Lambda function. It turns out that when the API gateway sends the URL sql query parameter to the Lambda function, it comes through for Node.js as:
var insql = event.params.querystring.sql;
So the trick that took some time for me was to use JSON.stringify to show the full event stack and then work my way down through the sections to be able to pull out the sql parameter from the query string.
So basically you can use the default passthrough functionality in the API gateway with the trick being how the parameters are passed when you are in the Lambda function.
Using ASP.NET's visible="false"
property will set the visibility
attribute where as I think when you call show()
in jQuery it modifies the display
attribute of the CSS style.
So doing the latter won't rectify the former.
You need to do this:
$("#test1").attr("visibility", "visible");
As mentioned by Jon F Hancock, this is how a fragment can 'close' the activity by suggesting the activity to close. This makes the fragment portable as is the reason for them. If you use it in a different activity, you might not want to close the activity.
Code below is a snippet from an activity and fragment which has a save and cancel button.
PlayerActivity
public class PlayerActivity extends Activity
implements PlayerInfo.PlayerAddListener {
public void onPlayerCancel() {
// Decide if its suitable to close the activity,
//e.g. is an edit being done in one of the other fragments?
finish();
}
}
PlayerInfoFragment, which contains an interface which the calling activity needs to implement.
public class PlayerInfoFragment extends Fragment {
private PlayerAddListener callback; // implemented in the Activity
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
callback= (PlayerAddListener) activity;
}
public interface PlayerAddListener {
public void onPlayerSave(Player p); // not shown in impl above
public void onPlayerCancel();
}
public void btnCancel(View v) {
callback.onPlayerCancel(); // the activity's implementation
}
}
If using @worldofjr answer in jQuery you are getting error:
e.relatedTarget.data is not a function
you should use:
$('#myModal').on('show.bs.modal', function (e) {
var loadurl = $(e.relatedTarget).data('load-url');
$(this).find('.modal-body').load(loadurl);
});
Not that e.relatedTarget
if wrapped by $(..)
I was getting the error in latest Bootstrap 3 and after using this method it's working without any problem.
Tomalak already gave you a correct answer, but I would like to add that most of the times when you would like to know the VBA code needed to do a certain action in the user interface it is a good idea to record a macro.
In this case click Record Macro on the developer tab of the Ribbon, freeze the top row and then stop recording. Excel will have the following macro recorded for you which also does the job:
With ActiveWindow
.SplitColumn = 0
.SplitRow = 1
End With
ActiveWindow.FreezePanes = True
You need to uncomment max_input_vars value in php.ini file and increase it (exp. 2000), also dont forget to restart your server this will help for 99,99%.
Two ways come to mind:
Using a command-line tool like the popular ffmpeg, however you will almost always need an own server (or a very nice server administrator / hosting company) to get that
Using the "screenshoot" plugin for the LongTail Video player that allows the creation of manual screenshots that are then sent to a server-side script.
The icon file is added to your project as a content file.
Here is a sample InputFilter which only allows max 4 digits before the decimal point and max 1 digit after that.
Values that edittext allows: 555.2, 555, .2
Values that edittext blocks: 55555.2, 055.2, 555.42
InputFilter filter = new InputFilter() {
final int maxDigitsBeforeDecimalPoint=4;
final int maxDigitsAfterDecimalPoint=1;
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
StringBuilder builder = new StringBuilder(dest);
builder.replace(dstart, dend, source
.subSequence(start, end).toString());
if (!builder.toString().matches(
"(([1-9]{1})([0-9]{0,"+(maxDigitsBeforeDecimalPoint-1)+"})?)?(\\.[0-9]{0,"+maxDigitsAfterDecimalPoint+"})?"
)) {
if(source.length()==0)
return dest.subSequence(dstart, dend);
return "";
}
return null;
}
};
mEdittext.setFilters(new InputFilter[] { filter });
You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start()
. The headers will be sent automatically when any HTML is output.
Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.
Move the session_start()
to the top of your document :
<?php session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php'; // more PHP code here.
pip
/ conda
After extensively documenting a similar problem with Git (How can I make git accept a self signed certificate?), here we are again behind a corporate firewall with a proxy giving us a MitM "attack" that we should trust and:
NEVER disable all SSL verification!
This creates a bad security culture. Don't be that person.
pip config set global.cert path/to/ca-bundle.crt
pip config list
conda config --set ssl_verify path/to/ca-bundle.crt
conda config --show ssl_verify
# Bonus while we are here...
git config --global http.sslVerify true
git config --global http.sslCAInfo path/to/ca-bundle.crt
But where do we get ca-bundle.crt
?
cURL publishes an extract of the Certificate Authorities bundled with Mozilla Firefox
https://curl.haxx.se/docs/caextract.html
I recommend you open up this cacert.pem
file in a text editor as we will need to add our self-signed CA to this file.
Certificates are a document complying with X.509 but they can be encoded to disk a few ways. The below article is a good read but the short version is that we are dealing with the base64 encoding which is often called PEM in the file extensions. You will see it has the format:
----BEGIN CERTIFICATE----
....
base64 encoded binary data
....
----END CERTIFICATE----
Below are a few options on how to get our self signed certificate:
echo quit | openssl s_client -showcerts -servername "curl.haxx.se" -connect curl.haxx.se:443 > cacert.pem
Thanks to this answer and the linked blog, it shows steps (on Windows) how to view the certificate and then copy to file using the base64 PEM encoding option.
Copy the contents of this exported file and paste it at the end of your cacerts.pem
file.
For consistency rename this file cacerts.pem
--> ca-bundle.crt
and place it somewhere easy like:
# Windows
%USERPROFILE%\certs\ca-bundle.crt
# or *nix
$HOME/certs/cabundle.crt
Thanks to all the brilliant answers in:
How to get response SSL certificate from requests in python?
I have put together the following to attempt to take it a step further.
https://github.com/neozenith/get-ca-py
Set the configuration in pip and conda so that it knows where this CA store resides with our extra self-signed CA.
pip config set global.cert %USERPROFILE%\certs\ca-bundle.crt
conda config --set ssl_verify %USERPROFILE%\certs\ca-bundle.crt
OR
pip config set global.cert $HOME/certs/ca-bundle.crt
conda config --set ssl_verify $HOME/certs/ca-bundle.crt
THEN
pip config list
conda config --show ssl_verify
# Hot tip: use -v to show where your pip config file is...
pip config list -v
# Example output for macOS and homebrew installed python
For variant 'global', will try loading '/Library/Application Support/pip/pip.conf'
For variant 'user', will try loading '/Users/jpeak/.pip/pip.conf'
For variant 'user', will try loading '/Users/jpeak/.config/pip/pip.conf'
For variant 'site', will try loading '/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/pip.conf'
I have come up with two statements that can divide positive and negative numbers into integers and fractions without compromising accuracy (bit overflow) and speed.
x = 100.1323 # A number to be divided into integers and fractions
# The two statement to divided a number into integers and fractions
i = int(x) # A positive or negative integer
f = (x*1e17-i*1e17)/1e17 # A positive or negative fraction
E.g. 100.1323
-> 100
, 0.1323
or -100.1323
-> -100
, -0.1323
Speedtest
The performance test shows that the two statements are faster than math.modf
, as long as they are not put into their own function or method.
test.py
:
#!/usr/bin/env python
import math
import cProfile
""" Get the performance of both statements and math.modf. """
X = -100.1323 # The number to be divided into integers and fractions
LOOPS = range(5*10**6) # Number of loops
def scenario_a():
""" The integers (i) and the fractions (f)
come out as integer and float. """
for _ in LOOPS:
i = int(X) # -100
f = (X*1e17-i*1e17)/1e17 # -0.1323
def scenario_b():
""" The integers (i) and the fractions (f)
come out as float.
NOTE: The only difference between this
and math.modf is the accuracy. """
for _ in LOOPS:
i = int(X) # -100
i, f = float(i), (X*1e17-i*1e17)/1e17 # (-100.0, -0.1323)
def scenario_c():
""" Performance test of the statements in a function. """
def modf(x):
i = int(x)
return i, (x*1e17-i*1e17)/1e17
for _ in LOOPS:
i, f = modf(X) # (-100, -0.1323)
def scenario_d():
for _ in LOOPS:
f, i = math.modf(X) # (-100.0, -0.13230000000000075)
def scenario_e():
""" Convert the integer part to real integer. """
for _ in LOOPS:
f, i = math.modf(X) # (-100.0, -0.13230000000000075)
i = int(i) # -100
if __name__ == '__main__':
cProfile.run('scenario_a()')
cProfile.run('scenario_b()')
cProfile.run('scenario_c()')
cProfile.run('scenario_d()')
cProfile.run('scenario_e()')
Output:
4 function calls in 1.312 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 1.312 1.312 <string>:1(<module>)
1 1.312 1.312 1.312 1.312 test.py:10(scenario_a)
1 0.000 0.000 1.312 1.312 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
4 function calls in 1.887 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 1.887 1.887 <string>:1(<module>)
1 1.887 1.887 1.887 1.887 test.py:18(scenario_b)
1 0.000 0.000 1.887 1.887 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
5000004 function calls in 2.797 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 2.797 2.797 <string>:1(<module>)
1 1.261 1.261 2.797 2.797 test.py:27(scenario_c)
5000000 1.536 0.000 1.536 0.000 test.py:31(modf)
1 0.000 0.000 2.797 2.797 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
5000004 function calls in 1.852 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 1.852 1.852 <string>:1(<module>)
1 1.050 1.050 1.852 1.852 test.py:38(scenario_d)
1 0.000 0.000 1.852 1.852 {built-in method builtins.exec}
5000000 0.802 0.000 0.802 0.000 {built-in method math.modf}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
5000004 function calls in 2.467 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 2.467 2.467 <string>:1(<module>)
1 1.652 1.652 2.467 2.467 test.py:42(scenario_e)
1 0.000 0.000 2.467 2.467 {built-in method builtins.exec}
5000000 0.815 0.000 0.815 0.000 {built-in method math.modf}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
NOTE:
The statement can be faster with modulo, but modulo can not be used to split negative numbers into integer and fraction parts.
i, f = int(x), x*1e17%1e17/1e17 # x can not be negative
You can check this question. You can use the View
's post() method.
Reverse the string and check if original string and reverse are same or not
I am the author of the source code at the specified link. While the intention of the source code license is not clear (it will be later today), the code is in fact open and free for use in your free or commercial applications with no strings attached.
//create and fill polygon
CanvasRenderingContext2D.prototype.fillPolygon = function (pointsArray, fillColor, strokeColor) {
if (pointsArray.length <= 0) return;
this.moveTo(pointsArray[0][0], pointsArray[0][1]);
for (var i = 0; i < pointsArray.length; i++) {
this.lineTo(pointsArray[i][0], pointsArray[i][1]);
}
if (strokeColor != null && strokeColor != undefined)
this.strokeStyle = strokeColor;
if (fillColor != null && fillColor != undefined) {
this.fillStyle = fillColor;
this.fill();
}
}
//And you can use this method as
var polygonPoints = [[10,100],[20,75],[50,100],[100,100],[10,100]];
context.fillPolygon(polygonPoints, '#F00','#000');
If you want to see DDL for the objects, you can use
select dbms_metadata.get_ddl('OBJECT_TYPE','OBJECT_NAME','OBJECT_OWNER')
from dual
/
For example this will give you the DDL script for emp
table.
select dbms_metadata.get_ddl('TABLE','EMP','HR')
from dual
/
You may need to set the long
type format to big number. For packages, you need to access dba_source, user_source, all_source
tables. You can query for object name and type to see what code is stored.
head -1000 file.txt > first100lines.txt
tail --lines=+1001 file.txt > restoffile.txt
With JRE 8 on XP there is another way - to use MSI to deploy package.
or (silent way, usable in batch file etc..)
for %%I in ("*.msi") do if exist "%%I" msiexec.exe /i %%I /qn EULA=0 SKIPLICENSE=1 PROG=0 ENDDIALOG=0
I know this question was specific to JavaScript, however, there seems to be no good, clean way to ALWAYS detect when a textarea changes in all current browsers. I've learned jquery has taken care of it for us. It even handles contextual menu changes to text areas. The same syntax is used regardless of input type.
$('div.lawyerList').on('change','textarea',function(){
// Change occurred so count chars...
});
or
$('textarea').on('change',function(){
// Change occurred so count chars...
});
Try this.
CameraManager camManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
String cameraId = null; // Usually front camera is at 0 position.
try {
cameraId = camManager.getCameraIdList()[0];
camManager.setTorchMode(cameraId, true);
} catch (CameraAccessException e) {
e.printStackTrace();
}
The best way for converting to Numpy Array is using '.to_numpy(self, dtype=None, copy=False)'. It is new in version 0.24.0.Refrence
You can also use '.array'.Refrence
Pandas .as_matrix deprecated since version 0.23.0.
You can use COM, or P/Invoke from .Net, to open the Winspool.drv driver and send bytes directly to devices. But you don't want to do that; this typically works only for the one device on the one version of the one driver you test with, and breaks on everything else. Take this from long, painful, personal experience.
What you want to do is get a barcode font or library that draws barcodes using plain old GDI or GDI+ commands; there's one for .Net here. This works on all devices, even after Zebra changes the driver.
Why would you use it if you already knew the class and were going to cast it? Why not just do it the old fashioned way and make the class like you always make it? There's no advantage to this over the way it's done normally. Is there a way to take the text and operate on it thusly:
label1.txt = "Pizza"
Magic(label1.txt) p = new Magic(lablel1.txt)(arg1, arg2, arg3);
p.method1();
p.method2();
If I already know its a Pizza there's no advantage to:
p = (Pizza)somefancyjunk("Pizza"); over
Pizza p = new Pizza();
but I see a huge advantage to the Magic method if it exists.
High resolution timers that provide a resolution of 1 microsecond are system-specific, so you will have to use different methods to achieve this on different OS platforms. You may be interested in checking out the following article, which implements a cross-platform C++ timer class based on the functions described below:
Windows
The Windows API provides extremely high resolution timer functions: QueryPerformanceCounter()
, which returns the current elapsed ticks, and QueryPerformanceFrequency()
, which returns the number of ticks per second.
Example:
#include <stdio.h>
#include <windows.h> // for Windows APIs
int main(void)
{
LARGE_INTEGER frequency; // ticks per second
LARGE_INTEGER t1, t2; // ticks
double elapsedTime;
// get ticks per second
QueryPerformanceFrequency(&frequency);
// start timer
QueryPerformanceCounter(&t1);
// do something
// ...
// stop timer
QueryPerformanceCounter(&t2);
// compute and print the elapsed time in millisec
elapsedTime = (t2.QuadPart - t1.QuadPart) * 1000.0 / frequency.QuadPart;
printf("%f ms.\n", elapsedTime);
}
Linux, Unix, and Mac
For Unix or Linux based system, you can use gettimeofday()
. This function is declared in "sys/time.h".
Example:
#include <stdio.h>
#include <sys/time.h> // for gettimeofday()
int main(void)
{
struct timeval t1, t2;
double elapsedTime;
// start timer
gettimeofday(&t1, NULL);
// do something
// ...
// stop timer
gettimeofday(&t2, NULL);
// compute and print the elapsed time in millisec
elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0; // sec to ms
elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0; // us to ms
printf("%f ms.\n", elapsedTime);
}
To get the value from a textarea with an id you just have to do
Edited
$("#area1").val();
If you are having more than one element with the same id in the document then the HTML is invalid.
From the docs:
"a UNIQUE index permits multiple NULL values for columns that can contain NULL"
This applies to all engines but BDB.
You could also use RegExp
:
function validateEmail(str) {
return new RegExp(/([\w\.\-_]+)?\w+@[\w-_]+(\.\w+){1,}/, 'igm').test(str);
}
See the Regular Expressions guide on MDN for more info.
in addition to all the previous answers, and in case you're wondering how we're going to write dynamic property names in the Future using Computed Property Names ( ECMAScript 6 ), here's how:
var person = "John Doe";
var personId = "person_" + new Date().getTime();
var personIndex = {
[ personId ]: person
// ^ computed property name
};
personIndex[ personId ]; // "John Doe"
reference: Understanding ECMAScript 6 - Nickolas Zakas
By strange it can seem it works perfectly fine: date_create( '2016-02-01 + 1 day' );
echo date_create( $your_date . ' + 1 day' )->format( 'Y-m-d' );
Should do it
You Could also use this.. it works assuming 'yourimage.jpg' is in your public folder.
<img src={'./yourimage.jpg'}/>
You can do this too:
oldIFS="$IFS"
IFS=$'\n' arr=($(<file))
IFS="$oldIFS"
echo "${arr[1]}" # It will print `A Dog`.
Note:
Filename expansion still occurs. For example, if there's a line with a literal *
it will expand to all the files in current folder. So use it only if your file is free of this kind of scenario.
I know this question is a bit old, but, I'm using this code since lot time ago (I've used response from @chris-go), and now, these code are obsolete with PHP 7.2
I'll post an updated version of these code (Credit for the main code are from @bigwebguy, @mike and @chris-go, all of them answers of this question):
/**
* Replaces any parameter placeholders in a query with the value of that
* parameter. Useful for debugging. Assumes anonymous parameters from
* $params are are in the same order as specified in $query
*
* @param string $query The sql query with parameter placeholders
* @param array $params The array of substitution parameters
* @return string The interpolated query
*/
public function interpolateQuery($query, $params) {
$keys = array();
$values = $params;
# build a regular expression for each parameter
foreach ($params as $key => $value) {
if (is_string($key)) {
$keys[] = '/:'.$key.'/';
} else {
$keys[] = '/[?]/';
}
if (is_array($value))
$values[$key] = implode(',', $value);
if (is_null($value))
$values[$key] = 'NULL';
}
// Walk the array to see if we can add single-quotes to strings
array_walk($values, function(&$v, $k) { if (!is_numeric($v) && $v != "NULL") $v = "\'" . $v . "\'"; });
$query = preg_replace($keys, $values, $query, 1, $count);
return $query;
}
Note the change on the code are on array_walk() function, replacing create_function by an anonymous function. This make these good piece of code functional and compatible with PHP 7.2 (and hope future versions too).
There is a built-in method to get the bounding rectangle: Element.getBoundingClientRect
.
The result is the smallest rectangle which contains the entire element, with the read-only left, top, right, bottom, x, y, width, and height properties.
See the example below:
let innerBox = document.getElementById("myDiv").getBoundingClientRect().height;_x000D_
document.getElementById("data_box").innerHTML = "height: " + innerBox;
_x000D_
body {_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
.relative {_x000D_
width: 220px;_x000D_
height: 180px;_x000D_
position: relative;_x000D_
background-color: purple;_x000D_
}_x000D_
_x000D_
.absolute {_x000D_
position: absolute;_x000D_
top: 30px;_x000D_
left: 20px;_x000D_
background-color: orange;_x000D_
padding: 30px;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
#myDiv {_x000D_
margin: 20px;_x000D_
padding: 10px;_x000D_
color: red;_x000D_
font-weight: bold;_x000D_
background-color: yellow;_x000D_
}_x000D_
_x000D_
#data_box {_x000D_
font: 30px arial, sans-serif;_x000D_
}
_x000D_
Get height of <mark>myDiv</mark> in px dimension:_x000D_
<div id="data_box"></div>_x000D_
<div class="relative">_x000D_
<div class="absolute">_x000D_
<div id="myDiv">myDiv</div>_x000D_
</div>_x000D_
</div>
_x000D_
You need to specify it on the methods that can throw the exceptions. You just seperate them with a ',' if it can throw more than 1 type of exception. e.g.
public interface MyInterface {
public MyObject find(int x) throws MyExceptionA,MyExceptionB;
}
A slight improvement to Bizzard's excellent answer. Supports width-offset and/or height-offset on the element, to determine how much will be subtracted from the width/height, and prevents negative dimensions.
<div resize height-offset="260" width-offset="100">
directive:
app.directive('resize', ['$window', function ($window) {
return function (scope, element) {
var w = angular.element($window);
var heightOffset = parseInt(element.attr('height-offset'));
var widthOffset = parseInt(element.attr('width-offset'));
var changeHeight = function () {
if (!isNaN(heightOffset) && w.height() - heightOffset > 0)
element.css('height', (w.height() - heightOffset) + 'px');
if (!isNaN(widthOffset) && w.width() - widthOffset > 0)
element.css('width', (w.width() - widthOffset) + 'px');
};
w.bind('resize', function () {
changeHeight();
});
changeHeight();
}
}]);
Edit This is actually a silly way of doing it in modern browsers. CSS3 has calc, which allows the calculation to be specified in CSS, like this:
#myDiv {
width: calc(100% - 200px);
height: calc(100% - 120px);
}
Send XML requests with the raw
data type, then set the Content-Type to text/xml
.
After creating a request, use the dropdown to change the request type to POST.
Open the Body tab and check the data type for raw.
Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)
Enter your raw XML data into the input field below
Click Send to submit your XML Request to the specified server.
No, filter does not scan the whole stream. It's an intermediate operation, which returns a lazy stream (actually all intermediate operations return a lazy stream). To convince you, you can simply do the following test:
List<Integer> list = Arrays.asList(1, 10, 3, 7, 5);
int a = list.stream()
.peek(num -> System.out.println("will filter " + num))
.filter(x -> x > 5)
.findFirst()
.get();
System.out.println(a);
Which outputs:
will filter 1
will filter 10
10
You see that only the two first elements of the stream are actually processed.
So you can go with your approach which is perfectly fine.
This will not change the default schema in Oracle Sql Developer but I wanted to point out that it is easy to quickly view another user schema, right click the Database Connection:
Select the user to see the schema for that user
the answer is already exist above, but I would like to add some thing.. you can specify the following in your @font-face
@font-face {
font-family: 'Name You Font';
src: url('assets/font/xxyourfontxxx.eot');
src: local('Cera Pro Medium'), local('CeraPro-Medium'),
url('assets/font/xxyourfontxxx.eot?#iefix') format('embedded-opentype'),
url('assets/font/xxyourfontxxx.woff') format('woff'),
url('assets/font/xxyourfontxxx.ttf') format('truetype');
font-weight: 500;
font-style: normal;
}
So you can just indicate your fontfamily name that you already choosed
NOTE: the font-weight and font-style depend on your .woff .ttf ... files
One can achieve this using one's browser console and running
fetch('https://api.github.com/repos/[USERNAME]/[REPO]')
.then(v => v.json()).then((function(v){
console.log(v['size'] + "KB")
})
)
Let's consider a practical example.
Assuming one wants to find the size of this repo using Firefox.
Open the console with Ctrl
+Shift
+K
.
Then paste the following code
fetch('https://api.github.com/repos/goncaloperes/TimeSeries')
.then(v => v.json()).then((function(v){
console.log(v['size'] + "KB")
})
)
Press enter and one will receive the size of the repo as one can see in the image bellow.
I want to share a simple approach for downloading files with JavaScript (ES6), React and a Spring Boot backend:
- Spring boot Rest Controller
Resource from org.springframework.core.io.Resource
@SneakyThrows
@GetMapping("/files/{filename:.+}/{extraVariable}")
@ResponseBody
public ResponseEntity<Resource> serveFile(@PathVariable String filename, @PathVariable String extraVariable) {
Resource file = storageService.loadAsResource(filename, extraVariable);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
.body(file);
}
- React, API call using AXIOS
Set the responseType to arraybuffer to specify the type of data contained in the response.
export const DownloadFile = (filename, extraVariable) => {
let url = 'http://localhost:8080/files/' + filename + '/' + extraVariable;
return axios.get(url, { responseType: 'arraybuffer' }).then((response) => {
return response;
})};
Final step > downloading
with the help of js-file-download you can trigger browser to save data to file as if it was downloaded.
DownloadFile('filename.extension', 'extraVariable').then(
(response) => {
fileDownload(response.data, filename);
}
, (error) => {
// ERROR
});
In 2012 OData underwent standardization, so I'll just add an update here..
First the definitions:
REST - is an architecture of how to send messages over HTTP.
OData V4- is a specific implementation of REST, really defines the content of the messages in different formats (currently I think is AtomPub and JSON). ODataV4 follows rest principles.
For example, asp.net people will mostly use WebApi controller to serialize/deserialize objects into JSON and have javascript do something with it. The point of Odata is being able to query directly from the URL with out-of-the-box options.
You can get current href value by this code:
$(this).attr("href");
To get href value by ID
$("#mylink").attr("href");
This is how you can create a beautiful button with a bezel and rounded edges:
loginButton = UIButton(frame: CGRectMake(self.view.bounds.origin.x + (self.view.bounds.width * 0.325), self.view.bounds.origin.y + (self.view.bounds.height * 0.8), self.view.bounds.origin.x + (self.view.bounds.width * 0.35), self.view.bounds.origin.y + (self.view.bounds.height * 0.05)))
loginButton.layer.cornerRadius = 18.0
loginButton.layer.borderWidth = 2.0
loginButton.backgroundColor = UIColor.whiteColor()
loginButton.layer.borderColor = UIColor.whiteColor().CGColor
loginButton.setTitle("Login", forState: UIControlState.Normal)
loginButton.setTitleColor(UIColor(red: 24.0/100, green: 116.0/255, blue: 205.0/205, alpha: 1.0), forState: UIControlState.Normal)
Here is a way to check is virtualization is enabled or disabled by the firmware as suggested by this link in parallels.com.
How to check that Intel VT-x is supported in CPU:
Open Terminal application from Application/Utilities
Copy/paste command bellow
sysctl -a | grep machdep.cpu.features
Mac:~ user$ sysctl -a | grep machdep.cpu.features
kern.exec: unknown type returned
machdep.cpu.features: FPU VME DE PSE TSC MSR PAE MCE CX8 APIC SEP MTRR PGE MCA CMOV PAT CLFSH DS ACPI MMX FXSR SSE SSE2 SS HTT TM SSE3 MON VMX EST TM2 TPR PDCM
If you see VMX entry then CPU supports Intel VT-x feature, but it still may be disabled.
Refer to this link on Apple.com to enable hardware support for virtualization:
The simple way to solve the problem is to use ComparisonChain from Guava http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ComparisonChain.html
private static Comparator<String> stringAlphabeticalComparator = new Comparator<String>() {
public int compare(String str1, String str2) {
return ComparisonChain.start().
compare(str1,str2, String.CASE_INSENSITIVE_ORDER).
compare(str1,str2).
result();
}
};
Collections.sort(list, stringAlphabeticalComparator);
The first comparator from the chain will sort strings according to the case insensitive order, and the second comparator will sort strings according to the case insensitive order. As excepted strings appear in the result according to the alphabetical order:
"AA","Aa","aa","Development","development"
have also a site where base - tag is used, and the problem described occured. ( after upgrading jquery ), was able to fix it by having tab urls like this:
<li><a href="{$smarty.server.REQUEST_URI}#tab_1"></li>
this makes them "local"
references i used:
http://bugs.jqueryui.com/ticket/7822 http://htmlhelp.com/reference/html40/head/base.html http://tjvantoll.com/2013/02/17/using-jquery-ui-tabs-with-the-base-tag/
I too experienced the same issues with the border formatting not being shown using entrophy's code but a few little fixes and now the table is expandable and displays all css styling rules you may add.
to css add:
#maintable{width: 100%}
then here is the new javascript:
function moveScroll(){
var scroll = $(window).scrollTop();
var anchor_top = $("#maintable").offset().top;
var anchor_bottom = $("#bottom_anchor").offset().top;
if (scroll > anchor_top && scroll < anchor_bottom) {
clone_table = $("#clone");
if(clone_table.length === 0) {
clone_table = $("#maintable").clone();
clone_table.attr({id: "clone"})
.css({
position: "fixed",
"pointer-events": "none",
top:0
})
.width($("#maintable").width());
$("#table-container").append(clone_table);
// dont hide the whole table or you lose border style &
// actively match the inline width to the #maintable width if the
// container holding the table (window, iframe, div) changes width
$("#clone").width($("#maintable").width());
// only the clone thead remains visible
$("#clone thead").css({
visibility:"visible"
});
// clone tbody is hidden
$("#clone tbody").css({
visibility:"hidden"
});
// add support for a tfoot element
// and hide its cloned version too
var footEl = $("#clone tfoot");
if(footEl.length){
footEl.css({
visibility:"hidden"
});
}
}
}
else {
$("#clone").remove();
}
}
$(window).scroll(moveScroll);
Declare a global var:
var td
Then select your guiena pig <td>
getting it by its id
, if you want to change all of them then
window.onload = function () {
td = document.getElementsByTagName("td");
}
Make a function to be triggered and a loop to change all of your desired td
's
function trigger() {
for(var x = 0; x < td.length; x++) {
td[x].className = "yournewclass";
}
}
Go to your CSS Sheet:
.yournewclass:hover { background-color: #00ff00; }
And that is it, with this you are able to to make all your <td>
tags get a background-color: #00ff00;
when hovered by changing its css propriety directly (switching between css classes).
If you would like it to go back to first option try this:
document.getElementById("select").selectedIndex = 0;
For anyone running Windows 10 1607 and looking for .net 4.7. Disregard all of the above.
It's not in the Registry, C:\Windows\Microsoft.NET folder or the Installed Programs list or the WMIC display of that same list.
Look for "installed updates" KB3186568.
That's pretty much all you need:
mysql> select * from t;
+------+-------+
| id | data |
+------+-------+
| 1 | max |
| 2 | linda |
| 3 | sam |
| 4 | henry |
+------+-------+
4 rows in set (0.02 sec)
mysql> update t set data=concat(data, 'a');
Query OK, 4 rows affected (0.01 sec)
Rows matched: 4 Changed: 4 Warnings: 0
mysql> select * from t;
+------+--------+
| id | data |
+------+--------+
| 1 | maxa |
| 2 | lindaa |
| 3 | sama |
| 4 | henrya |
+------+--------+
4 rows in set (0.00 sec)
Not sure why you'd be having trouble, though I am testing this on 5.1.41
Actually I wanted same alike thing, To get one year backward date, for a given date! :-)
With the hint of above answer from @mohammad mohsenipur I got to the following link, via his given link!
Luckily, there is a method same as date_add method, named date_sub method! :-) I do the following to get done what I wanted!
$date = date_create('2000-01-01');
date_sub($date, date_interval_create_from_date_string('1 years'));
echo date_format($date, 'Y-m-d');
Hopes this answer will help somebody too! :-)
Good luck guys!
StringUtils is a utility class from Apache commons-lang (many libraries have it but this is the most common library). You need to download the jar and add it to your applications classpath.
Assuming the MyEjbProject is not another Maven Project you own or want to build with maven, you could use system dependencies to link to the existing jar file of the project like so
<project>
...
<dependencies>
<dependency>
<groupId>yourgroup</groupId>
<artifactId>myejbproject</artifactId>
<version>2.0</version>
<scope>system</scope>
<systemPath>path/to/myejbproject.jar</systemPath>
</dependency>
</dependencies>
...
</project>
That said it is usually the better (and preferred way) to install the package to the repository either by making it a maven project and building it or installing it the way you already seem to do.
If they are, however, dependent on each other, you can always create a separate parent project (has to be a "pom" project) declaring the two other projects as its "modules". (The child projects would not have to declare the third project as their parent). As a consequence you'd get a new directory for the new parent project, where you'd also quite probably put the two independent projects like this:
parent
|- pom.xml
|- MyEJBProject
| `- pom.xml
`- MyWarProject
`- pom.xml
The parent project would get a "modules" section to name all the child modules. The aggregator would then use the dependencies in the child modules to actually find out the order in which the projects are to be built)
<project>
...
<artifactId>myparentproject</artifactId>
<groupId>...</groupId>
<version>...</version>
<packaging>pom</packaging>
...
<modules>
<module>MyEJBModule</module>
<module>MyWarModule</module>
</modules>
...
</project>
That way the projects can relate to each other but (once they are installed in the local repository) still be used independently as artifacts in other projects
Finally, if your projects are not in related directories, you might try to give them as relative modules:
filesystem
|- mywarproject
| `pom.xml
|- myejbproject
| `pom.xml
`- parent
`pom.xml
now you could just do this (worked in maven 2, just tried it):
<!--parent-->
<project>
<modules>
<module>../mywarproject</module>
<module>../myejbproject</module>
</modules>
</project>
If you don't want to modify the registry or app.config files, an alternate way is to create a simple .NET 4 console app that mimicks what PowerShell.exe does and hosts the PowerShell ConsoleShell.
See Option 2 – Hosting Windows PowerShell yourself
First, add a reference to the System.Management.Automation and Microsoft.PowerShell.ConsoleHost assemblies which can be found under %programfiles%\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0
Then use the following code:
using System;
using System.Management.Automation.Runspaces;
using Microsoft.PowerShell;
namespace PSHostCLRv4
{
class Program
{
static int Main(string[] args)
{
var config = RunspaceConfiguration.Create();
return ConsoleShell.Start(
config,
"Windows PowerShell - Hosted on CLR v4\nCopyright (C) 2010 Microsoft Corporation. All rights reserved.",
"",
args
);
}
}
}
On a 64-bit system you have to make sure that both the Tomcat application and the JDK are the same architecture: either both are x86 or x64.
In case you want to change the Tomcat instance to x64 you might have to download the tomcat8.exe
or tomcat9.exe
and the tcnative-1.dll
with the appropriate x64 versions. You can get those at http://svn.apache.org/viewvc/tomcat/.
Alternatively you can point Tomcat to the x86 JDK by changing the Java Virtual Machine path in the Tomcat config.
Second Largest in O(n/2)
public class SecMaxNum {
// second Largest number with O(n/2)
/**
* @author Rohan Kamat
* @Date Feb 04, 2016
*/
public static void main(String[] args) {
int[] input = { 1, 5, 10, 11, 11, 4, 2, 8, 1, 8, 9, 8 };
int large = 0, second = 0;
for (int i = 0; i < input.length - 1; i = i + 2) {
// System.out.println(i);
int fist = input[i];
int sec = input[i + 1];
if (sec >= fist) {
int temp = fist;
fist = sec;
sec = temp;
}
if (fist >= second) {
if (fist >= large) {
large = fist;
} else {
second = fist;
}
}
if (sec >= second) {
if (sec >= large) {
large = sec;
} else {
second = sec;
}
}
}
}
}
Statement stmt3 = con.createStatement();
ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) AS count FROM "+lastTempTable+" ;");
count = rs3.getInt("count");
In my case, I was looking for a solution that allows one of the navbar items to be right aligned. In order to do this, you must add style="width:100%;"
to the <ul class="navbar-nav">
and then add the ml-auto
class to your navbar item.
The MySQL extension is the oldest of the three and was the original way that developers used to communicate with MySQL. This extension is now being deprecated in favor of the other two alternatives because of improvements made in newer releases of both PHP and MySQL.
MySQLi is the 'improved' extension for working with MySQL databases. It takes advantage of features that are available in newer versions of the MySQL server, exposes both a function-oriented and an object-oriented interface to the developer and a does few other nifty things.
PDO offers an API that consolidates most of the functionality that was previously spread across the major database access extensions, i.e. MySQL, PostgreSQL, SQLite, MSSQL, etc. The interface exposes high-level objects for the programmer to work with database connections, queries and result sets, and low-level drivers perform communication and resource handling with the database server. A lot of discussion and work is going into PDO and it’s considered the appropriate method of working with databases in modern, professional code.
import pandas as pd
print(pd.json_normalize(your_json))
This will Normalize semi-structured JSON data into a flat table
Output
FirstName LastName MiddleName password username
John Mark Lewis 2910 johnlewis2
If you need an asynchronous-friendly version of Array.forEach
and similar, they're available in the Node.js 'async' module: http://github.com/caolan/async ...as a bonus this module also works in the browser.
async.each(openFiles, saveFile, function(err){
// if any of the saves produced an error, err would equal that error
});
I just ran the following command:
php artisan passport:install
I was using passport to run my application completely based on API's and Vue.js. Laravel worked fine but everytime i tried to login via my API i would get the error. After running the command and updating the client_id and client_secret on my Laravel files then pushed the new updates to the live server, the problem was solved. In my user model i have a script as follows:
public function generateToken($request)
{
$http = new \GuzzleHttp\Client();
$response = $http->post(URL::to('/').'/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => '6',
'client_secret' => 'x3yhgWVqF8sSaMev4JI3yvsVxfbgkfRJmqzlpiMQ',
'username' => $this->email,
'password' => $request->input('password'),
'scope' => '',
],
]);
// Lets get an array instead of a stdObject so that we can return without errors
$response = json_decode($response->getBody(), true);
return oq_api_notify([
'auth' => $response, // API ACCESS TOKEN
'user' => $this->load(['settings'])->toArray(),
], 201);
}
I just updated the client_id and client_secret only then saved. Since the passport command gives you two client keys:
1) Personal access client (client_id & client_secret)
2) Password grant client (client_id & client_secret)
I used the Password grant client. Hopes this helps someone out there :)
How about converting to lowercase first? you can use string.lower()
.
Use another flex container to fix the min-height
issue in IE10 and IE11:
HTML
<div class="ie-fixMinHeight">
<div id="page">
<div id="header"></div>
<div id="content"></div>
<div id="footer"></div>
</div>
</div>
CSS
.ie-fixMinHeight {
display:flex;
}
#page {
min-height:100vh;
width:100%;
display:flex;
flex-direction:column;
}
#content {
flex-grow:1;
}
See a working demo.
body
because it
screws up elements inserted via jQuery plugins (autocomplete, popup,
etc.).height:100%
or height:100vh
on your container because the footer will stick at the bottom of window and won't adapt to long content.flex-grow:1
rather than flex:1
cause IE10 and IE11 default values for flex
are 0 0 auto
and not 0 1 auto
.The accepted answer is correct, but I prefer:
@{int count = 0;}
@foreach (var item in Model.Resources)
{
@Html.Raw(count <= 3 ? "<div class=\"resource-row\">" : "")
// some code
@Html.Raw(count <= 3 ? "</div>" : "")
@(count++)
}
I hope this inspires someone, even though I'm late to the party.
I think you are not configured properly,
if you are using XAMPP then you can easily send mail from localhost.
for example you can configure C:\xampp\php\php.ini
and c:\xampp\sendmail\sendmail.ini
for gmail to send mail.
in C:\xampp\php\php.ini
find extension=php_openssl.dll
and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.
in php.ini file find [mail function]
and change
SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"
(use the above send mail path only and it will work)
Now Open C:\xampp\sendmail\sendmail.ini
. Replace all the existing code in sendmail.ini with following code
[sendmail]
smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]
Now you have done!! create php file with mail function and send mail from localhost.
Update
First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()
).
You can set the following settings in your PHP.ini:
ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");
private async void Ping_Click(object sender, RoutedEventArgs e)
{
Ping pingSender = new Ping();
string host = @"stackoverflow.com";
await Task.Run(() =>{
PingReply reply = pingSender.Send(host);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine("Address: {0}", reply.Address.ToString());
Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
}
else
{
Console.WriteLine("Address: {0}", reply.Status);
}
});
}
This should do it:
SELECT report_id, computer_id, date_entered
FROM reports AS a
WHERE date_entered = (
SELECT MAX(date_entered)
FROM reports AS b
WHERE a.report_id = b.report_id
AND a.computer_id = b.computer_id
)
You can give it a property display block; so it will behave like a div and have its own line
CSS:
.feature_desc {
display: block;
....
}
No, you can't control the animation of the images.
You would need two versions of each image, one that is animated, and one that's not. On hover you can easily change from one image to another.
Example:
$(function(){
$('img').each(function(e){
var src = $(e).attr('src');
$(e).hover(function(){
$(this).attr('src', src.replace('.gif', '_anim.gif'));
}, function(){
$(this).attr('src', src);
});
});
});
Time goes by, and possibilities change. As kritzikatzi pointed out, having two versions of the image is not the only option, you can apparently use a canvas element to create a copy of the first frame of the animation. Note that this doesn't work in all browsers, IE 8 for example doesn't support the canvas element.
Either modify the pattern beforehand so that it only matches the entire string:
var r = /^a$/
or check afterward whether the pattern matched the whole string:
function matchExact(r, str) {
var match = str.match(r);
return match && str === match[0];
}
Following line in above code is not working
DB_PASSWORD=$(eval echo ${DB_PASSWORD} | base64 --decode)
Correct line is:
DB_PASSWORD=`echo $PASSWORD|base64 -d`
And save the password in other file as PASSWORD.
Yes, Daniel is correct, but to expand upon his answer, your primary app component would need to have a navbar component within it. That way, when you render the primary app (any page under the '/' path), it would also display the navbar. I am guessing that you wouldn't want your login page to display the navbar, so that shouldn't be a nested component, and should instead be by itself. So your routes would end up looking something like this:
<Router>
<Route path="/" component={App}>
<Route path="page1" component={Page1} />
<Route path="page2" component={Page2} />
</Route>
<Route path="/login" component={Login} />
</Router>
And the other components would look something like this:
var NavBar = React.createClass({
render() {
return (
<div>
<ul>
<a onClick={() => history.push('page1') }>Page 1</a>
<a onClick={() => history.push('page2') }>Page 2</a>
</ul>
</div>
)
}
});
var App = React.createClass({
render() {
return (
<div>
<NavBar />
<div>Other Content</div>
{this.props.children}
</div>
)
}
});
You can simply use
document.getElementById("elementID").outerHTML="";
It works in all browsers, even on Internet Explorer.
Very simple: no color, no opacity:
rgba(0, 0, 0, 0);
If you want to search for documents that belong to a specific month, make sure to query like this:
// Anything greater than this month and less than the next month
db.posts.find({created_on: {$gte: new Date(2015, 6, 1), $lt: new Date(2015, 7, 1)}});
Avoid quering like below as much as possible.
// This may not find document with date as the last date of the month
db.posts.find({created_on: {$gte: new Date(2015, 6, 1), $lt: new Date(2015, 6, 30)}});
// don't do this too
db.posts.find({created_on: {$gte: new Date(2015, 6, 1), $lte: new Date(2015, 6, 30)}});
use:
NSLog(@"%f",[[UIScreen mainScreen] bounds].size.width) ;
Take the width of the table and divide it by the number of cell ().
PerformanceTable {width:500px;}
PerformanceTable.td {width:100px;}
If the table dynamically widens or shrinks you could dynamically increase the cell size with a little javascript.
If you're on Windows then it's a total no-brainer: Get Visual C++ Express.
Sharing my case, hope that will help.
In my situation inside MY_PROJ.Database->MY_PROJ.Database.sqlproj
I had to put this:
<Build Include="dbo\Tables\MyTableGeneratingScript.sql" />
I always advocate Joda-time. Here's why.
EDIT: The Java date/time classes introduced with Java 8 are now the preferred solution, if you can migrate to Java 8
You need to login to your mysql terminal first using
mysql -u username -p password
Then use this:
SELECT @@sql_mode; or SELECT @@GLOBAL.sql_mode;
output will be like this:
STRICT_TRANS_TABLES,STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,TRADITIONAL,NO_AUTO_CREATE_USER,NO_ENGINE_SUB
You can also set sql mode by this:
SET GLOBAL sql_mode=TRADITIONAL;
This is supposed to print the ASCII value of the character, as %d
is the escape sequence for an integer. So the value given as argument of printf
is taken as integer when printed.
char ch = 'a';
printf("%d", ch);
Same holds for printf("%d", '\0');
, where the NULL character is interpreted as the 0 integer.
Finally, sizeof('\n')
is 4 because in C, this notation for characters stands for the corresponding ASCII integer. So '\n' is the same as 10 as an integer.
It all depends on the interpretation you give to the bytes.
A quick and simple solution is for the AndroidManifest.xml file, add the following for each activity that you wish to force to landscape mode:
android:screenOrientation="landscape"
Looks like you've got some answers to this, however I think there is something worth mentioning here that will greatly simplify your code. jQuery introduced the $.when
in v1.5. It looks like:
$.when($.ajax(...), $.ajax(...)).then(function (resp1, resp2) {
//this callback will be fired once all ajax calls have finished.
});
Didn't see it mentioned here, hope it helps.
You can simply place multiple name together separated by a white space like
C:\Users\Dell>pip install markdown django-filter
#c:\Users\Dell is path in my pc this can be anything on yours
this installed markdown and django-filter on my device.
A view helps us in get rid of utilizing database space all the time. If you create a table it is stored in database and holds some space throughout its existence. Instead view is utilized when a query runs hence saving the db space. And we cannot create big tables all the time joining different tables though we could but its depends how big the table is to save the space. So view just temporarily create a table with joining different table at the run time. Experts,Please correct me if I am wrong.
angular.module('myapp', ['myapp.filters', 'myapp.services', 'myapp.directives']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/page/:name*', {
templateUrl: function(urlattr){
return '/pages/' + urlattr.name + '.html';
},
controller: 'CMSController'
});
}
]);
From the docs (1.3.0):
"If templateUrl is a function, it will be called with the following parameters:
{Array.} - route parameters extracted from the current $location.path() by applying the current route"
Also
when(path, route) : Method
- path can contain named groups starting with a colon and ending with a star: e.g.:name*. All characters are eagerly stored in $routeParams under the given name when the route matches.
Assuming a C-style array a
of size N
, with elements of a type implicitly convertible from 0
, the following sets all the elements to values constructed from 0
.
std::fill(a, a+N, 0);
Note that this is not the same as "emptying" or "clearing".
Edit: Following james Kanze's suggestion, in C++11 you could use the more idiomatic alternative
std::fill( std::begin( a ), std::end( a ), 0 );
In the absence of C++11, you could roll out your own solution along these lines:
template <typename T, std::size_t N> T* end_(T(&arr)[N]) { return arr + N; }
template <typename T, std::size_t N> T* begin_(T(&arr)[N]) { return arr; }
std::fill( begin_( a ), end_( a ), 0 );
Here's some simple code to add a time out to your recv
function using poll
in C:
struct pollfd fd;
int ret;
fd.fd = mySocket; // your socket handler
fd.events = POLLIN;
ret = poll(&fd, 1, 1000); // 1 second for timeout
switch (ret) {
case -1:
// Error
break;
case 0:
// Timeout
break;
default:
recv(mySocket,buf,sizeof(buf), 0); // get your data
break;
}
Renders a view and sends the rendered HTML string to the client.
res.render('index');
Or
res.render('index', function(err, html) {
if(err) {...}
res.send(html);
});
DOCS HERE: https://expressjs.com/en/api.html#res.render
I feel compelled to provide a counterpoint to Ashwini Chaudhary's answer. Despite appearances, the two-argument form of the round
function does not round a Python float to a given number of decimal places, and it's often not the solution you want, even when you think it is. Let me explain...
The ability to round a (Python) float to some number of decimal places is something that's frequently requested, but turns out to be rarely what's actually needed. The beguilingly simple answer round(x, number_of_places)
is something of an attractive nuisance: it looks as though it does what you want, but thanks to the fact that Python floats are stored internally in binary, it's doing something rather subtler. Consider the following example:
>>> round(52.15, 1)
52.1
With a naive understanding of what round
does, this looks wrong: surely it should be rounding up to 52.2
rather than down to 52.1
? To understand why such behaviours can't be relied upon, you need to appreciate that while this looks like a simple decimal-to-decimal operation, it's far from simple.
So here's what's really happening in the example above. (deep breath) We're displaying a decimal representation of the nearest binary floating-point number to the nearest n
-digits-after-the-point decimal number to a binary floating-point approximation of a numeric literal written in decimal. So to get from the original numeric literal to the displayed output, the underlying machinery has made four separate conversions between binary and decimal formats, two in each direction. Breaking it down (and with the usual disclaimers about assuming IEEE 754 binary64 format, round-ties-to-even rounding, and IEEE 754 rules):
First the numeric literal 52.15
gets parsed and converted to a Python float. The actual number stored is 7339460017730355 * 2**-47
, or 52.14999999999999857891452847979962825775146484375
.
Internally as the first step of the round
operation, Python computes the closest 1-digit-after-the-point decimal string to the stored number. Since that stored number is a touch under the original value of 52.15
, we end up rounding down and getting a string 52.1
. This explains why we're getting 52.1
as the final output instead of 52.2
.
Then in the second step of the round
operation, Python turns that string back into a float, getting the closest binary floating-point number to 52.1
, which is now 7332423143312589 * 2**-47
, or 52.10000000000000142108547152020037174224853515625
.
Finally, as part of Python's read-eval-print loop (REPL), the floating-point value is displayed (in decimal). That involves converting the binary value back to a decimal string, getting 52.1
as the final output.
In Python 2.7 and later, we have the pleasant situation that the two conversions in step 3 and 4 cancel each other out. That's due to Python's choice of repr
implementation, which produces the shortest decimal value guaranteed to round correctly to the actual float. One consequence of that choice is that if you start with any (not too large, not too small) decimal literal with 15 or fewer significant digits then the corresponding float will be displayed showing those exact same digits:
>>> x = 15.34509809234
>>> x
15.34509809234
Unfortunately, this furthers the illusion that Python is storing values in decimal. Not so in Python 2.6, though! Here's the original example executed in Python 2.6:
>>> round(52.15, 1)
52.200000000000003
Not only do we round in the opposite direction, getting 52.2
instead of 52.1
, but the displayed value doesn't even print as 52.2
! This behaviour has caused numerous reports to the Python bug tracker along the lines of "round is broken!". But it's not round
that's broken, it's user expectations. (Okay, okay, round
is a little bit broken in Python 2.6, in that it doesn't use correct rounding.)
Short version: if you're using two-argument round, and you're expecting predictable behaviour from a binary approximation to a decimal round of a binary approximation to a decimal halfway case, you're asking for trouble.
So enough with the "two-argument round is bad" argument. What should you be using instead? There are a few possibilities, depending on what you're trying to do.
If you're rounding for display purposes, then you don't want a float result at all; you want a string. In that case the answer is to use string formatting:
>>> format(66.66666666666, '.4f')
'66.6667'
>>> format(1.29578293, '.6f')
'1.295783'
Even then, one has to be aware of the internal binary representation in order not to be surprised by the behaviour of apparent decimal halfway cases.
>>> format(52.15, '.1f')
'52.1'
If you're operating in a context where it matters which direction decimal halfway cases are rounded (for example, in some financial contexts), you might want to represent your numbers using the Decimal
type. Doing a decimal round on the Decimal
type makes a lot more sense than on a binary type (equally, rounding to a fixed number of binary places makes perfect sense on a binary type). Moreover, the decimal
module gives you better control of the rounding mode. In Python 3, round
does the job directly. In Python 2, you need the quantize
method.
>>> Decimal('66.66666666666').quantize(Decimal('1e-4'))
Decimal('66.6667')
>>> Decimal('1.29578293').quantize(Decimal('1e-6'))
Decimal('1.295783')
In rare cases, the two-argument version of round
really is what you want: perhaps you're binning floats into bins of size 0.01
, and you don't particularly care which way border cases go. However, these cases are rare, and it's difficult to justify the existence of the two-argument version of the round
builtin based on those cases alone.
The post needs an update after the links
option is deprecated.
Basically, links
is no longer needed because its main purpose, making container reachable by another by adding environment variable, is included implicitly with network
. When containers are placed in the same network, they are reachable by each other using their container name and other alias as host.
For docker run
, --link
is also deprecated and should be replaced by a custom network.
docker network create mynet
docker run -d --net mynet --name container1 my_image
docker run -it --net mynet --name container1 another_image
depends_on
expresses start order (and implicitly image pulling order), which was a good side effect of links
.
Using the .loc[] accessor:
In [25]: a.loc[a['c1'] == 8].index[0]
Out[25]: 4
Can also use the get_loc() by setting 'c1' as the index. This will not change the original dataframe.
In [17]: a.set_index('c1').index.get_loc(8)
Out[17]: 4
GetType()
exists on every single framework type, because it is defined on the base object
type. So, regardless of the type itself, you can use it to return the underlying Type
So, all you need to do is:
u.GetType() == t
I think this is the problem
A little background
Traceview is a graphical viewer for execution logs that you create by using the Debug class to log tracing information in your code. Traceview can help you debug your application and profile its performance. Enabling it creates a .trace
file in the sdcard root folder which can then be extracted by ADB and processed by traceview bat file for processing. It also can get added by the DDMS.
It is a system used internally by the logger. In general unless you are using traceview to extract the trace file this error shouldnt bother you. You should look at error/logs directly related to your application
How do I enable it:
There are two ways to generate trace logs:
Include the Debug class in your code and call its methods such as
startMethodTracing()
andstopMethodTracing()
, to start and stop logging of trace information to disk. This option is very precise because you can specify exactly where to start and stop logging trace data in your code.Use the method profiling feature of DDMS to generate trace logs. This option is less precise because you do not modify code, but rather specify when to start and stop logging with DDMS. Although you have less control on exactly where logging starts and stops, this option is useful if you don't have access to the application's code, or if you do not need precise log timing.
But the following restrictions exist for the above
If you are using the Debug class, your application must have permission to write to external storage (
WRITE_EXTERNAL_STORAGE
).If you are using DDMS: Android 2.1 and earlier devices must have an SD card present and your application must have permission to write to the SD card. Android 2.2 and later devices do not need an SD card. The trace log files are streamed directly to your development machine.
So in essence the traceFile access requires two things
1.) Permission to write a trace log file i.e.
WRITE_EXTERNAL_STORAGE
andREAD_EXTERNAL_STORAGE
for good measure2.) An emulator with an SDCard attached with sufficient space. The doc doesnt say if this is only for DDMS but also for debug, so I am assuming this is also true for debugging via the application.
What do I do with this error:
Now the error is essentially a fall out of either not having the sdcard path to create a tracefile or not having permission to access it. This is an old thread, but the dev behind the bounty, check if are meeting the two prerequisites. You can then go search for the .trace
file in the sdcard folder in your emulator. If it exists it shouldn't be giving you this problem, if it doesnt try creating it by adding the startMethodTracing
to your app.
I'm not sure why it automatically looks for this file when the logger kicks in. I think when an error/log event occurs , the logger internally tries to write to trace file and does not find it, in which case it throws the error.Having scoured through the docs, I don't find too many references to why this is automatically on.
But in general this doesn't affect you directly, you should check direct application logs/errors.
Also as an aside Android 2.2 and later devices do not need an SD card for DDMS trace logging. The trace log files are streamed directly to your development machine.
Additional information on Traceview:
Copying Trace Files to a Host Machine
After your application has run and the system has created your trace files .trace on a device or emulator, you must copy those files to your development computer. You can use adb pull to copy the files. Here's an example that shows how to copy an example file, calc.trace, from the default location on the emulator to the /tmp directory on the emulator host machine:
adb pull /sdcard/calc.trace /tmp Viewing Trace Files in Traceview To run Traceview and view the trace files, enter traceview . For example, to run Traceview on the example files copied in the previous section, use:
traceview /tmp/calc Note: If you are trying to view the trace logs of an application that is built with ProGuard enabled (release mode build), some method and member names might be obfuscated. You can use the Proguard mapping.txt file to figure out the original unobfuscated names. For more information on this file, see the Proguard documentation.
I think any other answer regarding positioning of oncreate
statements or removing uses-sdk
are not related, but this is Android and I could be wrong. Would be useful to redirect this question to an android engineer or post it as a bug
More in the docs
After a some research i found the way to bypass ssl error Trust anchor for certification path not found. This might be not a good way to do but you can use it for a testing purpose.
private HttpsURLConnection httpsUrlConnection( URL urlDownload) throws Exception {
HttpsURLConnection connection=null;
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@SuppressLint("TrustAllX509TrustManager")
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@SuppressLint("TrustAllX509TrustManager")
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
SSLContext sc = SSLContext.getInstance("SSL"); // Add in try catch block if you get error.
sc.init(null, trustAllCerts, new java.security.SecureRandom()); // Add in try catch block if you get error.
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier usnoHostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
SSLSocketFactory sslSocketFactory = sc.getSocketFactory();
connection = (HttpsURLConnection) urlDownload.openConnection();
connection.setHostnameVerifier(usnoHostnameVerifier);
connection.setSSLSocketFactory(sslSocketFactory);
return connection;
}
Use following in your CSS
div {
-webkit-transform: rotate(90deg); /* Safari and Chrome */
-moz-transform: rotate(90deg); /* Firefox */
-ms-transform: rotate(90deg); /* IE 9 */
-o-transform: rotate(90deg); /* Opera */
transform: rotate(90deg);
}
My solution was to switch all datetime columns to datetime2, and use datetime2 for any new columns. In other words make EF use datetime2 by default. Add this to the OnModelCreating method on your context:
modelBuilder.Properties<DateTime>().Configure(c => c.HasColumnType("datetime2"));
That will get all the DateTime and DateTime? properties on all your entities.
Prior to adding the Ajax.BeginForm. Add below scripts to your project in the order mentioned,
Only these two are enough for performing Ajax operation.
Extending from the correct answer of Andrey-Egorov using .executeScript()
to conclude my own question example:
inputField = driver.findElement(webdriver.By.id('gbqfq'));
driver.executeScript("arguments[0].setAttribute('value', '" + longstring +"')", inputField);
Step-1: Your Model class
public class RechargeMobileViewModel
{
public string CustomerFullName { get; set; }
public string TelecomSubscriber { get; set; }
public int TotalAmount { get; set; }
public string MobileNumber { get; set; }
public int Month { get; set; }
public List<SelectListItem> getAllDaysList { get; set; }
// Define the list which you have to show in Drop down List
public List<SelectListItem> getAllWeekDaysList()
{
List<SelectListItem> myList = new List<SelectListItem>();
var data = new[]{
new SelectListItem{ Value="1",Text="Monday"},
new SelectListItem{ Value="2",Text="Tuesday"},
new SelectListItem{ Value="3",Text="Wednesday"},
new SelectListItem{ Value="4",Text="Thrusday"},
new SelectListItem{ Value="5",Text="Friday"},
new SelectListItem{ Value="6",Text="Saturday"},
new SelectListItem{ Value="7",Text="Sunday"},
};
myList = data.ToList();
return myList;
}
}
Step-2: Call this method to fill Drop down in your controller Action
namespace MvcVariousApplication.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
RechargeMobileViewModel objModel = new RechargeMobileViewModel();
objModel.getAllDaysList = objModel.getAllWeekDaysList();
return View(objModel);
}
}
}
Step-3: Fill your Drop-Down List of View as follows
@model MvcVariousApplication.Models.RechargeMobileViewModel
@{
ViewBag.Title = "Contact";
}
@Html.LabelFor(model=> model.CustomerFullName)
@Html.TextBoxFor(model => model.CustomerFullName)
@Html.LabelFor(model => model.MobileNumber)
@Html.TextBoxFor(model => model.MobileNumber)
@Html.LabelFor(model => model.TelecomSubscriber)
@Html.TextBoxFor(model => model.TelecomSubscriber)
@Html.LabelFor(model => model.TotalAmount)
@Html.TextBoxFor(model => model.TotalAmount)
@Html.LabelFor(model => model.Month)
@Html.DropDownListFor(model => model.Month, new SelectList(Model.getAllDaysList, "Value", "Text"), "-Select Day-")
Since JSF 2.3 all the bean scopes defined in package javax.faces.bean
package have been deprecated to align the scopes with CDI. Moreover they're only applicable if your bean is using @ManagedBean
annotation. If you are using JSF versions below 2.3 refer to the legacy answer at the end.
From JSF 2.3 here are scopes that can be used on JSF Backing Beans:
1. @javax.enterprise.context.ApplicationScoped
: The application scope persists for the entire duration of the web application. That scope is shared among all requests and all sessions. This is useful when you have data for whole application.
2. @javax.enterprise.context.SessionScoped
: The session scope persists from the time that a session is established until session termination. The session context is shared between all requests that occur in the same HTTP session. This is useful when you wont to save data for a specific client for a particular session.
3. @javax.enterprise.context.ConversationScoped
: The conversation scope persists as log as the bean lives. The scope provides 2 methods: Conversation.begin()
and Conversation.end()
. These methods should called explicitly, either to start or end the life of a bean.
4. @javax.enterprise.context.RequestScoped
: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back to the client. If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage.
5. @javax.faces.flow.FlowScoped
: The Flow scope persists as long as the Flow lives. A flow may be defined as a contained set of pages (or views) that define a unit of work. Flow scoped been is active as long as user navigates with in the Flow.
6. @javax.faces.view.ViewScoped
: A bean in view scope persists while the same JSF page is redisplayed. As soon as the user navigates to a different page, the bean goes out of scope.
The following legacy answer applies JSF version before 2.3
As of JSF 2.x there are 4 Bean Scopes:
- @SessionScoped
- @RequestScoped
- @ApplicationScoped
- @ViewScoped
Session Scope: The session scope persists from the time that a session is established until session termination. A session terminates if the web application invokes the invalidate method on the HttpSession object, or if it times out.
RequestScope: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back to the client. If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage.
ApplicationScope: The application scope persists for the entire duration of the web application. That scope is shared among all requests and all sessions. You place managed beans into the application scope if a single bean should be shared among all instances of a web application. The bean is constructed when it is first requested by any user of the application, and it stays alive until the web application is removed from the application server.
ViewScope: View scope was added in JSF 2.0. A bean in view scope persists while the same JSF page is redisplayed. (The JSF specification uses the term view for a JSF page.) As soon as the user navigates to a different page, the bean goes out of scope.
Choose the scope you based on your requirement.
Source: Core Java Server Faces 3rd Edition by David Geary & Cay Horstmann [Page no. 51 - 54]
For Java 11 you can use new HTTP client:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost/api"))
.header("Content-Type", "application/json")
.POST(ofInputStream(() -> getClass().getResourceAsStream(
"/some-data.json")))
.build();
client.sendAsync(request, BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();
You can use publisher from InputStream, String, File. Converting JSON to the String or IS you can with Jackson.
You can also use DateTime class:
$time1 = new DateTime('09:00:59');
$time2 = new DateTime('09:01:00');
$interval = $time1->diff($time2);
echo $interval->format('%s second(s)');
Result:
1 second(s)
To test whether a file exists in .NET, you can use
System.IO.File.Exists (String)
If anyone like me is searching to read only a specific line, example only line 18 here is the code:
filename = "C:\log.log"
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)
For i = 1 to 17
f.ReadLine
Next
strLine = f.ReadLine
Wscript.Echo strLine
f.Close
Your code is creating an array of function pointers. Try
char* a[size];
or
char a[size1][size2];
instead.
I think that (approaching) side effect free programming for some key parts of software will be essential when we start to get more and more cores in our hardware. Give functional programming a bit more time. And the functional sprinkling in current and future versions of C# will go a long way in preparing those corporate programmers for functional programming without them even realising it...
In Kotlin, if you don't want to create an extra class just for setting one value, you can create anonymous class from LayoutManager:
recyclerView.layoutManager = object : LinearLayoutManager(context) {
override fun canScrollVertically(): Boolean = false
}
I experienced this crash even though I had the RecyclerView.LayoutManager
properly set. I had to move the RecyclerView
initialization code into the onViewCreated(...)
callback to fix this issue.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_listing, container, false);
rootView.setTag(TAG);
return inflater.inflate(R.layout.fragment_listing, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mLayoutManager = new LinearLayoutManager(getActivity());
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new ListingAdapter(mListing);
mRecyclerView.setAdapter(mAdapter);
}
This did the trick for me. It captures all the stdout output from the subprocess(For python 3.8):
from subprocess import check_output, STDOUT
cmd = "Your Command goes here"
try:
cmd_stdout = check_output(cmd, stderr=STDOUT, shell=True).decode()
except Exception as e:
print(e.output.decode()) # print out the stdout messages up to the exception
print(e) # To print out the exception message
I've been using ClockPick.
df.shape
, where df
is your DataFrame.
Actually what you are searching is: Optional.map. Your code would then look like:
object.map(o -> "result" /* or your function */)
.orElseThrow(MyCustomException::new);
I would rather omit passing the Optional
if you can. In the end you gain nothing using an Optional
here. A slightly other variant:
public String getString(Object yourObject) {
if (Objects.isNull(yourObject)) { // or use requireNonNull instead if NullPointerException suffices
throw new MyCustomException();
}
String result = ...
// your string mapping function
return result;
}
If you already have the Optional
-object due to another call, I would still recommend you to use the map
-method, instead of isPresent
, etc. for the single reason, that I find it more readable (clearly a subjective decision ;-)).
Sleep() causes the currently executing thread to sleep (temporarily cease execution).
Yield() causes the currently executing thread object to temporarily pause and allow other threads to execute.
Read [this] (Link Removed) for a good explanation of the topic.
$ThatTime ="14:08:10";
if (time() >= strtotime($ThatTime)) {
echo "ok";
}
A solution using DateTime
(that also regards the timezone).
$dateTime = new DateTime($ThatTime);
if ($dateTime->diff(new DateTime)->format('%R') == '+') {
echo "OK";
}
Wow, you have a huge misunderstanding how asp.net works.
This line of code
System.Diagnostics.Process.Start("help/AdminTutorial.html");
Will not redirect a admin user to a new site, but start a new process on the server (usually a browser, IE) and load the site. That is for sure not what you want.
A very easy solution would be to change the href attribute of the link in you page_load method.
Your aspx code:
<a href="#" runat="server" id="myLink">Tutorial</a>
Your codebehind / cs code of page_load:
...
if (userinfo.user == "Admin")
{
myLink.Attributes["href"] = "help/AdminTutorial.html";
}
else
{
myLink.Attributes["href"] = "help/otherSite.html";
}
...
Don't forget to check the Admin rights again on "AdminTutorial.html" to "prevent" hacking.
It is not necessary to have two routes.
Simply add
(/*)?
at the end of yourpath
string.For example,
app.get('/hello/world(/*)?' /* ... */)
Here is a fully working example, feel free to copy and paste this into a .js file to run with node, and play with it in a browser (or curl):
const app = require('express')()
// will be able to match all of the following
const test1 = 'http://localhost:3000/hello/world'
const test2 = 'http://localhost:3000/hello/world/'
const test3 = 'http://localhost:3000/hello/world/with/more/stuff'
// but fail at this one
const failTest = 'http://localhost:3000/foo/world'
app.get('/hello/world(/*)?', (req, res) => res.send(`
This will match at example endpoints: <br><br>
<pre><a href="${test1}">${test1}</a></pre>
<pre><a href="${test2}">${test2}</a></pre>
<pre><a href="${test3}">${test3}</a></pre>
<br><br> Will NOT match at: <pre><a href="${failTest}">${failTest}</a></pre>
`))
app.listen(3000, () => console.log('Check this out in a browser at http://localhost:3000/hello/world!'))
In addition to others' proposals, there is another option to handle that issue.
If your application should behave the same in case of lack of "href
" attribute, as in case of it being empty, just replace this:
var theHref = $(obj.mainImg_select).attr('href');
with this:
var theHref = $(obj.mainImg_select).attr('href') || '';
which will treat empty string (''
) as the default, if the attribute has not been found.
But it really depends, on how you want to handle undefined "href
" attribute. This answer assumes you will want to handle it as if it was empty string.
Easy to read/type.
table = new char[][] {
"0123456789".toCharArray()
, "abcdefghij".toCharArray()
};
In the example you give, you're perfectly right, you have to set the title attribute.
If the aria-label
is one tool used by assistive technologies (like screen readers), it is not natively supported on browsers and has no effect on them. It won't be of any help to most of the people targetted by the WCAG (except screen reader users), for instance a person with intellectal disabilities.
The "X" is not sufficient enough to give information to the action led by the button (think about someone with no computer knowledge). It might mean "close", "delete", "cancel", "reduce", a strange cross, a doodle, nothing.
Despite the fact that the W3C seems to promote the aria-label
rather that the title
attribute here: http://www.w3.org/TR/2014/NOTE-WCAG20-TECHS-20140916/ARIA14 in a similar example, you can see that the technology support does not include standard browsers : http://www.w3.org/WAI/WCAG20/Techniques/ua-notes/aria#ARIA14
In fact aria-label
, in this exact situation might be used to give more context to an action:
For instance, blind people do not perceive popups like those of us with good vision, it's like a change of context. "Back to the page" will be a more convenient alternative for a screen reader, when "Close" is more significant for someone with no screen reader.
<button
aria-label="Back to the page"
title="Close" onclick="myDialog.close()">X</button>
can also Use parameterized each with index and the element.
$('#selectIntegrationConf').find('option').each(function(index,element){
console.log(index);
console.log(element.value);
console.log(element.text);
});
// this will also work
$('#selectIntegrationConf option').each(function(index,element){
console.log(index);
console.log(element.value);
console.log(element.text);
});
You can define a function type in interface in various ways,
export interface IParam {
title: string;
callback(arg1: number, arg2: number): number;
}
export interface IParam {
title: string;
callback: (arg1: number, arg2: number) => number;
}
type MyFnType = (arg1: number, arg2: number) => number;
export interface IParam {
title: string;
callback: MyFnType;
}
Using is very straight forward,
function callingFn(paramInfo: IParam):number {
let needToCall = true;
let result = 0;
if(needToCall){
result = paramInfo.callback(1,2);
}
return result;
}
export interface IParam{
title: string;
callback(lateCallFn?:
(arg1:number,arg2:number)=>number):number;
}
I got this error Unexpected identifier
because of a missing semi-colon ;
at the end of a line. Anyone wandering here for other than above-mentioned solutions, This might also be the cause of this error.
EDIT: Warning: Please, read the answer posted by Evan Carroll. It seems that this solution is not safe and not recommended.
This worked for me in the standard Ubuntu 14.04 64 bits installation.
I followed the instructions, with small modifications, that I found in http://suite.opengeo.org/4.1/dataadmin/pgGettingStarted/firstconnect.html
sudo apt-get install postgresql
sudo –u postgres psql postgres
\password postgres
\q
#Database administrative login by Unix domain socket
local all postgres peer
To:
#Database administrative login by Unix domain socket
local all postgres md5
sudo service postgresql restart
sudo –u postgres createdb mytestdb
psql –U postgres –W
\l
You can use WMIC or SCHTASKS (which means no third party software is needed):
1) SCHTASKS:
SCHTASKS /s remote_machine /U username /P password /create /tn "On demand demo" /tr "C:\some.bat" /sc ONCE /sd 01/01/1910 /st 00:00
SCHTASKS /s remote_machine /U username /P password /run /TN "On demand demo"
2) WMIC (wmic will return the pid of the started process)
WMIC /NODE:"remote_machine" /user user /password password process call create "c:\some.bat","c:\exec_dir"
You don't even have to set a specific width for the cells, table-layout: fixed
suffices to spread the cells evenly.
ul {_x000D_
width: 100%;_x000D_
display: table;_x000D_
table-layout: fixed;_x000D_
border-collapse: collapse;_x000D_
}_x000D_
li {_x000D_
display: table-cell;_x000D_
text-align: center;_x000D_
border: 1px solid hotpink;_x000D_
vertical-align: middle;_x000D_
word-wrap: break-word;_x000D_
}
_x000D_
<ul>_x000D_
<li>foo<br>foo</li>_x000D_
<li>barbarbarbarbar</li>_x000D_
<li>baz</li>_x000D_
</ul>
_x000D_
Note that for
table-layout
to work the table styled element must have a width set (100% in my example).
Well, to calculate the average of an array, you can consider using for
loop instead of while loop.
So as per your question let me assume an array as arrNumbers
( here i'm considering the same array elements as in your question )
int arrNumbers[] = new int[]{1, 3, 2, 5, 8};
int sum = 0;
for(int a = 0; a < arrNumbers.length; a++)
{
sum = sum + arrNumbers[a];
}
double average = sum / arrNumbers.length;
System.out.println("Average is: " + average);
You can use scanner
class as well. It's left to you.
After the configure step you probably have a makefile. Inside this makefile look for CFLAGS (or similar). puf -fPIC at the end and run make again. In other words -fPIC is a compiler option that has to be passed to the compiler somewhere.
The most robust mechanism for listing all resources in the classpath is currently to use this pattern with ClassGraph, because it handles the widest possible array of classpath specification mechanisms, including the new JPMS module system. (I am the author of ClassGraph.)
List<String> resourceNames;
try (ScanResult scanResult = new ClassGraph().whitelistPaths("x/y/z").scan()) {
resourceNames = scanResult.getAllResources().getNames();
}
I found this blog post very helpful. It saved my day. http://www.techsirius.com/2014/05/simple-geo-tracking-system.html
Basically you need to install the IP database table and then do mysql query for the IP for location.
<?php
include 'config.php';
mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) OR die(mysql_error());
mysql_select_db(DB_NAME) OR die(mysql_error());
$ip = $_SERVER['REMOTE_ADDR'];
$long = sprintf('%u', ip2long($ip));
$sql = "SELECT * FROM `geo_ips` WHERE '$long' BETWEEN `ip_start` AND `ip_end`";
$result = mysql_query($sql) OR die(mysql_error());
$ip_detail = mysql_fetch_assoc($result);
if($ip_detail){
echo $ip_detail['country']."', '".$ip_detail['state']."', '".$ip_detail['city'];
}
else{
//Something wrong with IP
}
I had the same problem for a while now. Until I searched through the Android Studio site and bumped with the introduction. Then I found how to activate (I think) the autocomplete feature. It says press Control+Space and when I did, it worked.
You can also use chmod 777 *
This will give permissions to all files currently in the folder and files added in the future without giving permissions to the directory itself.
NOTE: This should be done in the folder where the files are located. For me it was an images that had an issue so I went to my images folder and did this.
I just install stylus by default under my home dir, so I just use npm uninstall stylus
to detach it, or you can try npm rm <package_name>
out.
You can do it programmatically by reading the java
system properties
@Test
public void javaVersion() {
System.out.println(System.getProperty("java.version"));
System.out.println(System.getProperty("java.runtime.version"));
System.out.println(System.getProperty("java.home"));
System.out.println(System.getProperty("java.vendor"));
System.out.println(System.getProperty("java.vendor.url"));
System.out.println(System.getProperty("java.class.path"));
}
This will output somthing like
1.7.0_17
1.7.0_17-b02
C:\workspaces\Oracle\jdk1.7\jre
Oracle Corporation
http://java.oracle.com/
C:\workspaces\Misc\Miscellaneous\bin; ...
The first line shows the version number. You can parse it an see whether it fits your minimun required java version or not. You can find a description for the naming convention here and more infos here.
What's you've got there should be fine to work, but there is no actual "Is Mobile/Tablet" media query so you're always going to be stuck.
There are media queries for common breakpoints , but with the ever changing range of devices they're not guaranteed to work moving forwards.
The idea is that your site maintains the same brand across all sizes, so you should want the styles to cascade across the breakpoints and only update the widths and positioning to best suit that viewport.
To further the answer above, using Modernizr with a no-touch test will allow you to target touch devices which are most likely tablets and smart phones, however with the new releases of touch based screens that is not as good an option as it once was.
I would use regular expression matching to sum over variables with certain pattern names. For example:
df <- df %>% mutate(sum1 = rowSums(.[grep("x[3-5]", names(.))], na.rm = TRUE),
sum_all = rowSums(.[grep("x", names(.))], na.rm = TRUE))
This way you can create more than one variable as a sum of certain group of variables of your data frame.
Use CSS. It's easier and faster than javascript.
overflow-x: hidden;
overflow-y: scroll;
Using the RESTORE DATABASE
command most likely. bak
is a common extension used for a database backup file. You'll find documentation for this command on MSDN.
Already if you are using itextsharp dll, no need to add third party dll's(plugin), I think you are using htmlworker instead of it use xmlworker you can easily convert your html to pdf.
Some css won't work they are Supported CSS
Full Explain with example Reference Click here
MemoryStream memStream = new MemoryStream();
TextReader xmlString = new StringReader(outXml);
using (Document document = new Document())
{
PdfWriter writer = PdfWriter.GetInstance(document, memStream);
//document.SetPageSize(iTextSharp.text.PageSize.A4);
document.Open();
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(outXml);
MemoryStream ms = new MemoryStream(byteArray);
XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, ms, System.Text.Encoding.UTF8);
document.Close();
}
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(memStream.ToArray());
Response.End();
Response.Flush();
As of Spring 3.2, this is no longer an issue. Spring now supports Autowiring of the results of generic factory methods. See the section entitled "Generic Factory Methods" in this blog post: http://spring.io/blog/2012/11/07/spring-framework-3-2-rc1-new-testing-features/.
The key point is:
In Spring 3.2, generic return types for factory methods are now properly inferred, and autowiring by type for mocks should work as expected. As a result, custom work-arounds such as a MockitoFactoryBean, EasyMockFactoryBean, or Springockito are likely no longer necessary.
Which means this should work out of the box:
<bean id="dao" class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="com.package.Dao" />
</bean>
For those who may be confused by the accepted answer, as I was, you also need to have the ruby headers installed [ruby-devel].
The article that saved my hide is here.
And this is the revised solution (note that I'm on Fedora 13):
yum -y install gcc mysql-devel ruby-devel rubygems
gem install -y mysql -- --with-mysql-config=/usr/bin/mysql_config
For Debian, and other distributions using Debian style packaging the ruby development headers are installed by:
sudo apt-get install ruby-dev
For Ubuntu the ruby development headers are installed by:
sudo apt-get install ruby-all-dev
If you are using a earlier version of ruby (such as 2.2), then you will need to run:
sudo apt-get install ruby2.2-dev
(where 2.2 is your desired Ruby version)
.asterisc {_x000D_
display: block;_x000D_
color: red;_x000D_
margin: -19px 185px;_x000D_
}
_x000D_
<input style="width:200px">_x000D_
<span class="asterisc">*</span>
_x000D_
Let me expand a bit on a VonC's very comprehensive answer:
First, if I remember it correctly, the fact that Git by default doesn't create merge commits in the fast-forward case has come from considering single-branch "equal repositories", where mutual pull is used to sync those two repositories (a workflow you can find as first example in most user's documentation, including "The Git User's Manual" and "Version Control by Example"). In this case you don't use pull to merge fully realized branch, you use it to keep up with other work. You don't want to have ephemeral and unimportant fact when you happen to do a sync saved and stored in repository, saved for the future.
Note that usefulness of feature branches and of having multiple branches in single repository came only later, with more widespread usage of VCS with good merging support, and with trying various merge-based workflows. That is why for example Mercurial originally supported only one branch per repository (plus anonymous tips for tracking remote branches), as seen in older revisions of "Mercurial: The Definitive Guide".
Second, when following best practices of using feature branches, namely that feature branches should all start from stable version (usually from last release), to be able to cherry-pick and select which features to include by selecting which feature branches to merge, you are usually not in fast-forward situation... which makes this issue moot. You need to worry about creating a true merge and not fast-forward when merging a very first branch (assuming that you don't put single-commit changes directly on 'master'); all other later merges are of course in non fast-forward situation.
HTH
var sample_data = '';
$.getJSON("sample.json", function (data) {
sample_data = data;
$.each(data, function (key, value) {
console.log(sample_data);
});
});
NPX:
Web developers can have dozens of projects on their development machines, and each project has its own particular set of npm-installed dependencies. A few years back, the usual advice for dealing with CLI applications like Grunt or Gulp was to install them locally in each project and also globally so they could easily be run from the command line.
But installing globally caused as many problems as it solved. Projects may depend on different versions of command line tools, and polluting the operating system with lots of development-specific CLI tools isn’t great either. Today, most developers prefer to install tools locally and leave it at that.
Local versions of tools allow developers to pull projects from GitHub without worrying about incompatibilities with globally installed versions of tools. NPM can just install local versions and you’re good to go. But project specific installations aren’t without their problems: how do you run the right version of the tool without specifying its exact location in the project or playing around with aliases?
That’s the problem npx solves. A new tool included in NPM 5.2, npx is a small utility that’s smart enough to run the right application when it’s called from within a project.
If you wanted to run the project-local version of mocha, for example, you can run npx mocha inside the project and it will do what you expect.
A useful side benefit of npx is that it will automatically install npm packages that aren’t already installed. So, as the tool’s creator Kat Marchán points out, you can run npx benny-hill without having to deal with Benny Hill polluting the global environment.
If you want to take npx for a spin, update to the most recent version of npm.
Here's a straightforward and generic example.
The filter:
sampleApp.filter('unique', function() {
// Take in the collection and which field
// should be unique
// We assume an array of objects here
// NOTE: We are skipping any object which
// contains a duplicated value for that
// particular key. Make sure this is what
// you want!
return function (arr, targetField) {
var values = [],
i,
unique,
l = arr.length,
results = [],
obj;
// Iterate over all objects in the array
// and collect all unique values
for( i = 0; i < arr.length; i++ ) {
obj = arr[i];
// check for uniqueness
unique = true;
for( v = 0; v < values.length; v++ ){
if( obj[targetField] == values[v] ){
unique = false;
}
}
// If this is indeed unique, add its
// value to our values and push
// it onto the returned array
if( unique ){
values.push( obj[targetField] );
results.push( obj );
}
}
return results;
};
})
The markup:
<div ng-repeat = "item in items | unique:'name'">
{{ item.name }}
</div>
<script src="your/filters.js"></script>
I managed to find the required function in lodash, a utility library similar to underscore.
http://lodash.com/docs#mapValues
_.mapValues(object, [callback=identity], [thisArg])
Creates an object with the same keys as object and values generated by running each own enumerable property of object through the callback. The callback is bound to thisArg and invoked with three arguments; (value, key, object).
If you're using Bash you could also use one of the following commands:
printf '%(%Y%m%d%H%M%S)T' # prints the current time
printf '%(%Y%m%d%H%M%S)T' -1 # same as above
printf '%(%Y%m%d%H%M%S)T' -2 # prints the time the shell was invoked
You can use the Option -v varname
to store the result in $varname
instead of printing it to stdout:
printf -v varname '%(%Y%m%d%H%M%S)T'
While the date command will always be executed in a subshell (i.e. in a separate process) printf is a builtin command and will therefore be faster.
when you need in a timestamp in seconds, you can use the following:
var timestamp = (int)(DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalSeconds;
Use this:
static int RandomNumber(int min, int max)
{
Random random = new Random(); return random.Next(min, max);
}
This is example for you to modify and use in your application.
Here's an alternative solution using requests:
import requests
wjdata = requests.get('url').json()
print wjdata['data']['current_condition'][0]['temp_C']
I'm putting this in a new answer because no linebreaks / codeblocks in comments. I assume you want those nans to turn into a blank string? I couldn't find a nice way to do this, only do the ugly method:
s = pd.Series([1001.,1002.,None])
a = s.loc[s.isnull()].fillna('')
b = s.loc[s.notnull()].astype(int).astype(str)
result = pd.concat([a,b])
Including "string.h" makes things easier. An easier way to tackle your problem is:
#include <string.h>
char* createStr(){
static char str[20] = "my";
return str;
}
int main(){
char a[20];
strcpy(a,createStr()); //this will copy the returned value of createStr() into a[]
printf("%s",a);
return 0;
}
As @Peter Cullen answer mention, your script will meet browser timeout first. So its good idea to provide some log output, then flush()
, but connection have buffer and you'll not see anything unless much output provided. Here are code snippet what helps provide reliable log:
set_time_limit(0);
...
print "log message";
print "<!--"; print str_repeat (' ', 4000); print "-->"; flush();
print "log message";
print "<!--"; print str_repeat (' ', 4000); print "-->"; flush();
If you are writing code in Swift it would look as an example like this
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
switch section
{
case 0:
return "Apple Devices"
case 1:
return "Samsung Devices"
default:
return "Other Devices"
}
}
Similar to what you have, you could do something like
if (some_variable === undefined || some_variable === null) {
do stuff
}
Not so hard:
#include <thread>
void Test::runMultiThread()
{
std::thread t1(&Test::calculate, this, 0, 10);
std::thread t2(&Test::calculate, this, 11, 20);
t1.join();
t2.join();
}
If the result of the computation is still needed, use a future instead:
#include <future>
void Test::runMultiThread()
{
auto f1 = std::async(&Test::calculate, this, 0, 10);
auto f2 = std::async(&Test::calculate, this, 11, 20);
auto res1 = f1.get();
auto res2 = f2.get();
}
Here is the one-liner version getting the client's IP address:
$ip = @$_SERVER['HTTP_CLIENT_IP'] ?: @$_SERVER['HTTP_X_FORWARDED_FOR'] ?: @$_SERVER['REMOTE_ADDR'];
Notes:
@
, it suppresses the PHP notices.Value from HTTP_X_FORWARDED_FOR
may consist multiple addresses separated by comma, so if you prefer to get the first one, you can use the following method:
current(explode(',', @$_SERVER['HTTP_X_FORWARDED_FOR']))
File - setting - Build Execution Deployment - Gradle - Select 'Use default gradle wrapper(recommended)'