adb logcat -c
Logcat options are documented here: http://developer.android.com/tools/help/logcat.html
In my case I was sending empty tag i.e
Log.d("","My Log");
Instead send a tag name
Log.d("Class name","My Log");
Hope it helps someone
This has to do with having two buttons with the same ID in two different Activities, sometimes Android Studio can't find, You just have to give your button a new ID and re Build the Project
Go to your desired perspective. Go to 'Window->show view' menu.
If you see logcat there, click it and you are done.
Else, click on 'other' (at the bottom), chose 'Android'->logcat.
Hope that helps :-)
If you use the Logcat display inside the 'debug' perspective in Eclipse the lines are colour-coded. It's pretty easy to find what made your app crash because it's usually in red.
The Java (or Dalvik) virtual machine should never crash, but if your program throws an exception and does not catch it the VM will terminate your program, which is the 'crash' you are seeing.
This error, as you can read on the question linked in comments above, results to be:
"[...] a problem with loading {some} hardware module. This could be something to do with GPU support, sdcard handling, basically anything."
The step 1 below should resolve this problem. Also as I can see, you have some strange package names inside your manifest:
<manifest>
tag,<application>
<activity>
As you know, these things do not prevent your app to be displayed. But I think:
the
Couldn't load memtrack module error
could occur because of emulators configurations problems and, because your project contains many organization problems, it might help to give a fresh redesign.
For better using and with few things, this can be resolved by following these tips:
And even a real device! The memtrack module
error seems related to your emulator. So change it into Run configuration
, don't forget to change the API
too.
For OpenGl
errors, as called unimplemented OpenGL ES API
, it's not an error but a statement! You should enable it in your manifest (you can read this answer if you're using GLSurfaceView inside HomeActivity.java
, it might help you):
<uses-feature android:glEsVersion="0x00020000"></uses-feature>
// or
<uses-feature android:glEsVersion="0x00010001" android:required="true" />
Don't declare different package names to all the tags in Manifest
. You should have the same for Manifest
, Activities
, etc. Something like this looks right:
<!-- set the general package -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sit.gems.activity"
android:versionCode="1"
android:versionName="1.0" >
<!-- don't set a package name in <application> -->
<application ... >
<!-- then, declare the activities -->
<activity
android:name="com.sit.gems.activity.SplashActivity" ... >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- same package here -->
<activity
android:name="com.sit.gems.activity.HomeActivity" ... >
</activity>
</application>
</manifest>
You should set another layout for SplashScreenActivity.java
because you're not using the TabHost
for the splash screen and this is not a safe resource way. Declare a specific layout with something different, like the app name and the logo:
// inside SplashScreen class
setContentView(R.layout.splash_screen);
// layout splash_screen.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="@string/appname" />
Avoid using a layout in activities which don't use it.
Finally, I don't understand clearly the purpose of your SplashScreenActivity
. It sets a content view and directly finish. This is useless.
As its name is Splash Screen, I assume that you want to display a screen before launching your HomeActivity
. Therefore, you should do this and don't use the TabHost
layout ;):
// FragmentActivity is also useless here! You don't use a Fragment into it, so, use traditional Activity
public class SplashActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set your splash_screen layout
setContentView(R.layout.splash_screen);
// create a new Thread
new Thread(new Runnable() {
public void run() {
try {
// sleep during 800ms
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
// start HomeActivity
startActivity(new Intent(SplashActivity.this, HomeActivity.class));
SplashActivity.this.finish();
}
}).start();
}
}
I hope this kind of tips help you to achieve what you want.
If it's not the case, let me know how can I help you.
Tools-> Android -> Android Device Monitor
will open a separate window
Writing the followin code to print anything on LogCat works perfectly fine!!
int score=0;
score++;
System.out.println(score);
prints score on LogCat.Try this
The Android Studio website has recently (I think) provided some advice what kind of messages to expect from different log levels that may be useful along with Kurtis' answer:
You can use my libary called RDALogger. Here is github link.
With this library, you can log your message with method name/class name/line number and anchor link. With this link, when you click log, screen goes to this line of code.
To use library, you must do implementations below.
in root level gradle
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
in app level gradle
dependencies {
implementation 'com.github.ardakaplan:RDALogger:1.0.0'
}
For initializing library, you should start like this (in Application.class or before first use)
RDALogger.start("TAG NAME").enableLogging(true);
And than you can log whatever you want;
RDALogger.info("info");
RDALogger.debug("debug");
RDALogger.verbose("verbose");
RDALogger.warn("warn");
RDALogger.error("error");
RDALogger.error(new Throwable());
RDALogger.error("error", new Throwable());
And finally output shows you all you want (class name, method name, anchor link, message)
08-09 11:13:06.023 20025-20025/com.ardakaplan.application I/Application: IN CLASS : (ENApplication.java:29) /// IN METHOD : onCreate
info
This is simple.
Just close the Logcat from eclipse.
Then reopen it by following steps in Eclipse.
Window - Show View - Other - Android - LogCat - ok
Hope this solves your problem.
On the left in the logcat view you have the "Saved Filters" windows. Here you can add a new logcat filter by Application Name (for example, com.your.package)
Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.
If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.
You will not have access to your real sd card in emulator. You will have to follow the steps in this tutorial to direct your emulator to a directory on your development environment acting as your SD card.
Do not depend on ADB shell, just treat it (the adb logcat) a normal linux output and then pip it:
$ adb shell logcat | grep YouTag
# just like:
$ ps -ef | grep your_proc
In my case, it was literally a bad USB cable. Apparently it was right on the edge - adb logcat would work, but about half the time I would get this error when trying to push an app to the device.
Changed to a different cable, and everything was fine. The old cable was also very slow at charging, so I should have suspected it sooner...
Eventhough it is an old question, this may help someone.
We can choose multiple files while browsing for a file using "multiple"
<input type="file" name="datafile" size="40" multiple>
If you use Angular 6 we can put body in http.request
method.
You can try this, for me it works.
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
constructor(
private http: HttpClient
) {
http.request('delete', url, {body: body}).subscribe();
}
}
In MySql between the values are inclusive therefore when you give try to get between '2011-01-01' and '2011-01-31'
it will include from 2011-01-01 00:00:00
upto 2011-01-31 00:00:00
therefore nothing actually in 2011-01-31 since its time should go from 2011-01-31 00:00:00 ~ 2011-01-31 23:59:59
For the upper bound you can change to 2011-02-01
then it will get all data upto 2011-01-31 23:59:59
One another way is to use the same thing what firebase uses.
For example when user logs in, firebase stores below details in local storage. When user comes back to the page, firebase uses the same method to identify if user should be logged in automatically.
ATTN: As this is neither listed or recommended by firebase. You can call this method un-official way of doing this. Which means later if firebase changes their inner working, this method may not work. Or in short. Use at your own risk! :)
Are you trying to do logical equality utilizing the object's .equals method? You can do this utilizing the argThat matcher that is included in Mockito
import static org.mockito.Matchers.argThat
Next you can implement your own argument matcher that will defer to each objects .equals method
private class ObjectEqualityArgumentMatcher<T> extends ArgumentMatcher<T> {
T thisObject;
public ObjectEqualityArgumentMatcher(T thisObject) {
this.thisObject = thisObject;
}
@Override
public boolean matches(Object argument) {
return thisObject.equals(argument);
}
}
Now using your code you can update it to read...
Object obj = getObject();
Mockeable mock= Mockito.mock(Mockeable.class);
Mockito.when(mock.mymethod(obj)).thenReturn(null);
Testeable obj = new Testeable();
obj.setMockeable(mock);
command.runtestmethod();
verify(mock).mymethod(argThat(new ObjectEqualityArgumentMatcher<Object>(obj)));
If you are just going for EXACT equality (same object in memory), just do
verify(mock).mymethod(obj);
This will verify it was called once.
When doing a getObject()
from the S3 API, per the docs the contents of your file are located in the Body
property, which you can see from your sample output. You should have code that looks something like the following
const aws = require('aws-sdk');
const s3 = new aws.S3(); // Pass in opts to S3 if necessary
var getParams = {
Bucket: 'abc', // your bucket name,
Key: 'abc.txt' // path to the object you're looking for
}
s3.getObject(getParams, function(err, data) {
// Handle any error and exit
if (err)
return err;
// No error happened
// Convert Body from a Buffer to a String
let objectData = data.Body.toString('utf-8'); // Use the encoding necessary
});
You may not need to create a new buffer from the data.Body
object but if you need you can use the sample above to achieve that.
also you can reimplement protected member QWidget::closeEvent()
void YourWidgetWithXButton::closeEvent(QCloseEvent *event)
{
// do what you need here
// then call parent's procedure
QWidget::closeEvent(event);
}
Here is PostgreSQL example without trigger if someone need it on PostgreSQL:
CREATE SEQUENCE messages_seq;
CREATE TABLE IF NOT EXISTS messages (
id CHAR(20) NOT NULL DEFAULT ('message_' || nextval('messages_seq')),
name CHAR(30) NOT NULL,
);
ALTER SEQUENCE messages_seq OWNED BY messages.id;
array_search('20120504', array_keys($your_array));
Question was: Why is not (explicitly) calling return faster or better, and thus preferable?
There is no statement in R documentation making such an assumption.
The main page ?'function' says:
function( arglist ) expr
return(value)
Is it faster without calling return?
Both function()
and return()
are primitive functions and the function()
itself returns last evaluated value even without including return()
function.
Calling return()
as .Primitive('return')
with that last value as an argument will do the same job but needs one call more. So that this (often) unnecessary .Primitive('return')
call can draw additional resources.
Simple measurement however shows that the resulting difference is very small and thus can not be the reason for not using explicit return. The following plot is created from data selected this way:
bench_nor2 <- function(x,repeats) { system.time(rep(
# without explicit return
(function(x) vector(length=x,mode="numeric"))(x)
,repeats)) }
bench_ret2 <- function(x,repeats) { system.time(rep(
# with explicit return
(function(x) return(vector(length=x,mode="numeric")))(x)
,repeats)) }
maxlen <- 1000
reps <- 10000
along <- seq(from=1,to=maxlen,by=5)
ret <- sapply(along,FUN=bench_ret2,repeats=reps)
nor <- sapply(along,FUN=bench_nor2,repeats=reps)
res <- data.frame(N=along,ELAPSED_RET=ret["elapsed",],ELAPSED_NOR=nor["elapsed",])
# res object is then visualized
# R version 2.15
The picture above may slightly difffer on your platform. Based on measured data, the size of returned object is not causing any difference, the number of repeats (even if scaled up) makes just a very small difference, which in real word with real data and real algorithm could not be counted or make your script run faster.
Is it better without calling return?
Return
is good tool for clearly designing "leaves" of code where the routine should end, jump out of the function and return value.
# here without calling .Primitive('return')
> (function() {10;20;30;40})()
[1] 40
# here with .Primitive('return')
> (function() {10;20;30;40;return(40)})()
[1] 40
# here return terminates flow
> (function() {10;20;return();30;40})()
NULL
> (function() {10;20;return(25);30;40})()
[1] 25
>
It depends on strategy and programming style of the programmer what style he use, he can use no return() as it is not required.
R core programmers uses both approaches ie. with and without explicit return() as it is possible to find in sources of 'base' functions.
Many times only return() is used (no argument) returning NULL in cases to conditially stop the function.
It is not clear if it is better or not as standard user or analyst using R can not see the real difference.
My opinion is that the question should be: Is there any danger in using explicit return coming from R implementation?
Or, maybe better, user writing function code should always ask: What is the effect in not using explicit return (or placing object to be returned as last leaf of code branch) in the function code?
I think process.communicate() would be suitable for output having small size. For larger output it would not be the best approach.
Update for mid 2016:
The things are changing so fast that if it's late 2017 this answer might not be up to date anymore!
Beginners can quickly get lost in choice of build tools and workflows, but what's most up to date in 2016 is not using Bower, Grunt or Gulp at all! With help of Webpack you can do everything directly in NPM!
Google "npm as build tool" result: https://medium.com/@dabit3/introduction-to-using-npm-as-a-build-tool-b41076f488b0#.c33e74tsa
Don't get me wrong people use other workflows and I still use GULP in my legacy project(but slowly moving out of it), but this is how it's done in the best companies and developers working in this workflow make a LOT of money!
Look at this template it's a very up-to-date setup consisting of a mixture of the best and the latest technologies: https://github.com/coryhouse/react-slingshot
Your questions:
When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json
Everything belongs in package.json now
Dependencies required for build are in "devDependencies" i.e. npm install require-dir --save-dev
(--save-dev updates your package.json by adding an entry to devDependencies)
npm install lodash --save
(--save updates your package.json by adding an entry to dependencies)If that is the case, when should I ever install packages explicitly like that without adding them to the file that manages dependencies (apart from installing command line tools globally)?
Always. Just because of comfort. When you add a flag (--save-dev
or --save
) the file that manages deps (package.json) gets updated automatically. Don't waste time by editing dependencies in it manually. Shortcut for npm install --save-dev package-name
is npm i -D package-name
and shortcut for npm install --save package-name
is npm i -S package-name
anotherfunc(*extraArgs)
Since this is the top result on Google, I will post here after failing to find a solution for my problem. If you are looking to format the display value of a float object and have it remain a float - not a string, you can use this solution:
Create a new class that modifies the way that float values are displayed.
from builtins import float
class FormattedFloat(float):
def __str__(self):
return "{:.10f}".format(self).rstrip('0')
You can modify the precision yourself by changing the integer values in {:f}
The complete listing is buried in the android docs, and i only found it via google / dogpile.
http://developer.android.com/tools/help/emulator.html
That link has the emulator shortcut keys as of right now.
=\
You're not loading the validation plugin. You need:
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
Put this before the line that loads the additional methods.
Also, you should get the additional methods from the CDN as well, rather than jquery.bassistance.de.
Other errors:
[4.20]
should be
[4,20]
and
rangelenght:
should be:
rangelength:
I stumbled onto this question while trying to understand how to remove every occurrence of an element from an Array. Here's a comparison of splice
and delete
for removing every 'c'
from the items
Array.
var items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];
while (items.indexOf('c') !== -1) {
items.splice(items.indexOf('c'), 1);
}
console.log(items); // ["a", "b", "d", "a", "b", "d"]
items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];
while (items.indexOf('c') !== -1) {
delete items[items.indexOf('c')];
}
console.log(items); // ["a", "b", undefined, "d", "a", "b", undefined, "d"]
?
Because the Method2
is static, all you have to do is call like this:
public class AllMethods
{
public static void Method2()
{
// code here
}
}
class Caller
{
public static void Main(string[] args)
{
AllMethods.Method2();
}
}
If they are in different namespaces you will also need to add the namespace of AllMethods
to caller.cs in a using
statement.
If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:
public class MyClass
{
public void InstanceMethod()
{
// ...
}
}
public static void Main(string[] args)
{
var instance = new MyClass();
instance.InstanceMethod();
}
Update
As of C# 6, you can now also achieve this with using static
directive to call static methods somewhat more gracefully, for example:
// AllMethods.cs
namespace Some.Namespace
{
public class AllMethods
{
public static void Method2()
{
// code here
}
}
}
// Caller.cs
using static Some.Namespace.AllMethods;
namespace Other.Namespace
{
class Caller
{
public static void Main(string[] args)
{
Method2(); // No need to mention AllMethods here
}
}
}
Further Reading
Update:
Guido van Rossum announced on the mailing list that as of Python 3.7 dict
s in all Python implementations must preserve insertion order.
You don't need to use id for textview. You can learn more from android arrayadapter. The below code initializes the arrayadapter.
ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.single_item, eatables);
tv.setText( a1 + " ");
This will resolve your problem.
$datetime = date("Y-m-d h:i:s");
$timestamp = strtotime($datetime);
$image = $_POST['image'];
$imgdata = base64_decode($image);
$f = finfo_open();
$mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE);
$temp=explode('/',$mime_type);
$path = "uploads/$timestamp.$temp[1]";
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded->>> $timestamp.$temp[1]";
This will be enough for image processing. Special thanks to Mr. Dev Karan Sharma
I would like to make the case for SPA being best for Data Driven Applications. gmail, of course is all about data and thus a good candidate for a SPA.
But if your page is mostly for display, for example, a terms of service page, then a SPA is completely overkill.
I think the sweet spot is having a site with a mixture of both SPA and static/MVC style pages, depending on the particular page.
For example, on one site I am building, the user lands on a standard MVC index page. But then when they go to the actual application, then it calls up the SPA. Another advantage to this is that the load-time of the SPA is not on the home page, but on the app page. The load time being on the home page could be a distraction to first time site users.
This scenario is a little bit like using Flash. After a few years of experience, the number of Flash only sites dropped to near zero due to the load factor. But as a page component, it is still in use.
With unsigned numbers of type unsigned int
or larger, in the absence of type conversions, a-b
is defined as yielding the unsigned number which, when added to b
, will yield a
. Conversion of a negative number to unsigned is defined as yielding the number which, when added to the sign-reversed original number, will yield zero (so converting -5 to unsigned will yield a value which, when added to 5, will yield zero).
Note that unsigned numbers smaller than unsigned int
may get promoted to type int
before the subtraction, the behavior of a-b
will depend upon the size of int
.
If you are often programming dynamic stored procedures, you will fall in love with your second example (using where). If you have various input parameters and lots of morph mess, then that is the only way. Otherwise, they both will run the same query plan so there is definitely no obvious difference in classic queries.
hasOwnProperty
is a normal JavaScript function that takes a string argument.
When you call shape1.hasOwnProperty(name)
you are passing it the value of the name
variable (which doesn't exist), just as it would if you wrote alert(name)
.
You need to call hasOwnProperty
with a string containing name
, like this: shape1.hasOwnProperty("name")
.
It is not necessary to declare the interface abstract.
Just like declaring all those methods public (which they already are if the interface is public) or abstract (which they already are in an interface) is redundant.
No one is stopping you, though.
Other things you can explicitly state, but don't need to:
extends Object
Is there other rules that applies with an abstract interface?
An interface is already "abstract". Applying that keyword again makes absolutely no difference.
If you are using Microsoft Drivers 3.1, 3.0, and 2.0.
Please check your PHP version already install with IIS.
Use this script to check the php version:
<?php echo phpinfo(); ?>
OR
If you have installed PHP Manager in IIS using web platform Installer you can check the version from it.
Then:
If you are using new PHP version (5.6) please download Drivers from here
For PHP version Lower than 5.6 - please download Drivers from here
Then use the PHP Manager to add that downloaded drivers into php config
file.You can do it as shown below (browse the files and press OK).
Then Restart the IIS Server
If this method not work please change the php version and try to run your php script.
Tip:Change the php version
to lower and try to understand what happened.then you can download relevant drivers.
Very simple answer for this problem that seems to catch a lot of people:
<img src="url-to-image">
<p>Nullam id dolor id nibh ultricies vehicula ut id elit.</p>
img {
float: left;
}
p {
overflow: hidden;
}
See example: http://jsfiddle.net/vandigroup/upKGe/132/
If above answers don't work maybe you didn't add return value into getItem method in the custom adapter see this question and check out first answer.
You can do like this
$.datepicker.regional['fr'] = {clearText: 'Effacer', clearStatus: '',
closeText: 'Fermer', closeStatus: 'Fermer sans modifier',
prevText: '<Préc', prevStatus: 'Voir le mois précédent',
nextText: 'Suiv>', nextStatus: 'Voir le mois suivant',
currentText: 'Courant', currentStatus: 'Voir le mois courant',
monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
'Jul','Aoû','Sep','Oct','Nov','Déc'],
monthStatus: 'Voir un autre mois', yearStatus: 'Voir un autre année',
weekHeader: 'Sm', weekStatus: '',
dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
dayStatus: 'Utiliser DD comme premier jour de la semaine', dateStatus: 'Choisir le DD, MM d',
dateFormat: 'dd/mm/yy', firstDay: 0,
initStatus: 'Choisir la date', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['fr']);
Use reflection
System.Reflection.PropertyInfo pi = item.GetType().GetProperty("name");
String name = (String)(pi.GetValue(item, null));
Search your code for occurrences of new
, and make sure that they all occur within a constructor with a matching delete in a destructor. Make sure that this is the only possibly throwing operation in that constructor. A simple way to do this is to wrap all pointers in std::auto_ptr
, or boost::scoped_ptr
(depending on whether or not you need move semantics). For all future code just ensure that every resource is owned by an object that cleans up the resource in its destructor. If you need move semantics then you can upgrade to a compiler that supports r-value references (VS2010 does I believe) and create move constructors. If you don't want to do that then you can use a variety of tricky techniques involving conscientious usage of swap, or try the Boost.Move library.
Passsing bitmap as parceable in bundle between activity is not a good idea because of size limitation of Parceable(1mb). You can store the bitmap in a file in internal storage and retrieve the stored bitmap in several activities. Here's some sample code.
To store bitmap in a file myImage in internal storage:
public String createImageFromBitmap(Bitmap bitmap) {
String fileName = "myImage";//no .png or .jpg needed
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
FileOutputStream fo = openFileOutput(fileName, Context.MODE_PRIVATE);
fo.write(bytes.toByteArray());
// remember close file output
fo.close();
} catch (Exception e) {
e.printStackTrace();
fileName = null;
}
return fileName;
}
Then in the next activity you can decode this file myImage to a bitmap using following code:
//here context can be anything like getActivity() for fragment, this or MainActivity.this
Bitmap bitmap = BitmapFactory.decodeStream(context.openFileInput("myImage"));
Note A lot of checking for null and scaling bitmap's is ommited.
This should be much simpler in the new version 3.0. Easiest is to point to the Bootstrap CDN: http://www.bootstrapcdn.com/?v=01042013155511#tab_fontawesome
There is another solution if you want to develop in C/C++. http://www.DragonFireSDK.com will allow you to build iPhone applications in Visual Studio on Windows. It's worth a look-see for sure.
I just found a free zip database that includes time offset and participation in DST. I do like Erik J's answer, as it would help me choose the actual time zone as opposed to just the offset (because you never can be completely sure on the rules), but I think I might start with this, and have it try to find the best time zone match based on offset/dst configuration. I think I may try to set up a simple version of Development 4.0's answer to check against what I get from the zip info as a sanity test. It's definitely not as simple as I'd hope, but a combination should get me at least 90% sure of a user's time zone.
I usually use this form:
{{#if FriendStatus.IsFriend}}
...
{{else}} {{#if FriendStatus.FriendRequested}}
...
{{else}}
...
{{/if}}{{/if}}
In the pom.xml (after loading effective pom.xml in eclipse), you may see it "http://repo.maven.apache.org/maven2" under central repository instead of "https://repo.maven.apache.org/maven2". Fix it
How about using set?
let productPrice = [230,560,125,230,678,45,230,125,127];
let tempData = new Set(productPrice);
let uniqeProductPrice = [...tempData];
uniqeProductPrice.forEach((item)=>{
console.log(item)
});
Take a look at "SET ROLE" and "SET SESSION AUTHORIZATION".
If FlexContext is not available:
Solution 1: inside method (>= Spring 2.0 required)
HttpServletRequest request =
((ServletRequestAttributes)RequestContextHolder.getRequestAttributes())
.getRequest();
Solution 2: inside bean (supported by >= 2.5, Spring 3.0 for singelton beans required!)
@Autowired
private HttpServletRequest request;
setTimout on 0 is also very useful in the pattern of setting up a deferred promise, which you want to return right away:
myObject.prototype.myMethodDeferred = function() {
var deferredObject = $.Deferred();
var that = this; // Because setTimeout won't work right with this
setTimeout(function() {
return myMethodActualWork.call(that, deferredObject);
}, 0);
return deferredObject.promise();
}
Label
is an inline element - so, unless a width is defined, its width is exact the same which the letters span. Your div
element is a block element so its width is by default 100%.
You will have to place the text-align: right;
on the div
element in your case, or applying display: block;
to your label
Another option is to set a width for each label and then use text-align
. The display: block
method will not be necessary using this.
Do this for a cool border
and font
effect:
#ck-button:hover { /*ADD :hover */
margin:4px;
background-color:#EFEFEF;
border-radius:4px;
border:1px solid red; /*change border color*/
overflow:auto;
float:left;
color:red; /*add font color*/
}
Example: http://jsfiddle.net/zAFND/6/
By default you use UNICODE so I suggest using faulty's method
int bar = int.Parse(foo.ToString());
Even though the numeric values under are the same for digits and basic Latin chars.
Hello you can make use of input and output. Input let you to pass variable form parent to child. Output the same but from child to parent.
The easiest way is to pass "startdate" and "endDate" as input
<calendar [startDateInCalendar]="startDateInSearch" [endDateInCalendar]="endDateInSearch" ></calendar>
In this way you have your startdate and enddate directly in search page. Let me know if it works, or think another way. Thanks
I would one-up'd mightymada's answer if I had the reputation - I just implemented an asp.net HTML to PDF solution using Pechkin. results are wonderful.
There is a nuget package for Pechkin, but as the above poster mentions in his blog (http://codeutil.wordpress.com/2013/09/16/convert-html-to-pdf/ - I hope she doesn't mind me reposting it), there's a memory leak that's been fixed in this branch:
https://github.com/tuespetre/Pechkin
The above blog has specific instructions for how to include this package (it's a 32 bit dll and requires .net4). here is my code. The incoming HTML is actually assembled via HTML Agility pack (I'm automating invoice generations):
public static byte[] PechkinPdf(string html)
{
//Transform the HTML into PDF
var pechkin = Factory.Create(new GlobalConfig());
var pdf = pechkin.Convert(new ObjectConfig()
.SetLoadImages(true).SetZoomFactor(1.5)
.SetPrintBackground(true)
.SetScreenMediaType(true)
.SetCreateExternalLinks(true), html);
//Return the PDF file
return pdf;
}
again, thank you mightymada - your answer is fantastic.
Tested with Microsoft Excel 2016
A really tested solution.
To C# Reference please see: https://stackoverflow.com/a/1307180/10442623
To VB.net Reference please see: https://stackoverflow.com/a/54044646/10442623
1 include the class job
2 implement the class to handle the apropiate dispose of excel proces
One can make calls by using Bootstrap. The current version does not has any source update issues Trouble updating Bootstrap's typeahead data-source with post response , i.e. the source of bootstrap once updated can be again modified.
Please refer to below for an example:
jQuery('#help').typeahead({
source : function(query, process) {
jQuery.ajax({
url : "urltobefetched",
type : 'GET',
data : {
"query" : query
},
dataType : 'json',
success : function(json) {
process(json);
}
});
},
minLength : 1,
});
if i understand the question correctly you just want last month and the year it is in:
<?php
$month = date('m');
$year = date('Y');
$last_month = $month-1%12;
echo ($last_month==0?($year-1):$year)."-".($last_month==0?'12':$last_month);
?>
Here is the example: http://codepad.org/c99nVKG8
Simple. Text-align: justify; (to get the elements aligned) Padding-left: ?px; (to center the elements)
Use the "not" selector.
For example, instead of:
$(".thumbs").hover()
try:
$(".thumbs:not(.selected)").hover()
I use these methods in my personal library:
Array.prototype.sum = Array.prototype.sum || function() {
return this.reduce(function(sum, a) { return sum + Number(a) }, 0);
}
Array.prototype.average = Array.prototype.average || function() {
return this.sum() / (this.length || 1);
}
EDIT: To use them, simply ask the array for its sum or average, like:
[1,2,3].sum() // = 6
[1,2,3].average() // = 2
In my case, Visual Leak Detector I was using to track down memory leaks in Visual Studio 2015 was missing the Microsoft manifest file Microsoft.DTfW.DHL.manifest
, see link Building Visual Leak Detector all way down. This file must be in the folder where vld.dll
or vld_x64.dll
is in your configuration, say C:\Program Files (x86)\Visual Leak Detector\bin\Win32
, C:\Program Files (x86)\Visual Leak Detector\bin\Win64
, Debug
or x64/Debug
.
Putting this answer here as it is the top result in Google.
If you want a quick and simple way:
filter: brightness(0.2);
*Not compatible with IE
In my case, one of the services either Apache, Apache2 or Nginx was already running and due to that I was not able to start the other service.
Sample program to mouse hover using Selenium java WebDriver :
public class Mhover {
public static void main(String[] args){
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.google.com");
WebElement ele = driver.findElement(By.id("gbqfba"));
Actions action = new Actions(driver);
action.moveToElement(ele).build().perform();
}
}
All others answers don't work if the string contains Unicode char (like Emojis) because an Unicode char weight more bytes than a char.
Example : the emoji '' converted to bytes, will weight the equivalent of 2 chars. So, if the unicode char is placed at the beginning of your string,
offset
parameter will be shifted).
With this topic, i extend the StringInfo class to Replace by position keeping the Nick Miller's algorithm to avoid that :
public static class StringInfoUtils
{
public static string ReplaceByPosition(this string str, string replaceBy, int offset, int count)
{
return new StringInfo(str).ReplaceByPosition(replaceBy, offset, count).String;
}
public static StringInfo ReplaceByPosition(this StringInfo str, string replaceBy, int offset, int count)
{
return str.RemoveByTextElements(offset, count).InsertByTextElements(offset, replaceBy);
}
public static StringInfo RemoveByTextElements(this StringInfo str, int offset, int count)
{
return new StringInfo(string.Concat(
str.SubstringByTextElements(0, offset),
offset + count < str.LengthInTextElements
? str.SubstringByTextElements(offset + count, str.LengthInTextElements - count - offset)
: ""
));
}
public static StringInfo InsertByTextElements(this StringInfo str, int offset, string insertStr)
{
if (string.IsNullOrEmpty(str?.String))
return new StringInfo(insertStr);
return new StringInfo(string.Concat(
str.SubstringByTextElements(0, offset),
insertStr,
str.LengthInTextElements - offset > 0 ? str.SubstringByTextElements(offset, str.LengthInTextElements - offset) : ""
));
}
}
If you are testing asynchronous code, you need to make sure to place done()
in the callback of that asynchronous code. I had that issue when testing http requests to a REST API.
I found a good choice to be coc.nvim with the python language server.
It takes a bit of effort to set up. I got frustrated with jedi-vim, because it would always freeze vim for a bit when completing. coc.nvim doesn't do it because it's asyncronous, meaning that . It also gives you linting for your code. It supports many other languages and is highly configurable.
The python language server uses jedi so you get the same completion as you would get from jedi.
When I launch gVim without arguments, I want it to open in my "project" directory, so that I can do :find
etc. However, when I launch it with files, I don't want it to switch directory, I want it to stay right there (in part, so that it opens the file I want it to open!).
if argc() == 0
cd $PROJECT_DIR
endif
So that I can use :find
from any file in the current project, I set up my path to look up the directory tree 'til it finds src
or scripts
and descends into those, at least until it hits c:\work
which is the root of all of my projects. This allows me to open files in a project that is not current (i.e. PROJECT_DIR
above specifies a different directory).
set path+=src/**;c:/work,scripts/**;c:/work
So that I get automatic saving and reloading, and exiting of insert mode when gVim loses focus, as well as automatic checkout from Perforce when editing a readonly file...
augroup AutoSaveGroup
autocmd!
autocmd FocusLost *.cpp,*.h,*.cs,*.rad*,Jam*,*.py,*.bat,*.mel wa
autocmd FileChangedRO *.cpp,*.h,*.cs,*.rad*,Jam*,*.py,*.bat,*.mel silent !p4 edit %:p
autocmd FileChangedRO *.cpp,*.h,*.cs,*.rad*,Jam*,*.py,*.bat,*.mel w!
augroup END
augroup OutOfInsert
autocmd!
autocmd FocusLost * call feedkeys("\<C-\>\<C-N>")
augroup END
And finally, switch to the directory of the file in the current buffer so that it's easy to :e
other files in that directory.
augroup MiscellaneousTomStuff
autocmd!
" make up for the deficiencies in 'autochdir'
autocmd BufEnter * silent! lcd %:p:h:gs/ /\\ /
augroup END
I found I can make the match when I input a hard-coded non-breaking space (U+00A0) by typing Alt+0160 on Windows between the two quotes...
//table[@id='TableID']//td[text()=' ']
worked for me with the special char.
From what I understood, the XPath 1.0 standard doesn't handle escaping Unicode chars. There seems to be functions for that in XPath 2.0 but it looks like Firefox doesn't support it (or I misunderstood something). So you have to do with local codepage. Ugly, I know.
Actually, it looks like the standard is relying on the programming language using XPath to provide the correct Unicode escape sequence... So, somehow, I did the right thing.
If you're experimenting with Metal rendering & you're extracting the CGImage generated by imageByApplyingAlpha in the first reply, you may end up with a Metal rendering that's larger than you expect. While experimenting with Metal, you may want to change one line of code in imageByApplyingAlpha:
UIGraphicsBeginImageContextWithOptions (self.size, NO, 1.0f);
// UIGraphicsBeginImageContextWithOptions (self.size, NO, 0.0f);
If you're using a device with a scale factor of 3.0, like the iPhone 11 Pro Max, the 0.0 scale factor shown above will give you an CGImage that's three times larger than you're expecting. Changing the scale factor to 1.0 should avoid any scaling.
Hopefully, this reply will save beginners a lot of aggravation.
You cannot and should not rely on the ordering of elements within a JSON object.
From the JSON specification at http://www.json.org/
An object is an unordered set of name/value pairs
As a consequence, JSON libraries are free to rearrange the order of the elements as they see fit. This is not a bug.
1 - Create a folder in your google drive;
2 - Make this folder public (on share property)
3 - use something like this as your image src:
https://drive.google.com/thumbnail?id=${imageId}&sz=w${width || 200}-h${height || 200}
Let us assume that the class is Data with two objects name and dob which are both strings.
Initially, check if the list is empty. Then, add the objects from the list to a JSONArray
JSONArray allDataArray = new JSONArray();
List<Data> sList = new ArrayList<String>();
//if List not empty
if (!(sList.size() ==0)) {
//Loop index size()
for(int index = 0; index < sList.size(); index++) {
JSONObject eachData = new JSONObject();
try {
eachData.put("name", sList.get(index).getName());
eachData.put("dob", sList.get(index).getDob());
} catch (JSONException e) {
e.printStackTrace();
}
allDataArray.put(eachData);
}
} else {
//Do something when sList is empty
}
Finally, add the JSONArray to a JSONObject.
JSONObject root = new JSONObject();
try {
root.put("data", allDataArray);
} catch (JSONException e) {
e.printStackTrace();
}
You can further get this data as a String too.
String jsonString = root.toString();
Once you have cloned the repo, you have everything: you can then hg up branchname
or hg up tagname
to update your working copy.
UP: hg up
is a shortcut of hg update
, which also has hg checkout
alias for people with git
habits.
Just for fun, the following is a way of doing it on CPython 1.0-3.7b2, Pypy, Jython and Micropython. This is more of a curiosity than a way of doing it in modern code. I wrote it as part of http://stromberg.dnsalias.org/~strombrg/pythons/ , which is a script for testing a snippet of code on many versions of python at once, so you can easily get a feel for what python features are compatible with what versions of python:
via_platform = 0
check_sys = 0
via_sys_version_info = 0
via_sys_version = 0
test_sys = 0
try:
import platform
except (ImportError, NameError):
# We have no platform module - try to get the info via the sys module
check_sys = 1
if not check_sys:
if hasattr(platform, "python_version"):
via_platform = 1
else:
check_sys = 1
if check_sys:
try:
import sys
test_sys = 1
except (ImportError, NameError):
# just let via_sys_version_info and via_sys_version remain False - we have no sys module
pass
if test_sys:
if hasattr(sys, "version_info"):
via_sys_version_info = 1
elif hasattr(sys, "version"):
via_sys_version = 1
else:
# just let via_sys remain False
pass
if via_platform:
# This gives pretty good info, but is not available in older interpreters. Also, micropython has a
# platform module that does not really contain anything.
print(platform.python_version())
elif via_sys_version_info:
# This is compatible with some older interpreters, but does not give quite as much info.
print("%s.%s.%s" % sys.version_info[:3])
elif via_sys_version:
import string
# This is compatible with some older interpreters, but does not give quite as much info.
verbose_version = sys.version
version_list = string.split(verbose_version)
print(version_list[0])
else:
print("unknown")
This is caused by a gradle dependency on some out-of-date thing which causes the error. Remove gradle dependencies until the error stops appearing. For me, it was:
implementation 'org.apache.directory.studio:org.apache.commons.io:2.4'
This line needed to be updated to a newer version such as:
api group: 'commons-io', name: 'commons-io', version: '2.6'
You can use locate
and grep
:
locate jar | xargs grep 'my.class'
Make sure you run updatedb
before using locate
.
Please read the following carefully. It should remove all your doubts regarding the difference between null
and undefined
in JavaScript. Also, you can use the utility function at the end of this answer to get more specific types of variables.
In JavaScript we can have the following types of variables:
undefined
null
undefined
or null
The following explains each of these cases one by one:
Undeclared Variables
typeof
operator which returns string 'undefined'== undefined
), let alone the strict equality operator ( === undefined
),? :
) — these throw Reference ErrorsDeclared but Unassigned Variables
typeof
returns string 'undefined'==
check with null
returns true
==
check with undefined
returns true
===
check with null
returns false
===
check with undefined
returns true
? :
)Variables assigned with literal undefined
These variables are treated exactly the same as Declared But Unassigned Variables.
Variables assigned with literal null
typeof
returns string 'object'==
check with null
returns true
==
check with undefined
returns true
===
check with null
returns true
===
check with undefined
returns false
? :
)Variables assigned with anything other than undefined
or null
Following provides the algorithm for correct type checking of a variable:
typeof
our variable and return it if it isn't 'object'null
, as typeof null
returns 'object' as wellObject
's toString
method returns strings that look like '[object ConstructorName]' for native/host objects. For all other objects (user-defined objects), it always returns '[object Object]'true
, it will try to get the name of the constructor by toString
-ing it and extracting the name from there. If the constructor can't be reached, 'object' is returned as usual. If the string doesn't contain its name, 'anonymous' is returned(supports all types up to ECMAScript 2020)
function TypeOf(o, returnConstructorBoolean) {
const type = typeof o
if (type !== 'object') return type
if (o === null) return 'null'
const toString = Object.prototype.toString.call(o)
switch (toString) {
// Value types: 6
case '[object BigInt]': return 'bigint'
case '[object Boolean]': return 'boolean'
case '[object Date]': return 'date'
case '[object Number]': return 'number'
case '[object String]': return 'string'
case '[object Symbol]': return 'symbol'
// Error types: 7
case '[object Error]': return 'error'
case '[object EvalError]': return 'evalerror'
case '[object RangeError]': return 'rangeerror'
case '[object ReferenceError]': return 'referenceerror'
case '[object SyntaxError]': return 'syntaxerror'
case '[object TypeError]': return 'typeerror'
case '[object URIError]': return 'urierror'
// Indexed Collection and Helper types: 13
case '[object Array]': return 'array'
case '[object Int8Array]': return 'int8array'
case '[object Uint8Array]': return 'uint8array'
case '[object Uint8ClampedArray]': return 'uint8clampedarray'
case '[object Int16Array]': return 'int16array'
case '[object Uint16Array]': return 'uint16array'
case '[object Int32Array]': return 'int32array'
case '[object Uint32Array]': return 'uint32array'
case '[object Float32Array]': return 'float32array'
case '[object Float64Array]': return 'float64array'
case '[object ArrayBuffer]': return 'arraybuffer'
case '[object SharedArrayBuffer]': return 'sharedarraybuffer'
case '[object DataView]': return 'dataview'
// Keyed Collection types: 2
case '[object Map]': return 'map'
case '[object WeakMap]': return 'weakmap'
// Set types: 2
case '[object Set]': return 'set'
case '[object WeakSet]': return 'weakset'
// Operation types: 3
case '[object RegExp]': return 'regexp'
case '[object Proxy]': return 'proxy'
case '[object Promise]': return 'promise'
// Plain objects
case '[object Object]':
if (!returnConstructorBoolean)
return type
const _prototype = Object.getPrototypeOf(o)
if (!_prototype)
return type
const _constructor = _prototype.constructor
if (!_constructor)
return type
const matches = Function.prototype.toString.call(_constructor).match(/^function\s*([^\s(]+)/)
return matches ? matches[1] : 'anonymous'
default: return toString.split(' ')[1].slice(0, -1)
}
}
In python, bool(sequence)
is False
if the sequence is empty. Since strings are sequences, this will work:
cookie = ''
if cookie:
print "Don't see this"
else:
print "You'll see this"
$count = 0;
$output ='';
$ischeckedvalueArray = array();
for ($i=0; $i < sizeof($array); $i++) {
$eachArrayValue = $array[$i];
if(! in_array($eachArrayValue, $ischeckedvalueArray)) {
for( $j=$i; $j < sizeof($array); $j++) {
if ($array[$j] === $eachArrayValue) {
$count++;
}
}
$ischeckedvalueArray[] = $eachArrayValue;
$output .= $eachArrayValue. " Repated ". $count."<br/>";
$count = 0;
}
}
echo $output;
The prototype-solution from Krishna Chytanya is very nice, but needs a minor but important improvement. The days param must be parsed as Integer to avoid weird calculations when days is a String like "1". (I needed several hours to find out, what went wrong in my application.)
Date.prototype.addDays = function(days) {
this.setDate(this.getDate() + parseInt(days));
return this;
};
Even if you do not use this prototype function: Always be sure to have an Integer when using setDate().
As mentioned by Adam you have to take your system limitations into consideration before you can decide on approach whether you have enough memory to read it all into memory replace parts of it and re-write it.
If you're dealing with a small file or have no memory issues this might help:
Option 1) Read entire file into memory, do a regex substitution on the entire or part of the line and replace it with that line plus the extra line. You will need to make sure that the 'middle line' is unique in the file or if you have timestamps on each line this should be pretty reliable.
# open file with r+b (allow write and binary mode)
f = open("file.log", 'r+b')
# read entire content of file into memory
f_content = f.read()
# basically match middle line and replace it with itself and the extra line
f_content = re.sub(r'(middle line)', r'\1\nnew line', f_content)
# return pointer to top of file so we can re-write the content with replaced string
f.seek(0)
# clear file content
f.truncate()
# re-write the content with the updated content
f.write(f_content)
# close file
f.close()
Option 2) Figure out middle line, and replace it with that line plus the extra line.
# open file with r+b (allow write and binary mode)
f = open("file.log" , 'r+b')
# get array of lines
f_content = f.readlines()
# get middle line
middle_line = len(f_content)/2
# overwrite middle line
f_content[middle_line] += "\nnew line"
# return pointer to top of file so we can re-write the content with replaced string
f.seek(0)
# clear file content
f.truncate()
# re-write the content with the updated content
f.write(''.join(f_content))
# close file
f.close()
Here's a way to do it in Python without NumPy. Create a function that returns what you want and use a list comprehension, or the map function.
>>> a = [1, 2, 3, -4, 5]
>>> def zero_if_negative(x):
... if x < 0:
... return 0
... return x
...
>>> [zero_if_negative(x) for x in a]
[1, 2, 3, 0, 5]
>>> map(zero_if_negative, a)
[1, 2, 3, 0, 5]
You increment it
past the end of the (empty) container in the for loop's loop expression.
int i = 0;
Console.WriteLine(i++); // Prints 0. Then value of "i" becomes 1.
Console.WriteLine(--i); // Value of "i" becomes 0. Then prints 0.
Does this answer your question ?
multipart/form-data contains boundary to separate name/value pairs. The boundary acts like a marker of each chunk of name/value pairs passed when a form gets submitted. The boundary is automatically added to a content-type of a request header.
The form with enctype="multipart/form-data" attribute will have a request header Content-Type : multipart/form-data; boundary --- WebKit193844043-h (browser generated vaue).
The payload passed looks something like this:
Content-Type: multipart/form-data; boundary=---WebKitFormBoundary7MA4YWxkTrZu0gW
-----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name=”file”; filename=”captcha”
Content-Type:
-----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name=”action”
submit
-----WebKitFormBoundary7MA4YWxkTrZu0gW--
On the webservice side, it's consumed in @Consumes("multipart/form-data") form.
Beware, when testing your webservice using chrome postman, you need to check the form data option(radio button) and File menu from the dropdown box to send attachment. Explicit provision of content-type as multipart/form-data throws an error. Because boundary is missing as it overrides the curl request of post man to server with content-type by appending the boundary which works fine.
From JavaEE docs ServletResponse#setContentType
Sets the content type of the response being sent to the client, if the response has not been committed yet.
The given content type may include a character encoding specification, for example,
response.setContentType("text/html;charset=UTF-8");
The response's character encoding is only set from the given content type if this method is called before getWriter
is called.
This method may be called repeatedly to change content type and character encoding.
This method has no effect if called after the response has been committed. It does not set the response's character encoding if it is called after getWriter
has been called or after the response has been committed.
Containers must communicate the content type and the character encoding used for the servlet response's writer to the client if the protocol provides a way for doing so. In the case of HTTP, the Content-Type header is used.
This solution uses a RandomAccessFile
to only cache the portion of the file subsequent to the string to remove. It scans until it finds the String
you want to remove. Then it copies all of the data after the found string, then writes it over the found string, and everything after. Last, it truncates the file size to remove the excess data.
public static long scanForString(String text, File file) throws IOException {
if (text.isEmpty())
return file.exists() ? 0 : -1;
// First of all, get a byte array off of this string:
byte[] bytes = text.getBytes(/* StandardCharsets.your_charset */);
// Next, search the file for the byte array.
try (DataInputStream dis = new DataInputStream(new FileInputStream(file))) {
List<Integer> matches = new LinkedList<>();
for (long pos = 0; pos < file.length(); pos++) {
byte bite = dis.readByte();
for (int i = 0; i < matches.size(); i++) {
Integer m = matches.get(i);
if (bytes[m] != bite)
matches.remove(i--);
else if (++m == bytes.length)
return pos - m + 1;
else
matches.set(i, m);
}
if (bytes[0] == bite)
matches.add(1);
}
}
return -1;
}
public static void remove(String text, File file) throws IOException {
try (RandomAccessFile rafile = new RandomAccessFile(file, "rw");) {
long scanForString = scanForString(text, file);
if (scanForString == -1) {
System.out.println("String not found.");
return;
}
long remainderStartPos = scanForString + text.getBytes().length;
rafile.seek(remainderStartPos);
int remainderSize = (int) (rafile.length() - rafile.getFilePointer());
byte[] bytes = new byte[remainderSize];
rafile.read(bytes);
rafile.seek(scanForString);
rafile.write(bytes);
rafile.setLength(rafile.length() - (text.length()));
}
}
File Contents: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Method Call: remove("ABC", new File("Drive:/Path/File.extension"));
Resulting Contents: DEFGHIJKLMNOPQRSTUVWXYZ
This solution could easily be modified to remove with a certain, specifiable cacheSize
, if memory is a concern. This would just involve iterating over the rest of the file to continually replace portions of size, cacheSize
. Regardless, this solution is generally much better than caching an entire file in memory, or copying it to a temporary directory, etc.
Add below code in the onCreate function:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
And then override: @Override public boolean onOptionsItemSelected(MenuItem item){ onBackPressed(); return true; }
I guess using break to your teacher is like breaking a branch of tree to get the fruit,use some other tricks (bow the branch) so that you get the fruit and the branch is still alive.:)
What is a DLL?
Dynamic Link Libraries (DLL)s are like EXEs but they are not directly executable. They are similar to .so files in Linux/Unix. That is to say, DLLs are MS's implementation of shared libraries.
DLLs are so much like an EXE that the file format itself is the same. Both EXE and DLLs are based on the Portable Executable (PE) file format. DLLs can also contain COM components and .NET libraries.
What does a DLL contain?
A DLL contains functions, classes, variables, UIs and resources (such as icons, images, files, ...) that an EXE, or other DLL uses.
Types of libraries:
On virtually all operating systems, there are 2 types of libraries. Static libraries and dynamic libraries. In windows the file extensions are as follows: Static libraries (.lib) and dynamic libraries (.dll). The main difference is that static libraries are linked to the executable at compile time; whereas dynamic linked libraries are not linked until run-time.
More on static and dynamic libraries:
You don't normally see static libraries though on your computer, because a static library is embedded directly inside of a module (EXE or DLL). A dynamic library is a stand-alone file.
A DLL can be changed at any time and is only loaded at runtime when an EXE explicitly loads the DLL. A static library cannot be changed once it is compiled within the EXE. A DLL can be updated individually without updating the EXE itself.
Loading a DLL:
A program loads a DLL at startup, via the Win32 API LoadLibrary, or when it is a dependency of another DLL. A program uses the GetProcAddress to load a function or LoadResource to load a resource.
Further reading:
Please check MSDN or Wikipedia for further reading. Also the sources of this answer.
Below are the changes (Marked in BOLD) in your code:
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:text="Register"
android:id="@+id/register"
android:layout_width="0dp" //changes made here
android:layout_height="wrap_content"
android:padding="10dip"
android:layout_weight="1" /> //changes made here
<Button
android:text="Not this time"
android:id="@+id/cancel"
android:layout_width="0dp" //changes made here
android:layout_height="wrap_content"
android:padding="10dip"
android:layout_weight="1" /> //changes made here
</LinearLayout>
Since your LinearLayout has orientation as horizontal, therefore you will need to keep your width only as 0dp. for using weights in that direction . (If your orientation was vertical, you would have kept your height only 0dp).
Since there are 2 views and you have placed android:layout_weight="1"
for both the views, it means it will divide the two views equally in horizontal direction (or by width).
Below command will display the modfied files alone in windows.
svn status | findstr "^M"
I discovered quite by accident (I was working with images at the time) that the box-shadow, border-radius and transitions work quite well with the bog-standard audio tag player. I have this working in Chrome, FF and Opera.
audio:hover, audio:focus, audio:active
{
-webkit-box-shadow: 15px 15px 20px rgba(0,0, 0, 0.4);
-moz-box-shadow: 15px 15px 20px rgba(0,0, 0, 0.4);
box-shadow: 15px 15px 20px rgba(0,0, 0, 0.4);
-webkit-transform: scale(1.05);
-moz-transform: scale(1.05);
transform: scale(1.05);
}
with:-
audio
{
-webkit-transition:all 0.5s linear;
-moz-transition:all 0.5s linear;
-o-transition:all 0.5s linear;
transition:all 0.5s linear;
-moz-box-shadow: 2px 2px 4px 0px #006773;
-webkit-box-shadow: 2px 2px 4px 0px #006773;
box-shadow: 2px 2px 4px 0px #006773;
-moz-border-radius:7px 7px 7px 7px ;
-webkit-border-radius:7px 7px 7px 7px ;
border-radius:7px 7px 7px 7px ;
}
I grant you it only "tarts it up a bit", but it makes them a sight more exciting than what's already there, and without doing MAJOR fannying about in JS.
NOT available in IE, unfortunately (not yet supporting the transition bit), but it seems to degrade nicely.
if 'seek' in 'those who seek shall find':
print('Success!')
but keep in mind that this matches a sequence of characters, not necessarily a whole word - for example, 'word' in 'swordsmith'
is True. If you only want to match whole words, you ought to use regular expressions:
import re
def findWholeWord(w):
return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search
findWholeWord('seek')('those who seek shall find') # -> <match object>
findWholeWord('word')('swordsmith') # -> None
My version for a directive that uses jqplot to plot the data once it becomes available:
app.directive('lineChart', function() {
$.jqplot.config.enablePlugins = true;
return function(scope, element, attrs) {
scope.$watch(attrs.lineChart, function(newValue, oldValue) {
if (newValue) {
// alert(scope.$eval(attrs.lineChart));
var plot = $.jqplot(element[0].id, scope.$eval(attrs.lineChart), scope.$eval(attrs.options));
}
});
}
});
100% working solution
1) rm -rf /usr/local/lib/node_modules
2)brew uninstall node
3)echo prefix=~/.npm-packages >> ~/.npmrc
4)brew install node
5) npm install -g @angular/cli
Finally and most importantly
6) export PATH="$HOME/.npm-packages/bin:$PATH"
Also if any editor still shown err than write
7) point over there .
100% working
The following statement causes a user's password to expire:
ALTER USER user PASSWORD EXPIRE;
If you cause a database user's password to expire with PASSWORD EXPIRE, then the user (or the DBA) must change the password before attempting to log in to the database following the expiration. Tools such as SQL*Plus allow the user to change the password on the first attempted login following the expiration.
ALTER USER scott IDENTIFIED BY password;
Will set/reset the users password.
See the alter user doc for more info
One can access the "Find in Files" window via the drop-down menu selection and search all files in the Entire Solution: Edit > Find and Replace > Find in Files
Other, alternative is to open the "Find in Files" window via the "Standard Toolbars" button as highlighted in the below screen-short:
Here a good link on Quirksmode.
function setCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
document.cookie = name+'=; Max-Age=-99999999;';
}
>>> L = range (11)
>>> [ x if x%2 == 1 else None for x in L ]
[None, 1, None, 3, None, 5, None, 7, None, 9, None]
You asked about typical uses.
One common complaint about shell scripting is that you (allegedly) can't pass by reference to get values back out of functions.
But actually, via "eval", you can pass by reference. The callee can pass back a list of variable assignments to be evaluated by the caller. It is pass by reference because the caller can allowed to specify the name(s) of the result variable(s) - see example below. Error results can be passed back standard names like errno and errstr.
Here is an example of passing by reference in bash:
#!/bin/bash
isint()
{
re='^[-]?[0-9]+$'
[[ $1 =~ $re ]]
}
#args 1: name of result variable, 2: first addend, 3: second addend
iadd()
{
if isint ${2} && isint ${3} ; then
echo "$1=$((${2}+${3}));errno=0"
return 0
else
echo "errstr=\"Error: non-integer argument to iadd $*\" ; errno=329"
return 1
fi
}
var=1
echo "[1] var=$var"
eval $(iadd var A B)
if [[ $errno -ne 0 ]]; then
echo "errstr=$errstr"
echo "errno=$errno"
fi
echo "[2] var=$var (unchanged after error)"
eval $(iadd var $var 1)
if [[ $errno -ne 0 ]]; then
echo "errstr=$errstr"
echo "errno=$errno"
fi
echo "[3] var=$var (successfully changed)"
The output looks like this:
[1] var=1
errstr=Error: non-integer argument to iadd var A B
errno=329
[2] var=1 (unchanged after error)
[3] var=2 (successfully changed)
There is almost unlimited band width in that text output! And there are more possibilities if the multiple output lines are used: e.g., the first line could be used for variable assignments, the second for continuous 'stream of thought', but that's beyond the scope of this post.
The answer with for
is correct, but if you really want to use functional style avoiding for
statement - you can use the following instead of your expression:
Array.from(Array(1000000), () => Math.random());
The Array.from() method creates a new Array instance from an array-like or iterable object. The second argument of this method is a map function to call on every element of the array.
Following the same idea you can rewrite it using ES2015 Spread operator:
[...Array(1000000)].map(() => Math.random())
In both examples you can get an index of the iteration if you need, for example:
[...Array(1000000)].map((_, i) => i + Math.random())
Using Abizern code for swift 2.2
let objectData = responseString!.dataUsingEncoding(NSUTF8StringEncoding)
let json = try NSJSONSerialization.JSONObjectWithData(objectData!, options: NSJSONReadingOptions.MutableContainers)
Here are the differences. Note the newlines at the end.
> shell_exec('date')
string(29) "Wed Mar 6 14:18:08 PST 2013\n"
> exec('date')
string(28) "Wed Mar 6 14:18:12 PST 2013"
> shell_exec('whoami')
string(9) "mark\n"
> exec('whoami')
string(8) "mark"
> shell_exec('ifconfig')
string(1244) "eth0 Link encap:Ethernet HWaddr 10:bf:44:44:22:33 \n inet addr:192.168.0.90 Bcast:192.168.0.255 Mask:255.255.255.0\n inet6 addr: fe80::12bf:ffff:eeee:2222/64 Scope:Link\n UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1\n RX packets:16264200 errors:0 dropped:1 overruns:0 frame:0\n TX packets:7205647 errors:0 dropped:0 overruns:0 carrier:0\n collisions:0 txqueuelen:1000 \n RX bytes:13151177627 (13.1 GB) TX bytes:2779457335 (2.7 GB)\n"...
> exec('ifconfig')
string(0) ""
Note that use of the backtick operator is identical to shell_exec()
.
Update: I really should explain that last one. Looking at this answer years later even I don't know why that came out blank! Daniel explains it above -- it's because exec
only returns the last line, and ifconfig
's last line happens to be blank.
I know the problem! You just put a dot after "test.jpg"!
cvSaveImage("test.jpg". ,pSaveImg);
I may be wrong but I think its not good!
Within your app in the Android Emulator press Command + M on macOS or Ctrl + M on Linux and Windows.
With Hibernate you can create your own UserType. So thats what I did for this issue. Something as simple as this:
public class BytesType implements org.hibernate.usertype.UserType {
private final int[] SQL_TYPES = new int[] { java.sql.Types.VARBINARY };
//...
}
There of course is more to implement from extending your own UserType but I just wanted to throw that out there for anyone looking for other methods.
If possible, I went with a solution like this. It only works if you want several specific interfaces (e.g. those you have source access to) to be passed as a generic parameter, not any.
IInterface
.IInterface
In source, it looks like this:
Any interface you want to be passed as the generic parameter:
public interface IWhatever : IInterface
{
// IWhatever specific declarations
}
IInterface:
public interface IInterface
{
// Nothing in here, keep moving
}
The class on which you want to put the type constraint:
public class WorldPeaceGenerator<T> where T : IInterface
{
// Actual world peace generating code
}
I had the same issue I solved using this. Refer this Spring MVC: @Value annotation to get int value defined in *.properties file
@Value(#{propertyfileId.propertyName})
works
Use +
plus sign (Match one or more of the previous items),
var regexp = /^\S+$/
boolean compare(String str1, String str2) {
return (str1==null || str2==null) ? str1 == str2 : str1.equals(str2);
}
If you have a column called "col1" which is int, you cast it to String like this:
CONVERT(col1,char)
e.g. this allows you to check an int value is containing another value (here 9) like this:
CONVERT(col1,char) LIKE '%9%'
Since the tests will be instantiated like a Spring bean too, you just need to implement the ApplicationContextAware interface:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/services-test-config.xml"})
public class MySericeTest implements ApplicationContextAware
{
@Autowired
MyService service;
...
@Override
public void setApplicationContext(ApplicationContext context)
throws BeansException
{
// Do something with the context here
}
}
As far as i know %d
means decadic which is number without decimal point. if you want to load double value, use %lf
conversion (long float). for printf your values are wrong for same reason, %d
is used only for integer (and possibly chars if you know what you are doing) numbers.
Example:
double a,b;
printf("--------\n"); //seperate lines
scanf("%lf",&a);
printf("--------\n");
scanf("%lf",&b);
printf("%lf %lf",a,b);
Option 1:
Use following command in python ide.:
import numpy
Option 2:
Go to Python -> site-packages folder. There you should be able to find numpy and the numpy distribution info folder.
If any of the above is true then you installed numpy successfully.
checkout
can be use for many case :
1st case : switch between branch in local repository
For instance :
git checkout exists_branch_to_switch
You can also create new branch and switch out in throught this case with -b
git checkout -b new_branch_to_switch
2nd case : restore file from x rev
git checkout rev file_to_restore
...
Why for
? What do you want to iterate? Try this.
call :cpy pc-name-1
call :cpy pc-name-2
...
:cpy
net use \\%1\{destfolder} {password} /user:{username}
copy {file} \\%1\{destfolder}
goto :EOF
The question seems a little bit old. But let me suggest a function, parseStr, which makes something similar, that is, returns integer or float and if a given ASCII string cannot be converted to none of them it returns it untouched. The code of course might be adjusted to do only what you want:
>>> import string
>>> parseStr = lambda x: x.isalpha() and x or x.isdigit() and \
... int(x) or x.isalnum() and x or \
... len(set(string.punctuation).intersection(x)) == 1 and \
... x.count('.') == 1 and float(x) or x
>>> parseStr('123')
123
>>> parseStr('123.3')
123.3
>>> parseStr('3HC1')
'3HC1'
>>> parseStr('12.e5')
1200000.0
>>> parseStr('12$5')
'12$5'
>>> parseStr('12.2.2')
'12.2.2'
If you're using .NET 4.0 you should be able to allow these urls via the web.config
<system.web>
<httpRuntime
requestPathInvalidCharacters="<,>,%,&,:,\,?" />
</system.web>
Note, I've just removed the asterisk (*), the original default string is:
<httpRuntime
requestPathInvalidCharacters="<,>,*,%,&,:,\,?" />
See this question for more details.
One option would be
const styleElement = getComputedStyle(document.getElementById("myDiv"));
console.log(styleElement.height);
Here's the workflow I use all the time, using the keyboard only
Note that this doesn't work if there are blank lines in the selection.
You can convert a tensor in tensorflow
to numpy
array in the following ways.
First:
Use np.array(your_tensor)
Second:
Use your_tensor.numpy
You can solve the problem changing the compileSdkVersion in the Grandle.build file from 18 to wtever SDK is installed ..... BUTTTTT
If you are trying to goin back in SDK versions like 18 to 17 ,You can not use the feature available in 18 or 18+
If you are migrating your project (Eclipse to Android Studio ) Then off course you Don't have build.gradle file in your Existed Eclipse project
So, the only solution is to ensure the SDK version installed or not, you are targeting to , If not then install.
Error:Cause: failed to find target with hash string 'android-19' in: C:\Users\setia\AppData\Local\Android\sdk
Use the source
command to import other scripts:
#!/bin/bash
source /REFERENCE/TO/CONFIG.FILE
sudo -u wwwrun svn up /srv/www/htdocs/$production
sudo -u wwwrun svn up /srv/www/htdocs/$playschool
For getting a table by name in SQL Server:
SELECT *
FROM sys.Tables
WHERE name LIKE '%Employees%'
For finding a stored procedure by name:
SELECT name
FROM sys.objects
WHERE name = 'spName'
To get all stored procedures related to a table:
----Option 1
SELECT DISTINCT so.name
FROM syscomments sc
INNER JOIN sysobjects so ON sc.id=so.id
WHERE sc.TEXT LIKE '%tablename%'
----Option 2
SELECT DISTINCT o.name, o.xtype
FROM syscomments c
INNER JOIN sysobjects o ON c.id=o.id
WHERE c.TEXT LIKE '%tablename%'
Unless it is the most trivial case, there is only one sane way to use command line options in Ruby. It is called docopt and documented here.
What is amazing with it, is it's simplicity. All you have to do, is specify the "help" text for your command. What you write there will then be auto-parsed by the standalone (!) ruby library.
From the example:
#!/usr/bin/env ruby
require 'docopt.rb'
doc = <<DOCOPT
Usage: #{__FILE__} --help
#{__FILE__} -v...
#{__FILE__} go [go]
#{__FILE__} (--path=<path>)...
#{__FILE__} <file> <file>
Try: #{__FILE__} -vvvvvvvvvv
#{__FILE__} go go
#{__FILE__} --path ./here --path ./there
#{__FILE__} this.txt that.txt
DOCOPT
begin
require "pp"
pp Docopt::docopt(doc)
rescue Docopt::Exit => e
puts e.message
end
The output:
$ ./counted_example.rb -h
Usage: ./counted_example.rb --help
./counted_example.rb -v...
./counted_example.rb go [go]
./counted_example.rb (--path=<path>)...
./counted_example.rb <file> <file>
Try: ./counted_example.rb -vvvvvvvvvv
./counted_example.rb go go
./counted_example.rb --path ./here --path ./there
./counted_example.rb this.txt that.txt
$ ./counted_example.rb something else
{"--help"=>false,
"-v"=>0,
"go"=>0,
"--path"=>[],
"<file>"=>["something", "else"]}
$ ./counted_example.rb -v
{"--help"=>false, "-v"=>1, "go"=>0, "--path"=>[], "<file>"=>[]}
$ ./counted_example.rb go go
{"--help"=>false, "-v"=>0, "go"=>2, "--path"=>[], "<file>"=>[]}
Enjoy!
Found an alternative at Child elements with margins within DIVs You can also add:
.parent { overflow: auto; }
or:
.parent { overflow: hidden; }
This prevents the margins to collapse. Border and padding do the same. Hence, you can also use the following to prevent a top-margin collapse:
.parent {
padding-top: 1px;
margin-top: -1px;
}
Update by popular request: The whole point of collapsing margins is handling textual content. For example:
h1, h2, p, ul {_x000D_
margin-top: 1em;_x000D_
margin-bottom: 1em;_x000D_
}
_x000D_
<h1>Title!</h1>_x000D_
<div class="text">_x000D_
<h2>Title!</h2>_x000D_
<p>Paragraph</p>_x000D_
</div>_x000D_
<div class="text">_x000D_
<h2>Title!</h2>_x000D_
<p>Paragraph</p>_x000D_
<ul>_x000D_
<li>list item</li>_x000D_
</ul>_x000D_
</div>
_x000D_
Because the browser collapses margins, the text would appear as you'd expect, and the <div>
wrapper tags don't influence the margins. Each element ensures it has spacing around it, but spacing won't be doubled. The margins of the <h2>
and <p>
won't add up, but slide into each other (they collapse). The same happens for the <p>
and <ul>
element.
Sadly, with modern designs this idea can bite you when you explicitly want a container. This is called a new block formatting context in CSS speak. The overflow
or margin trick will give you that.
If you are generating a heap of commands to be run, then call that script from a terminal, you can try the following.
sftp login@host < /path/to/command/list
You will then be asked to enter your password (as per normal) however all the commands in the script run after that.
This is clearly not a completely automated option that can be used in a cron
job, but it can be used from a terminal.
Those are the levels. You'd consider the severity of the message you're logging, and use the appropriate levels.
It's basically a watermark; the higher the level, the more likely you want to retain the information in the log entry. FINEST would be for messages that are of very little importance, so you'd use it for things you usually don't care about but might want to see in some rare circumstance.
window.location = appurl;// fb://method/call..
!window.document.webkitHidden && setTimeout(function () {
setTimeout(function () {
window.location = weburl; // http://itunes.apple.com/..
}, 100);
}, 600);
document.webkitHidden
is to detect if your app is already invoked and current safari tab to going to the background, this code is from www.baidu.com
$_SERVER['SERVER_ADDR']
@GetMapping
is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET)
.
@GetMapping
is the newer annotaion.
It supports consumes
Consume options are :
consumes = "text/plain"
consumes = {"text/plain", "application/*"}
For Further details see: GetMapping Annotation
or read: request mapping variants
RequestMapping supports consumes as well
GetMapping we can apply only on method level and RequestMapping annotation we can apply on class level and as well as on method level
to add scroll u need to define max-height of your div and then add overflow-y
so do something like this
.my_scroll_div{
overflow-y: auto;
max-height: 100px;
}
Here are 2 radio buttons namely rd1 and Radio1
<input type="radio" name="rd" id="rd1" />
<input type="radio" name="rd" id="Radio1" />
The simplest wayt to check which radio button is checked ,by checking individual is(":checked") property
if ($("#rd1").is(":checked")) {
alert("rd1 checked");
}
else {
alert("rd1 not checked");
}
You can also cast an array to a string like...
newStr = String(aa);
I also agree with Tor Valamo's answer, console.log should have no problem with arrays, no need to convert to a string unless you're debugging something or just curious.
The possible reason could be deletion of the existing db file and migrations folder
you can use python manage.py makemigrations <app_name>
this should work. I once faced a similar problem.
Make sure you're not printing (echo or print) any text/data prior to generate your JSON formated data in your PHP file. That could explain that you get a -sucessfull 200 OK- but your sucess event still fails in your javascript. You can verify what your script is receiving by checking the section "Network - Answer" in firebug for the POST submit1.php.
Pure JavaScript answer:
document.querySelector('.menu').classList.contains('active');
Might help someone someday.
If you want to open multiple instances of the same folder, then it is not currently supported. Watch and upvote this GitHub issue if you want to see it implemented: Support to open a project folder in multiple Visual Studio Code windows
It's often useful to look at the signature and description of API methods, not just their name :) - Even in the Java standard API, names can sometimes be misleading.
I'm not sure what you are trying to do by wishing to convert C# to java, but if it is .net interoperability that you need, you might want to check out Mono
You can also use a formula in excel in order to convert this type of date to a date type excel can read:
=DATEVALUE(CONCATENATE(MID(A1,8,3),MID(A1,4,4),RIGHT(A1,4)))
And you get: 12/7/2016
from: Wed Dec 07 00:00:00 UTC 2016
Wildcard works for me also, but I'd like to give a side note for those using directory variables. Always use slash for folder tree (not backslash), otherwise it will fail:
BASEDIR = ../..
SRCDIR = $(BASEDIR)/src
INSTALLDIR = $(BASEDIR)/lib
MODULES = $(wildcard $(SRCDIR)/*.cpp)
OBJS = $(wildcard *.o)
I've tried to find a "fit to screen" property but there is no such.
But setting widget's "maximumSize" to a "some big number" ( like 2000 x 2000 ) will automatically fit the widget to the parent widget space.
I finally understood what was going on.
When creating an integration test on a statement saving an object, it is recommended to flush the entity manager so as to avoid any false negative, that is, to avoid a test running fine but whose operation would fail when run in production. Indeed, the test may run fine simply because the first level cache is not flushed and no writing hits the database. To avoid this false negative integration test use an explicit flush in the test body. Note that the production code should never need to use any explicit flush as it is the role of the ORM to decide when to flush.
When creating an integration test on an update statement, it may be necessary to clear the entity manager so as to reload the first level cache. Indeed, an update statement completely bypasses the first level cache and writes directly to the database. The first level cache is then out of sync and reflects the old value of the updated object. To avoid this stale state of the object, use an explicit clear in the test body. Note that the production code should never need to use any explicit clear as it is the role of the ORM to decide when to clear.
My test now works just fine.
I'm very late to the party, but since element.lastChild.nextSibling === null
, the following seems like the most straightforward option to me:
for(var child=element.firstChild; child!==null; child=child.nextSibling) {
console.log(child);
}
In C++11, you can use std::any_of
instead.
An example to find if there is any zero in the array:
std::array<int,3> foo = {0,1,-1};
if ( std::any_of(foo.begin(), foo.end(), [](int i){return i==0;}) )
std::cout << "zero found...";
If you use psycopg2
(and possibly some other client library), you can simply pass a Python datetime
object as a parameter to a SQL-query:
from datetime import datetime, timezone
dt = datetime.now(timezone.utc)
cur.execute('INSERT INTO mytable (mycol) VALUES (%s)', (dt,))
(This assumes that the timestamp with time zone
type is used on the database side.)
More Python types that can be adapted into SQL (and returned as Python objects when a query is executed) are listed here.
You are trying to access the class as opposed to the object. That statement can be confusing to beginners, but you are effectively trying to open your house door by picking up the door on your house plans.
If you actually wanted to access the form components directly from a class (which you don't) you would use the variable that instantiates your form.
Depending on which way you want to go you'd be better of either sending the text of a control or whatever to a method in your classes eg
public void DoSomethingWithText(string formText)
{
// do something text in here
}
or exposing properties on your form class and setting the form text in there - eg
string SomeProperty
{
get
{
return textBox1.Text;
}
set
{
textBox1.Text = value;
}
}
if(isset($_GET['id']))
{
// Do something
}
You want something like that
This Python code is my quick and dirty attempt to implement the algorithm:
import math
from collections import Counter
def build_vector(iterable1, iterable2):
counter1 = Counter(iterable1)
counter2 = Counter(iterable2)
all_items = set(counter1.keys()).union(set(counter2.keys()))
vector1 = [counter1[k] for k in all_items]
vector2 = [counter2[k] for k in all_items]
return vector1, vector2
def cosim(v1, v2):
dot_product = sum(n1 * n2 for n1, n2 in zip(v1, v2) )
magnitude1 = math.sqrt(sum(n ** 2 for n in v1))
magnitude2 = math.sqrt(sum(n ** 2 for n in v2))
return dot_product / (magnitude1 * magnitude2)
l1 = "Julie loves me more than Linda loves me".split()
l2 = "Jane likes me more than Julie loves me or".split()
v1, v2 = build_vector(l1, l2)
print(cosim(v1, v2))
In newer versions of Eclipse that use the M2E plugin it is:
Right-click on your project(s) --> Maven --> Update Project...
In the following dialog is a checkbox for forcing the update ("Force Update of Snapshots/Releases")
//just edit menu.xml file
//add icon for item which will change default setting icon
//add sub menus
///menu.xml file
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="@string/action_settings"
android:icon="@drawable/your_icon"
app:showAsAction="always" >
<menu>
<item android:id="@+id/action_menu1"
android:icon="@android:drawable/ic_menu_preferences"
android:title="menu 1" />
<item android:id="@+id/action_menu2"
android:icon="@android:drawable/ic_menu_help"
android:title="menu 2" />
</menu>
</item>
You may be overcomplicating things, is there any reason you need the stringr package?
df <- data.frame(Date = c("10/9/2009 0:00:00", "10/15/2009 0:00:00"))
as.Date(df$Date, "%m/%d/%Y %H:%M:%S")
[1] "2009-10-09" "2009-10-15"
More generally and if you need the time component as well, use strptime:
strptime(df$Date, "%m/%d/%Y %H:%M:%S")
I'm guessing at what your actual data might look at from the partial results you give.
You will have to submit this data to the server somehow. I'm assuming that you don't want to do a full page reload every time a user clicks a link, so you'll have to user XHR (AJAX). If you are not using jQuery (or some other JS library) you can read this tutorial on how to do the XHR request "by hand".
It seems that window.onerror
doesn't provide access to all possible errors. Specifically it ignores:
<img>
loading errors (response >= 400).<script>
loading errors (response >= 400).window.onerror
in an unknown way (jquery, angular, etc.).Here is the start of a script that catches many of these errors, so that you may add more robust debugging to your app during development.
(function(){
/**
* Capture error data for debugging in web console.
*/
var captures = [];
/**
* Wait until `window.onload`, so any external scripts
* you might load have a chance to set their own error handlers,
* which we don't want to override.
*/
window.addEventListener('load', onload);
/**
* Custom global function to standardize
* window.onerror so it works like you'd think.
*
* @see http://www.quirksmode.org/dom/events/error.html
*/
window.onanyerror = window.onanyerror || onanyerrorx;
/**
* Hook up all error handlers after window loads.
*/
function onload() {
handleGlobal();
handleXMLHttp();
handleImage();
handleScript();
handleEvents();
}
/**
* Handle global window events.
*/
function handleGlobal() {
var onerrorx = window.onerror;
window.addEventListener('error', onerror);
function onerror(msg, url, line, col, error) {
window.onanyerror.apply(this, arguments);
if (onerrorx) return onerrorx.apply(null, arguments);
}
}
/**
* Handle ajax request errors.
*/
function handleXMLHttp() {
var sendx = XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.send = function(){
handleAsync(this);
return sendx.apply(this, arguments);
};
}
/**
* Handle image errors.
*/
function handleImage() {
var ImageOriginal = window.Image;
window.Image = ImageOverride;
/**
* New `Image` constructor. Might cause some problems,
* but not sure yet. This is at least a start, and works on chrome.
*/
function ImageOverride() {
var img = new ImageOriginal;
onnext(function(){ handleAsync(img); });
return img;
}
}
/**
* Handle script errors.
*/
function handleScript() {
var HTMLScriptElementOriginal = window.HTMLScriptElement;
window.HTMLScriptElement = HTMLScriptElementOverride;
/**
* New `HTMLScriptElement` constructor.
*
* Allows us to globally override onload.
* Not ideal to override stuff, but it helps with debugging.
*/
function HTMLScriptElementOverride() {
var script = new HTMLScriptElement;
onnext(function(){ handleAsync(script); });
return script;
}
}
/**
* Handle errors in events.
*
* @see http://stackoverflow.com/questions/951791/javascript-global-error-handling/31750604#31750604
*/
function handleEvents() {
var addEventListenerx = window.EventTarget.prototype.addEventListener;
window.EventTarget.prototype.addEventListener = addEventListener;
var removeEventListenerx = window.EventTarget.prototype.removeEventListener;
window.EventTarget.prototype.removeEventListener = removeEventListener;
function addEventListener(event, handler, bubble) {
var handlerx = wrap(handler);
return addEventListenerx.call(this, event, handlerx, bubble);
}
function removeEventListener(event, handler, bubble) {
handler = handler._witherror || handler;
removeEventListenerx.call(this, event, handler, bubble);
}
function wrap(fn) {
fn._witherror = witherror;
function witherror() {
try {
fn.apply(this, arguments);
} catch(e) {
window.onanyerror.apply(this, e);
throw e;
}
}
return fn;
}
}
/**
* Handle image/ajax request errors generically.
*/
function handleAsync(obj) {
var onerrorx = obj.onerror;
obj.onerror = onerror;
var onabortx = obj.onabort;
obj.onabort = onabort;
var onloadx = obj.onload;
obj.onload = onload;
/**
* Handle `onerror`.
*/
function onerror(error) {
window.onanyerror.call(this, error);
if (onerrorx) return onerrorx.apply(this, arguments);
};
/**
* Handle `onabort`.
*/
function onabort(error) {
window.onanyerror.call(this, error);
if (onabortx) return onabortx.apply(this, arguments);
};
/**
* Handle `onload`.
*
* For images, you can get a 403 response error,
* but this isn't triggered as a global on error.
* This sort of standardizes it.
*
* "there is no way to get the HTTP status from a
* request made by an img tag in JavaScript."
* @see http://stackoverflow.com/questions/8108636/how-to-get-http-status-code-of-img-tags/8108646#8108646
*/
function onload(request) {
if (request.status && request.status >= 400) {
window.onanyerror.call(this, request);
}
if (onloadx) return onloadx.apply(this, arguments);
}
}
/**
* Generic error handler.
*
* This shows the basic implementation,
* which you could override in your app.
*/
function onanyerrorx(entity) {
var display = entity;
// ajax request
if (entity instanceof XMLHttpRequest) {
// 400: http://example.com/image.png
display = entity.status + ' ' + entity.responseURL;
} else if (entity instanceof Event) {
// global window events, or image events
var target = entity.currentTarget;
display = target;
} else {
// not sure if there are others
}
capture(entity);
console.log('[onanyerror]', display, entity);
}
/**
* Capture stuff for debugging purposes.
*
* Keep them in memory so you can reference them
* in the chrome debugger as `onanyerror0` up to `onanyerror99`.
*/
function capture(entity) {
captures.push(entity);
if (captures.length > 100) captures.unshift();
// keep the last ones around
var i = captures.length;
while (--i) {
var x = captures[i];
window['onanyerror' + i] = x;
}
}
/**
* Wait til next code execution cycle as fast as possible.
*/
function onnext(fn) {
setTimeout(fn, 0);
}
})();
It could be used like this:
window.onanyerror = function(entity){
console.log('some error', entity);
};
The full script has a default implementation that tries to print out a semi-readable "display" version of the entity/error that it receives. Can be used for inspiration for an app-specific error handler. The default implementation also keeps a reference to the last 100 error entities, so you can inspect them in the web console after they occur like:
window.onanyerror0
window.onanyerror1
...
window.onanyerror99
Note: This works by overriding methods on several browser/native constructors. This can have unintended side-effects. However, it has been useful to use during development, to figure out where errors are occurring, to send logs to services like NewRelic or Sentry during development so we can measure errors during development, and on staging so we can debug what is going on at a deeper level. It can then be turned off in production.
Hope this helps.
Python 2.x: docs.python.org/2/library/httplib.html:
Note: HTTPS support is only available if the socket module was compiled with SSL support.
Python 3.x: docs.python.org/3/library/http.client.html:
Note HTTPS support is only available if Python was compiled with SSL support (through the ssl module).
#!/usr/bin/env python
import httplib
c = httplib.HTTPSConnection("ccc.de")
c.request("GET", "/")
response = c.getresponse()
print response.status, response.reason
data = response.read()
print data
# =>
# 200 OK
# <!DOCTYPE html ....
To verify if SSL is enabled, try:
>>> import socket
>>> socket.ssl
<function ssl at 0x4038b0>
You can also use Comparator.comparing(Function, Comparator)
It is convenient to chain comparators when necessary, e.g.:
Comparator<SomeEntity> ENTITY_COMPARATOR = comparing(SomeEntity::getProperty1, reverseOrder())
.thenComparingInt(SomeEntity::getProperty2)
.thenComparing(SomeEntity::getProperty3, reverseOrder());
On Windows 8.1, since .NET 4.5 is built-in, the fix is to run this from an administrative command-prompt:
dism.exe /Online /Enable-Feature /all /FeatureName:IIS-ASPNET45
If they're block level elements they won't be affected by text-align: center;
. Someone may have set img { display: block; }
and that's throwing it out of whack. You can try:
td { text-align: center; }
td * { display: inline; }
and if it looks as desired you should definitely replace * with the desired elements like:
td img, td foo { display: inline; }
Better use $_SERVER['REQUEST_METHOD']
:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// …
}
for MySQL all (and 5.7)
SELECT LOWER(TRIM(BOTH 0x22 FROM TRIM(BOTH 0x20 FROM SUBSTRING(SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"'),LOCATE(0x2C,SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"')+1,LENGTH(json_filed)))),LOCATE(0x22,SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"'),LOCATE(0x2C,SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"')+1,LENGTH(json_filed))))),LENGTH(json_filed))))) AS result FROM `table`;
eryksun has answered question #1, and I've answered question #3 (the original #4), but now let's answer question #2:
Why does it release 50.5mb in particular - what is the amount that is released based on?
What it's based on is, ultimately, a whole series of coincidences inside Python and malloc
that are very hard to predict.
First, depending on how you're measuring memory, you may only be measuring pages actually mapped into memory. In that case, any time a page gets swapped out by the pager, memory will show up as "freed", even though it hasn't been freed.
Or you may be measuring in-use pages, which may or may not count allocated-but-never-touched pages (on systems that optimistically over-allocate, like linux), pages that are allocated but tagged MADV_FREE
, etc.
If you really are measuring allocated pages (which is actually not a very useful thing to do, but it seems to be what you're asking about), and pages have really been deallocated, two circumstances in which this can happen: Either you've used brk
or equivalent to shrink the data segment (very rare nowadays), or you've used munmap
or similar to release a mapped segment. (There's also theoretically a minor variant to the latter, in that there are ways to release part of a mapped segment—e.g., steal it with MAP_FIXED
for a MADV_FREE
segment that you immediately unmap.)
But most programs don't directly allocate things out of memory pages; they use a malloc
-style allocator. When you call free
, the allocator can only release pages to the OS if you just happen to be free
ing the last live object in a mapping (or in the last N pages of the data segment). There's no way your application can reasonably predict this, or even detect that it happened in advance.
CPython makes this even more complicated—it has a custom 2-level object allocator on top of a custom memory allocator on top of malloc
. (See the source comments for a more detailed explanation.) And on top of that, even at the C API level, much less Python, you don't even directly control when the top-level objects are deallocated.
So, when you release an object, how do you know whether it's going to release memory to the OS? Well, first you have to know that you've released the last reference (including any internal references you didn't know about), allowing the GC to deallocate it. (Unlike other implementations, at least CPython will deallocate an object as soon as it's allowed to.) This usually deallocates at least two things at the next level down (e.g., for a string, you're releasing the PyString
object, and the string buffer).
If you do deallocate an object, to know whether this causes the next level down to deallocate a block of object storage, you have to know the internal state of the object allocator, as well as how it's implemented. (It obviously can't happen unless you're deallocating the last thing in the block, and even then, it may not happen.)
If you do deallocate a block of object storage, to know whether this causes a free
call, you have to know the internal state of the PyMem allocator, as well as how it's implemented. (Again, you have to be deallocating the last in-use block within a malloc
ed region, and even then, it may not happen.)
If you do free
a malloc
ed region, to know whether this causes an munmap
or equivalent (or brk
), you have to know the internal state of the malloc
, as well as how it's implemented. And this one, unlike the others, is highly platform-specific. (And again, you generally have to be deallocating the last in-use malloc
within an mmap
segment, and even then, it may not happen.)
So, if you want to understand why it happened to release exactly 50.5mb, you're going to have to trace it from the bottom up. Why did malloc
unmap 50.5mb worth of pages when you did those one or more free
calls (for probably a bit more than 50.5mb)? You'd have to read your platform's malloc
, and then walk the various tables and lists to see its current state. (On some platforms, it may even make use of system-level information, which is pretty much impossible to capture without making a snapshot of the system to inspect offline, but luckily this isn't usually a problem.) And then you have to do the same thing at the 3 levels above that.
So, the only useful answer to the question is "Because."
Unless you're doing resource-limited (e.g., embedded) development, you have no reason to care about these details.
And if you are doing resource-limited development, knowing these details is useless; you pretty much have to do an end-run around all those levels and specifically mmap
the memory you need at the application level (possibly with one simple, well-understood, application-specific zone allocator in between).
I cannot comment because of Karma so I write this as whole answer: According to the answer of Gareth (var e = arguments[0] || window.event; [...]) I used this oneliner inline on the onclick for a fast hack:
<div onclick="(arguments[0] || window.event).stopPropagation();">..</div>
I know it's late but I wanted to let you know that this works in one line. The braces return an event which has the stopPropagation-function attached in both cases, so I tried to encapsulate them in braces like in an if and....it works. :)
JButton
has a model which answers these question:
isArmed()
, isPressed()
, isRollOVer()
etc. Hence you can ask the model for the answer you are seeking:
if(jButton1.getModel().isPressed())
System.out.println("the button is pressed");
Do note that PostgreSQL 9.0 (today in beta testing) will have a simple way to do that:
test=> GRANT SELECT ON ALL TABLES IN SCHEMA public TO joeuser;
ACID properties are very old and important concept of database theory. I know that you can find lots of posts on this topic, but still I would like to start share answer on this because this is very important topic of RDBMS.
Database System plays with lots of different types of transactions where all transaction has certain characteristic. This characteristic is known ACID Properties. ACID Properties take grantee for all database transactions to accomplish all tasks.
Atomicity : Either commit all or nothing.
Consistency : Make consistent record in terms of validate all rule and constraint of transaction.
Isolation : Make sure that two transaction is unaware to each other.
Durability : committed data stored forever. Reference taken from this article:
In this case I would use a definition list as so:
<dl>
<dt>Fruits I like:</dt>
<dd>Apples</dd>
<dd>Bananas</dd>
<dd>Oranges</dd>
</dl>
Note the following is functionally different to Gordon Linoff's answer. His answer assumes that you want to use email2
if email
is NULL. Mine assumes you want to use email2
if email
is an empty-string. The correct answer will depend on your database (or you could perform a NULL check and an empty-string check - it all depends on what is appropriate for your database design).
SELECT `id` , `naam`
FROM `klanten`
WHERE `email` LIKE '%[email protected]%'
OR (LENGTH(email) = 0 AND `email2` LIKE '%[email protected]%')
It can also be done this way:
figure(xx);
set(gcf, 'name', 'Name goes here')
gcf
gets the current figure handle.
Also if you want selected field from table and aggregated then as array .
SELECT json_agg(json_build_object('data_a',a,
'data_b',b,
)) from t;
The result will come .
[{'data_a':1,'data_b':'value1'}
{'data_a':2,'data_b':'value2'}]
In addition to Mark Ransom's answer using ctypes: This does not work for (all?) x64 systems since the handles seem to be truncated to int-size. Explicitly defining args and return values helps to overcomes this problem.
import ctypes
import ctypes.wintypes as w
CF_UNICODETEXT = 13
u32 = ctypes.WinDLL('user32')
k32 = ctypes.WinDLL('kernel32')
OpenClipboard = u32.OpenClipboard
OpenClipboard.argtypes = w.HWND,
OpenClipboard.restype = w.BOOL
GetClipboardData = u32.GetClipboardData
GetClipboardData.argtypes = w.UINT,
GetClipboardData.restype = w.HANDLE
EmptyClipboard = u32.EmptyClipboard
EmptyClipboard.restype = w.BOOL
SetClipboardData = u32.SetClipboardData
SetClipboardData.argtypes = w.UINT, w.HANDLE,
SetClipboardData.restype = w.HANDLE
CloseClipboard = u32.CloseClipboard
CloseClipboard.argtypes = None
CloseClipboard.restype = w.BOOL
GHND = 0x0042
GlobalAlloc = k32.GlobalAlloc
GlobalAlloc.argtypes = w.UINT, w.ctypes.c_size_t,
GlobalAlloc.restype = w.HGLOBAL
GlobalLock = k32.GlobalLock
GlobalLock.argtypes = w.HGLOBAL,
GlobalLock.restype = w.LPVOID
GlobalUnlock = k32.GlobalUnlock
GlobalUnlock.argtypes = w.HGLOBAL,
GlobalUnlock.restype = w.BOOL
GlobalSize = k32.GlobalSize
GlobalSize.argtypes = w.HGLOBAL,
GlobalSize.restype = w.ctypes.c_size_t
unicode_type = type(u'')
def get():
text = None
OpenClipboard(None)
handle = GetClipboardData(CF_UNICODETEXT)
pcontents = GlobalLock(handle)
size = GlobalSize(handle)
if pcontents and size:
raw_data = ctypes.create_string_buffer(size)
ctypes.memmove(raw_data, pcontents, size)
text = raw_data.raw.decode('utf-16le').rstrip(u'\0')
GlobalUnlock(handle)
CloseClipboard()
return text
def put(s):
if not isinstance(s, unicode_type):
s = s.decode('mbcs')
data = s.encode('utf-16le')
OpenClipboard(None)
EmptyClipboard()
handle = GlobalAlloc(GHND, len(data) + 2)
pcontents = GlobalLock(handle)
ctypes.memmove(pcontents, data, len(data))
GlobalUnlock(handle)
SetClipboardData(CF_UNICODETEXT, handle)
CloseClipboard()
#Test run
paste = get
copy = put
copy("Hello World!")
print(paste())
py2exe is a Python Distutils extension which converts Python scripts into executable Windows programs, able to run without requiring a Python installation.
You need to modify the jenkins.xml file. Specifically you need to change
<arguments>-Xrs -Xmx256m
-Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle
-jar "%BASE%\jenkins.war" --httpPort=8080</arguments>
to
<arguments>-Xrs -Xmx2048m -XX:MaxPermSize=512m
-Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle
-jar "%BASE%\jenkins.war" --httpPort=8080</arguments>
You can also verify the Java options that Jenkins is using by installing the Jenkins monitor plugin via Manage Jenkins / Manage Plugins and then navigating to Managing Jenkins / Monitoring of Hudson / Jenkins master to use monitoring to determine how much memory is available to Jenkins.
If you are getting an out of memory error when Jenkins calls Maven, it may be necessary to set MAVEN_OPTS via Manage Jenkins / Configure System e.g. if you are running on a version of Java prior to JDK 1.8 (the values are suggestions):
-Xmx2048m -XX:MaxPermSize=512m
If you are using JDK 1.8:
-Xmx2048m
Since classList is supported in all major browsers and jQuery drops support for IE<9 (in 2.x branch as Stormblack points in the comment), considering this HTML
<div id="mydiv" class="oldclass">text</div>
you can comfortably use this syntax:
document.getElementById('mydiv').classList.add("newClass");
This will also result in:
<div id="mydiv" class="oldclass newclass">text</div>
plus you can also use remove, toggle, contains methods.
You can use angularjs form state form.$submitted
.
Initially form.$submitted
value will be false
and will became true
after successful form submit.
The solution above was not working for me. I had to set 'class count to use import with '*'' to a high value, e.g. 999.
The aim of using StringBuilder, i.e reducing memory. Is it achieved?
No, not at all. That code is not using StringBuilder
correctly. (I think you've misquoted it, though; surely there aren't quotes around id2
and table
?)
Note that the aim (usually) is to reduce memory churn rather than total memory used, to make life a bit easier on the garbage collector.
Will that take memory equal to using String like below?
No, it'll cause more memory churn than just the straight concat you quoted. (Until/unless the JVM optimizer sees that the explicit StringBuilder
in the code is unnecessary and optimizes it out, if it can.)
If the author of that code wants to use StringBuilder
(there are arguments for, but also against; see note at the end of this answer), better to do it properly (here I'm assuming there aren't actually quotes around id2
and table
):
StringBuilder sb = new StringBuilder(some_appropriate_size);
sb.append("select id1, ");
sb.append(id2);
sb.append(" from ");
sb.append(table);
return sb.toString();
Note that I've listed some_appropriate_size
in the StringBuilder
constructor, so that it starts out with enough capacity for the full content we're going to append. The default size used if you don't specify one is 16 characters, which is usually too small and results in the StringBuilder
having to do reallocations to make itself bigger (IIRC, in the Sun/Oracle JDK, it doubles itself [or more, if it knows it needs more to satisfy a specific append
] each time it runs out of room).
You may have heard that string concatenation will use a StringBuilder
under the covers if compiled with the Sun/Oracle compiler. This is true, it will use one StringBuilder
for the overall expression. But it will use the default constructor, which means in the majority of cases, it will have to do a reallocation. It's easier to read, though. Note that this is not true of a series of concatenations. So for instance, this uses one StringBuilder
:
return "prefix " + variable1 + " middle " + variable2 + " end";
It roughly translates to:
StringBuilder tmp = new StringBuilder(); // Using default 16 character size
tmp.append("prefix ");
tmp.append(variable1);
tmp.append(" middle ");
tmp.append(variable2);
tmp.append(" end");
return tmp.toString();
So that's okay, although the default constructor and subsequent reallocation(s) isn't ideal, the odds are it's good enough — and the concatenation is a lot more readable.
But that's only for a single expression. Multiple StringBuilder
s are used for this:
String s;
s = "prefix ";
s += variable1;
s += " middle ";
s += variable2;
s += " end";
return s;
That ends up becoming something like this:
String s;
StringBuilder tmp;
s = "prefix ";
tmp = new StringBuilder();
tmp.append(s);
tmp.append(variable1);
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(" middle ");
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(variable2);
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(" end");
s = tmp.toString();
return s;
...which is pretty ugly.
It's important to remember, though, that in all but a very few cases it doesn't matter and going with readability (which enhances maintainability) is preferred barring a specific performance issue.
The file extension .command is assigned to Terminal.app. Double-clicking on any .command file will execute it.
I think the following class code will help you. It supports multithreading but you can do some improvement like remove sync block and and sync to getRandomId() method.
public class RandomNumberGenerator {
private static final Set<String> generatedNumbers = new HashSet<String>();
public RandomNumberGenerator() {
}
public static void main(String[] args) {
final int maxLength = 7;
final int maxTry = 10;
for (int i = 0; i < 10; i++) {
System.out.println(i + ". studentId=" + RandomNumberGenerator.getRandomId(maxLength, maxTry));
}
}
public static String getRandomId(final int maxLength, final int maxTry) {
final Random random = new Random(System.nanoTime());
final int max = (int) Math.pow(10, maxLength);
final int maxMin = (int) Math.pow(10, maxLength-1);
int i = 0;
boolean unique = false;
int randomId = -1;
while (i < maxTry) {
randomId = random.nextInt(max - maxMin - 1) + maxMin;
synchronized (generatedNumbers) {
if (generatedNumbers.contains(randomId) == false) {
unique = true;
break;
}
}
i++;
}
if (unique == false) {
throw new RuntimeException("Cannot generate unique id!");
}
synchronized (generatedNumbers) {
generatedNumbers.add(String.valueOf(randomId));
}
return String.valueOf(randomId);
}
}
General ternary syntax:
value_true if <test> else value_false
Another way can be:
[value_false, value_true][<test>]
e.g:
count = [0,N+1][count==N]
This evaluates both branches before choosing one. To only evaluate the chosen branch:
[lambda: value_false, lambda: value_true][<test>]()
e.g.:
count = [lambda:0, lambda:N+1][count==N]()
For you to output foo {1, 2, 3}
you have to do something like:
string t = "1, 2, 3";
string v = String.Format(" foo {{{0}}}", t);
To output a {
you use {{
and to output a }
you use }}
.
or Now, you can also use c# string interpolation like this (feature available in C# 6.0)
Escaping Brackets: String Interpolation $(""). it is new feature in C# 6.0
var inVal = "1, 2, 3";
var outVal = $" foo {{{inVal}}}";
//Output will be: foo {1, 2, 3}
you can use this file (https://github.com/louisremi/background-size-polyfill “background-size polyfill”) for IE8 that is really simple to use:
.selector {
background-size: cover;
-ms-behavior: url(/backgroundsize.min.htc);
}
function resize() {resizeFrame(elemento, margin);};
jQuery.event.add(window, "load", resize);
jQuery.event.add(window, "resize", resize);
function resizeFrame(item, marge) {
$(item).each(function() {
var m = marge*2;
var mw = $(window).width()-m;
var mh = $(window).height()-m;
var w = $('img',this).width();
var h = $('img',this).height();
var mr = mh/mw;
var cr = h/w;
$('img',this).css({position:'absolute',minWidth:(w-w)+20,minHeight:(h-h)+20,margin:'auto',top:'0',right:'0',bottom:'0',left:'0',padding:marge});
if(cr < mr){
var r = mw/w;
$('img',this).css({width: mw});
$('img',this).css({height: h*r});
}else if(cr > mr){
var r = mh/h;
$('img',this).css({height: mh});
$('img',this).css({width: w*r});
}
});
}
For MAMP 3.5 Mac El Capitan, create a separate empty config file and write your additional settings for mysql
sudo vim /Applications/MAMP/Library/my.cnf
And Add like this
[mysqld]
max_allowed_packet = 256M
Try this site http://www.sharelinkgenerator.com/. Hope this helps.
I recently needed to document how to get a version of it installed, so I've copied my steps here, as the other answers were using different sources from what I recommend, which is Cygwin. I like Cygwin because it is well maintained and provides a wealth of other utilities for Windows. Cygwin also allows you to easily update the versions as needed when vulnerabilities are fixed. Please update your version of OpenSSL often!
Open a Windows Command prompt and check to see if you have OpenSSL installed by entering: openssl version
If you get an error message that the command is NOT recognized, then install OpenSSL by referring to Cygwin following the summary steps below:
Basically, download and run the Cygwin Windows Setup App to install and to update as needed the OpenSSL application:
C:\Program Files\mosquitto>openssl versionOpenSSL 1.1.1f 31 Mar 2020
You need to close the connection before you can use the output parameters. Something like this
con.Close();
MessageBox.Show(cmd.Parameters["@code"].Value.ToString());
The file basically contain data for two new tables.
Then you may find it simpler to just DTS (or SSIS, if this is SQL Server 2005+) the data over, if the two servers are on the same network.
If the two servers are not on the same network, you can backup the source database and restore it to a new database on the destination server. Then you can use DTS/SSIS, or even a simple INSERT INTO SELECT
, to transfer the two tables to the destination database.
You were close. format=
needs to be added to the as.Date
call:
mydate <- factor("1/15/2006 0:00:00")
as.Date(mydate, format = "%m/%d/%Y")
## [1] "2006-01-15"
----------_x000D_
_x000D_
_x000D_
<?php_x000D_
echo '<div style="text-align:center;padding-top:200px;">Go New Page</div>'; _x000D_
$gourl='http://stackoverflow.com';_x000D_
echo '<META HTTP-EQUIV="Refresh" Content="2; URL='.$gourl.'">'; _x000D_
exit;_x000D_
_x000D_
?>_x000D_
_x000D_
_x000D_
----------
_x000D_
public async Task<bool> Update(MyObject item)
{
Context.Entry(await Context.MyDbSet.FirstOrDefaultAsync(x => x.Id == item.Id)).CurrentValues.SetValues(item);
return (await Context.SaveChangesAsync()) > 0;
}
To see both the normal distribution and your actual data you should plot your data as a histogram, then draw the probability density function over this. See the example on https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.normal.html for exactly how to do this.
Incorrect:
SELECT * FROM customers WHERE name LIKE '%Bob Smith%';
Instead:
select count(*)
from rearp.customers c
where c.name LIKE '%Bob smith.8%';
select count
will just query (totals)
C
will link the db.table to the names row you need this to index
LIKE
should be obvs
8
will call all references in DB 8 or less (not really needed but i like neatness)
The only problem with JSON in Java is that if your XML has a single child, but is an array, it will convert it to an object instead of an array. This can cause problems if you dynamically always convert from XML to JSON, where if your example XML has only one element, you return an object, but if it has 2+, you return an array, which can cause parsing issues for people using the JSON.
Infoscoop's XML2JSON class has a way of tagging elements that are arrays before doing the conversion, so that arrays can be properly mapped, even if there is only one child in the XML.
Here is an example of using it (in a slightly different language, but you can also see how arrays is used from the nodelist2json() method of the XML2JSON link).
USE update_attribute instead of update_attributes
Updates a single attribute and saves the record without going through the normal validation procedure.
if a.update_attribute('state', a.state)
Note:- 'update_attribute' update only one attribute at a time from the code given in question i think it will work for you.
I also read the answers and comments and tried some solutions from this thread.
Then a Googled a little more and this worked for me
https://www.c-sharpcorner.com/blogs/iis-express-failed-to-register-url-access-is-denied
Didn't comment on no one's answer because I didn't read whats written here, so it needed a new answer post. There's answers here that talk about netsh wlan stuff, but I didn't see exactly this solution. If some one wrote the exact same solution please tell me so I can comment there and remove this.
How to resize root partition online :
1) [root@oel7 ~]# df -h
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/root_vg-root 5.0G 4.5G 548M 90% /
2)
PV /dev/sda2 VG root_vg lvm2 [6.00 GiB / 0 free]
as here it shows that there is no space left on root_vg volume group, so first i need to extend VG
3)
[root@oel7 ~]# vgextend root_vg /dev/sdb5
Volume group "root_vg" successfully extended
4)
[root@oel7 ~]# pvscan
PV /dev/sda2 VG root_vg lvm2 [6.00 GiB / 0 free]
PV /dev/sdb5 VG root_vg lvm2 [2.00 GiB / 2.00 GiB free]
5) Now extend the logical volume
[root@oel7 ~]# lvextend -L +1G /dev/root_vg/root
Size of logical volume root_vg/root changed from 5.00 GiB (1280 extents) to 6.00 GiB (1536 extents).
Logical volume root successfully resized
3) [root@oel7 ~]# resize2fs /dev/root_vg/root
resize2fs 1.42.9 (28-Dec-2013)
resize2fs: Bad magic number in super-block while trying to open /dev/root_vg /root
Couldn't find valid filesystem superblock.
as root partition is not a ext* partiton so , you resize2fs will not work for you.
4) to check the filesystem type of a partition
[root@oel7 ~]# df -Th
Filesystem Type Size Used Avail Use% Mounted on
/dev/mapper/root_vg-root xfs 6.0G 4.5G 1.6G 75% /
devtmpfs devtmpfs 481M 0 481M 0% /dev
tmpfs tmpfs 491M 80K 491M 1% /dev/shm
tmpfs tmpfs 491M 7.1M 484M 2% /run
tmpfs tmpfs 491M 0 491M 0% /sys/fs /cgroup
/dev/mapper/data_vg-home xfs 3.5G 2.9G 620M 83% /home
/dev/sda1 xfs 497M 132M 365M 27% /boot
/dev/mapper/data_vg01-data_lv001 ext3 4.0G 2.4G 1.5G 62% /sybase
/dev/mapper/data_vg02-backup_lv01 ext3 4.0G 806M 3.0G 22% /backup
above command shows that root is an xfs filesystem , so we are sure that we need to use xfs_growfs command to resize the partition.
6) [root@oel7 ~]# xfs_growfs /dev/root_vg/root
meta-data=/dev/mapper/root_vg-root isize=256 agcount=4, agsize=327680 blks
= sectsz=512 attr=2, projid32bit=1
= crc=0 finobt=0
data = bsize=4096 blocks=1310720, imaxpct=25
= sunit=0 swidth=0 blks
naming =version 2 bsize=4096 ascii-ci=0 ftype=0
log =internal bsize=4096 blocks=2560, version=2
= sectsz=512 sunit=0 blks, lazy-count=1
realtime =none extsz=4096 blocks=0, rtextents=0
data blocks changed from 1310720 to 1572864
[root@oel7 ~]# df -Th
Filesystem Type Size Used Avail Use% Mounted on
/dev/mapper/root_vg-root xfs 6.0G 4.5G 1.6G 75% /