Checking null with normal equality will also return true for undefined.
if (window.variable == null) alert('variable is null or undefined');
When I had similar problem gem update --system
helped me. Run this before bundle install
Thanks @Fedrico A. for the Phyton implementation, I have ported it into a Objective C category class. Here is:
#import "LocationService+Bounds.h"
//Semi-axes of WGS-84 geoidal reference
const double WGS84_a = 6378137.0; //Major semiaxis [m]
const double WGS84_b = 6356752.3; //Minor semiaxis [m]
@implementation LocationService (Bounds)
struct BoundsLocation {
double maxLatitude;
double minLatitude;
double maxLongitude;
double minLongitude;
};
+ (struct BoundsLocation)locationBoundsWithLatitude:(double)aLatitude longitude:(double)aLongitude maxDistanceKm:(NSInteger)aMaxKmDistance {
return [self boundingBoxWithLatitude:aLatitude longitude:aLongitude halfDistanceKm:aMaxKmDistance/2];
}
#pragma mark - Algorithm
+ (struct BoundsLocation)boundingBoxWithLatitude:(double)aLatitude longitude:(double)aLongitude halfDistanceKm:(double)aDistanceKm {
double radianLatitude = [self degreesToRadians:aLatitude];
double radianLongitude = [self degreesToRadians:aLongitude];
double halfDistanceMeters = aDistanceKm*1000;
double earthRadius = [self earthRadiusAtLatitude:radianLatitude];
double parallelRadius = earthRadius*cosl(radianLatitude);
double radianMinLatitude = radianLatitude - halfDistanceMeters/earthRadius;
double radianMaxLatitude = radianLatitude + halfDistanceMeters/earthRadius;
double radianMinLongitude = radianLongitude - halfDistanceMeters/parallelRadius;
double radianMaxLongitude = radianLongitude + halfDistanceMeters/parallelRadius;
struct BoundsLocation bounds;
bounds.minLatitude = [self radiansToDegrees:radianMinLatitude];
bounds.maxLatitude = [self radiansToDegrees:radianMaxLatitude];
bounds.minLongitude = [self radiansToDegrees:radianMinLongitude];
bounds.maxLongitude = [self radiansToDegrees:radianMaxLongitude];
return bounds;
}
+ (double)earthRadiusAtLatitude:(double)aRadianLatitude {
double An = WGS84_a * WGS84_a * cosl(aRadianLatitude);
double Bn = WGS84_b * WGS84_b * sinl(aRadianLatitude);
double Ad = WGS84_a * cosl(aRadianLatitude);
double Bd = WGS84_b * sinl(aRadianLatitude);
return sqrtl( ((An * An) + (Bn * Bn))/((Ad * Ad) + (Bd * Bd)) );
}
+ (double)degreesToRadians:(double)aDegrees {
return M_PI*aDegrees/180.0;
}
+ (double)radiansToDegrees:(double)aRadians {
return 180.0*aRadians/M_PI;
}
@end
I have tested it and seems be working nice. Struct BoundsLocation should be replaced by a class, I have used it just to share it here.
Hi You can use a simple query,
select emp_cd, val1, val2, val3,
(val1+val2+val3) as total
from emp;
In case you need to insert a new row,
insert into emp select emp_cd, val1, val2, val3,
(val1+val2+val3) as total
from emp;
In order to update,
update emp set total = val1+val2+val3;
This will update for all comumns
Javax used to be only for extensions. Yet later sun added it to the java libary forgetting to remove the x. Developers started making code with javax. Yet later on in time suns decided to change it to java. Developers didn't like the idea because they're code would be ruined... so javax was kept.
Interesting artcle...
I've had a quick hunt around on google and found nothing, but you might want to check some of the comments - plenty of people seem to have had a go at implementing a simple component demo, you might want to take a look at some of theirs for inspiration:
http://www.unseen-academy.de/componentSystem.html
http://www.mcshaffry.com/GameCode/thread.php?threadid=732
http://www.codeplex.com/Wikipage?ProjectName=elephant
Also, the comments themselves seem to have a fairly in-depth discussion on how you might code up such a system.
Its hacked by CustomPagerAdapter:
MainActivity.java:
import android.content.Context;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private List<String> numberList = new ArrayList<String>();
private CustomPagerAdapter mCustomPagerAdapter;
private ViewPager mViewPager;
private Handler handler;
private Runnable runnable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
numberList.clear();
for (int i = 0; i < 10; i++) {
numberList.add(""+i);
}
mViewPager = (ViewPager)findViewById(R.id.pager);
mCustomPagerAdapter = new CustomPagerAdapter(MainActivity.this);
EndlessPagerAdapter mAdapater = new EndlessPagerAdapter(mCustomPagerAdapter);
mViewPager.setAdapter(mAdapater);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
int modulo = position%numberList.size();
Log.i("Current ViewPager View's Position", ""+modulo);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
mViewPager.setCurrentItem(mViewPager.getCurrentItem()+1);
handler.postDelayed(runnable, 1000);
}
};
handler.post(runnable);
}
@Override
protected void onDestroy() {
if(handler!=null){
handler.removeCallbacks(runnable);
}
super.onDestroy();
}
private class CustomPagerAdapter extends PagerAdapter {
Context mContext;
LayoutInflater mLayoutInflater;
public CustomPagerAdapter(Context context) {
mContext = context;
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return numberList.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
View itemView = mLayoutInflater.inflate(R.layout.row_item_viewpager, container, false);
TextView textView = (TextView) itemView.findViewById(R.id.txtItem);
textView.setText(numberList.get(position));
container.addView(itemView);
return itemView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
}
private class EndlessPagerAdapter extends PagerAdapter {
private static final String TAG = "EndlessPagerAdapter";
private static final boolean DEBUG = false;
private final PagerAdapter mPagerAdapter;
EndlessPagerAdapter(PagerAdapter pagerAdapter) {
if (pagerAdapter == null) {
throw new IllegalArgumentException("Did you forget initialize PagerAdapter?");
}
if ((pagerAdapter instanceof FragmentPagerAdapter || pagerAdapter instanceof FragmentStatePagerAdapter) && pagerAdapter.getCount() < 3) {
throw new IllegalArgumentException("When you use FragmentPagerAdapter or FragmentStatePagerAdapter, it only supports >= 3 pages.");
}
mPagerAdapter = pagerAdapter;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
if (DEBUG) Log.d(TAG, "Destroy: " + getVirtualPosition(position));
mPagerAdapter.destroyItem(container, getVirtualPosition(position), object);
if (mPagerAdapter.getCount() < 4) {
mPagerAdapter.instantiateItem(container, getVirtualPosition(position));
}
}
@Override
public void finishUpdate(ViewGroup container) {
mPagerAdapter.finishUpdate(container);
}
@Override
public int getCount() {
return Integer.MAX_VALUE; // this is the magic that we can scroll infinitely.
}
@Override
public CharSequence getPageTitle(int position) {
return mPagerAdapter.getPageTitle(getVirtualPosition(position));
}
@Override
public float getPageWidth(int position) {
return mPagerAdapter.getPageWidth(getVirtualPosition(position));
}
@Override
public boolean isViewFromObject(View view, Object o) {
return mPagerAdapter.isViewFromObject(view, o);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
if (DEBUG) Log.d(TAG, "Instantiate: " + getVirtualPosition(position));
return mPagerAdapter.instantiateItem(container, getVirtualPosition(position));
}
@Override
public Parcelable saveState() {
return mPagerAdapter.saveState();
}
@Override
public void restoreState(Parcelable state, ClassLoader loader) {
mPagerAdapter.restoreState(state, loader);
}
@Override
public void startUpdate(ViewGroup container) {
mPagerAdapter.startUpdate(container);
}
int getVirtualPosition(int realPosition) {
return realPosition % mPagerAdapter.getCount();
}
PagerAdapter getPagerAdapter() {
return mPagerAdapter;
}
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="180dp">
</android.support.v4.view.ViewPager>
</RelativeLayout>
row_item_viewpager.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/txtItem"
android:textAppearance="@android:style/TextAppearance.Large"/>
</LinearLayout>
Done
I have add this input tag into form tag..
<form id="form_data">
<input type="file" id="file_data" name="browse"
(change)="handleFileInput($event, dataFile, f)" />
</form>
I angular typescript, I have added below lines, get your form id in document forms and make that value as null.
for(let i=0; i<document.forms.length;i++){
if(document.forms[i].length > 0){
if(document.forms[i][0]['value']){ //document.forms[i][0] = "file_data"
document.forms[i][0]['value'] = "";
}
}
}
Print document.forms in console and you can get idea..
Create two partial indexes:
CREATE UNIQUE INDEX favo_3col_uni_idx ON favorites (user_id, menu_id, recipe_id)
WHERE menu_id IS NOT NULL;
CREATE UNIQUE INDEX favo_2col_uni_idx ON favorites (user_id, recipe_id)
WHERE menu_id IS NULL;
This way, there can only be one combination of (user_id, recipe_id)
where menu_id IS NULL
, effectively implementing the desired constraint.
Possible drawbacks: you cannot have a foreign key referencing (user_id, menu_id, recipe_id)
, you cannot base CLUSTER
on a partial index, and queries without a matching WHERE
condition cannot use the partial index. (It seems unlikely you'd want a FK reference three columns wide - use the PK column instead).
If you need a complete index, you can alternatively drop the WHERE
condition from favo_3col_uni_idx
and your requirements are still enforced.
The index, now comprising the whole table, overlaps with the other one and gets bigger. Depending on typical queries and the percentage of NULL
values, this may or may not be useful. In extreme situations it might even help to maintain all three indexes (the two partial ones and a total on top).
Aside: I advise not to use mixed case identifiers in PostgreSQL.
Taken from the Multimarkdown Users Guide (thanks to @MultiMarkdown on Twitter for pointing it out)
[Some Text][]
will link to a header named “Some Text”
e.g.
### Some Text ###
An optional label of your choosing to help disambiguate cases where multiple headers have the same title:
### Overview [MultiMarkdownOverview] ##
This allows you to use [MultiMarkdownOverview] to refer to this section specifically, and not another section named Overview. This works with atx- or settext-style headers.
If you have already defined an anchor using the same id that is used by a header, then the defined anchor takes precedence.
In addition to headers within the document, you can provide labels for images and tables which can then be used for cross-references as well.
anyItem has never been declared as a variable, so it makes sense that it causes an error. But more importantly, you have code after a return statement and this will cause an unreachable code error.
To increase the height of TextField Widget just make use of the maxLines: properties that comes with the widget. For Example: TextField( maxLines: 5 ) // it will increase the height and width of the Textfield.
You need to add a name
attribute.
Since this is a multiple select, at the HTTP level, the client just sends multiple name/value pairs with the same name, you can observe this yourself if you use a form with method="GET": someurl?something=1&something=2&something=3
.
In the case of PHP, Ruby, and some other library/frameworks out there, you would need to add square braces ([]
) at the end of the name. The frameworks will parse that string and wil present it in some easy to use format, like an array.
Apart from manually parsing the request there's no language/framework/library-agnostic way of accessing multiple values, because they all have different APIs
For PHP you can use:
<select name="something[]" id="inscompSelected" multiple="multiple" class="lstSelected">
You could do something with APIs.
Private Const SW_SHOW = 5
Private Const GW_HWNDNEXT = 2
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
(ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function ShowWindow Lib "user32" _
(ByVal hWnd As Long, ByVal nCmdShow As Long) As Long
Private Declare Function GetWindow Lib "user32" _
(ByVal hWnd As Long, ByVal wCmd As Long) As Long
Private Declare Function GetClassName Lib "user32" Alias "GetClassNameA" _
(ByVal hWnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long
Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" _
(ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Function FindWindowPartialX(ByVal Title As String) As Long
Dim hWndThis As Long
hWndThis = FindWindow(vbNullString, vbNullString)
While hWndThis
Dim sTitle As String, sClass As String
sTitle = Space$(255)
sTitle = Left$(sTitle, GetWindowText(hWndThis, sTitle, Len(sTitle)))
sClass = Space$(255)
sClass = Left$(sClass, GetClassName(hWndThis, sClass, Len(sClass)))
If InStr(sTitle, Title) > 0 Then
FindWindowPartialX = hWndThis
Exit Function
End If
hWndThis = GetWindow(hWndThis, GW_HWNDNEXT)
Wend
End Function
Sub CopySheet()
Dim objXL As Excel.Application
' A suitable portion of the window title such as file name '
WinHandle = FindWindowPartialX("LTD.xls")
ShowWindow WinHandle, SW_SHOW
Set objXL = GetObject(, "Excel.Application")
objXL.Worksheets("Source").Activate
objXL.ActiveSheet.UsedRange.Copy
Application.ActiveSheet.Paste
End Sub
If you want to check if some string is present in another string, use something like String.contains
If you want to check if some pattern is present in a string, append and prepend the pattern with '.*'. The result will accept strings that contain the pattern.
Example: Suppose you have some regex a(b|c) that checks if a string matches ab
or ac
.*(a(b|c)).*
will check if a string contains a ab
or ac
.
A disadvantage of this method is that it will not give you the location of the match.
Adding break
resolves your issue. You can store more than a record in a cell as markdown doesn't support much features.
Another alternative is the old school NET USER commands:
NET USER username "password" /ADD
OK - you can't set all the options but it's a lot less convoluted for simple user creation & easy to script up in Powershell.
NET LOCALGROUP "group" "user" /add
to set group membership.
It also has a syntax similar to prinft, e.g.:
qDebug ("message %d, says: %s",num,str);
Very handy as well
You should use the following code :
Class2 cls2 = new Class2();
cls2.UpdateEmployee();
In case you don't want to create a new instance to call the method, you can decalre the method as static
and then you can just call Class2.UpdateEmployee()
.
echo '<pre>';
foreach($data as $entry){
foreach($entry as $entry2){
echo $entry2.'<br />';
}
}
First, you're missing some parentheses in your conditional:
if ($("#about").hasClass("opened")) {
$("#about").animate({right: "-700px"}, 2000);
}
But you can also simplify this to:
$('#about.opened').animate(...);
If #about
doesn't have the opened
class, it won't animate.
If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)
You're interested in the collation. You could build something based on this snippet:
SELECT DATABASEPROPERTYEX('master', 'Collation');
Update
Based on your edit — If @test
and @TEST
can ever refer to two different variables, it's not SQL Server. If you see problems where the same variable is not equal to itself, check if that variable is NULL
, because NULL = NULL
returns `false.
An example using javascript, for comparison:
https://jsfiddle.net/drzaus/Lxsa4rpz/
function calcNormalAvg(list) {
// sum(list) / len(list)
return list.reduce(function(a, b) { return a + b; }) / list.length;
}
function calcRunningAvg(previousAverage, currentNumber, index) {
// [ avg' * (n-1) + x ] / n
return ( previousAverage * (index - 1) + currentNumber ) / index;
}
(function(){_x000D_
// populate base list_x000D_
var list = [];_x000D_
function getSeedNumber() { return Math.random()*100; }_x000D_
for(var i = 0; i < 50; i++) list.push( getSeedNumber() );_x000D_
_x000D_
// our calculation functions, for comparison_x000D_
function calcNormalAvg(list) {_x000D_
// sum(list) / len(list)_x000D_
return list.reduce(function(a, b) { return a + b; }) / list.length;_x000D_
}_x000D_
function calcRunningAvg(previousAverage, currentNumber, index) {_x000D_
// [ avg' * (n-1) + x ] / n_x000D_
return ( previousAverage * (index - 1) + currentNumber ) / index;_x000D_
}_x000D_
function calcMovingAvg(accumulator, new_value, alpha) {_x000D_
return (alpha * new_value) + (1.0 - alpha) * accumulator;_x000D_
}_x000D_
_x000D_
// start our baseline_x000D_
var baseAvg = calcNormalAvg(list);_x000D_
var runningAvg = baseAvg, movingAvg = baseAvg;_x000D_
console.log('base avg: %d', baseAvg);_x000D_
_x000D_
var okay = true;_x000D_
_x000D_
// table of output, cleaner console view_x000D_
var results = [];_x000D_
_x000D_
// add 10 more numbers to the list and compare calculations_x000D_
for(var n = list.length, i = 0; i < 10; i++, n++) {_x000D_
var newNumber = getSeedNumber();_x000D_
_x000D_
runningAvg = calcRunningAvg(runningAvg, newNumber, n+1);_x000D_
movingAvg = calcMovingAvg(movingAvg, newNumber, 1/(n+1));_x000D_
_x000D_
list.push(newNumber);_x000D_
baseAvg = calcNormalAvg(list);_x000D_
_x000D_
// assert and inspect_x000D_
console.log('added [%d] to list at pos %d, running avg = %d vs. regular avg = %d (%s), vs. moving avg = %d (%s)'_x000D_
, newNumber, list.length, runningAvg, baseAvg, runningAvg == baseAvg, movingAvg, movingAvg == baseAvg_x000D_
)_x000D_
results.push( {x: newNumber, n:list.length, regular: baseAvg, running: runningAvg, moving: movingAvg, eqRun: baseAvg == runningAvg, eqMov: baseAvg == movingAvg } );_x000D_
_x000D_
if(runningAvg != baseAvg) console.warn('Fail!');_x000D_
okay = okay && (runningAvg == baseAvg); _x000D_
}_x000D_
_x000D_
console.log('Everything matched for running avg? %s', okay);_x000D_
if(console.table) console.table(results);_x000D_
})();
_x000D_
var result = controller.ActioName(objParams);
IDictionary<string, object> data = (IDictionary<string, object>)new System.Web.Routing.RouteValueDictionary(result.Data);
Assert.AreEqual("Table already exists.", data["Message"]);
AngularJS directives ng-show, ng-hide allows to display and hide a row:
<tr ng-show="rw.isExpanded">
</tr>
A row will be visible when rw.isExpanded == true and hidden when rw.isExpanded == false. ng-hide performs the same task but requires inverse condition.
That's because arc4random_uniform() is defined as follows:
func arc4random_uniform(_: UInt32) -> UInt32
It takes a UInt32 as input, and spits out a UInt32. You're attempting to pass it a range of values. arc4random_uniform gives you a random number in between 0 and and the number you pass it (exclusively), so if for example, you wanted to find a random number between -50 and 50, as in [-50, 50]
you could use arc4random_uniform(101) - 50
Pip has no way of knowing what packages were installed by it and what packages were installed by your system's package manager. For this you would need to do something like this
for rpm-based distros (replace python2.7 with your python version you installed pip with):
find /usr/lib/python2.7/ |while read f; do
if ! rpm -qf "$f" &> /dev/null; then
echo "$f"
fi
done |xargs rm -fr
for a deb-based distribution:
find /usr/lib/python2.7/ |while read f; do
if ! dpkg-query -S "$f" &> /dev/null; then
echo "$f"
fi
done |xargs rm -fr
then to clean up empty directories left over:
find /usr/lib/python2.7 -type d -empty |xargs rm -fr
I found the top answer very misleading since it will remove all (most?) python packages from your distribution and probably leave you with a broken system.
Or create a function that creates an element including attributes from parameters
function elemCreate(elType){
var element = document.createElement(elType);
if (arguments.length>1){
var props = [].slice.call(arguments,1), key = props.shift();
while (key){
element.setAttribute(key,props.shift());
key = props.shift();
}
}
return element;
}
// usage
var img = elemCreate('img',
'width','100',
'height','100',
'src','http://example.com/something.jpeg');
FYI: height/width='100%'
would not work using attributes. For a height/width of 100% you need the elements style.height/style.width
anon and chepner's answers are on the right track. Python 3.x has a print function and this is what you will need if you want to embed print within a function (and, a fortiori, lambdas).
However, you can get the print function very easily in python 2.x by importing from the standard library's future module. Check it out:
>>>from __future__ import print_function
>>>
>>>iterable = ["a","b","c"]
>>>map(print, iterable)
a
b
c
[None, None, None]
>>>
I guess that looks kind of weird, so feel free to assign the return to _ if you would like to suppress [None, None, None]'s output (you are interested in the side-effects only, I assume):
>>>_ = map(print, iterable)
a
b
c
>>>
I don't know if this question is still relevant, but there is such possibility in Postman now. They added it a few months ago.
All you need is create simple .js file and run it via node.js. It looks like this:
var path = require('path'),
async = require('async'), //https://www.npmjs.com/package/async
newman = require('newman'),
parametersForTestRun = {
collection: path.join(__dirname, 'postman_collection.json'), // your collection
environment: path.join(__dirname, 'postman_environment.json'), //your env
};
parallelCollectionRun = function(done) {
newman.run(parametersForTestRun, done);
};
// Runs the Postman sample collection thrice, in parallel.
async.parallel([
parallelCollectionRun,
parallelCollectionRun,
parallelCollectionRun
],
function(err, results) {
err && console.error(err);
results.forEach(function(result) {
var failures = result.run.failures;
console.info(failures.length ? JSON.stringify(failures.failures, null, 2) :
`${result.collection.name} ran successfully.`);
});
});
Then just run this .js file ('node fileName.js' in cmd).
More details here
List<string> empnames = (from e in emplist select e.Enaame).ToList();
Or
string[] empnames = (from e in emplist select e.Enaame).ToArray();
Etc...
There's multiple ways of doing things in batch, so if escaping with a double percent %%
isn't working for you, then you could try something like this:
set olddir=%CD%
cd /d "path of folder"
del "file name/ or *.txt etc..."
cd /d "%olddir%"
How this works:
set olddir=%CD%
sets the variable "olddir"
or any other variable name you like to the directory
your batch file was launched from.
cd /d "path of folder"
changes the current directory the batch will be looking at. keep the
quotations and change path of folder to which ever path you aiming for.
del "file name/ or *.txt etc..."
will delete the file in the current directory your batch is looking at, just don't add a directory path before the file name and just have the full file name or, to delete multiple files with the same extension with *.txt
or whatever extension you need.
cd /d "%olddir%"
takes the variable saved with your old path and goes back to the directory you started the batch with, its not important if you don't want the batch going back to its previous directory path, and like stated before the variable name can be changed to whatever you wish by changing the set olddir=%CD% line
.
The display:table
family of CSS properties is mostly there so that HTML tables can be defined in terms of them. Because they're so intimately linked to a specific tag structure, they don't see much use beyond that.
If you were going to use these properties in your page, you would need a tag structure that closely mimicked that of tables, even though you weren't actually using the <table>
family of tags. A minimal version would be a single container element (display:table
), with direct children that can all be represented as rows (display:table-row
), which themselves have direct children that can all be represented as cells (display:table-cell
). There are other properties that let you mimic other tags in the table
family, but they require analogous structures in the HTML. Without this, it's going to be very hard (if not impossible) to make good use of these properties.
DateTime
doesn't have a default key as an input. The default key should be an input to the Column
function. Try this:
import datetime
from sqlalchemy import Column, Integer, DateTime
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Test(Base):
__tablename__ = 'test'
id = Column(Integer, primary_key=True)
created_date = Column(DateTime, default=datetime.datetime.utcnow)
The items with code "200 (cache)" were fulfilled directly from your browser cache, meaning that the original requests for the items were returned with headers indicating that the browser could cache them (e.g. future-dated Expires
or Cache-Control: max-age
headers), and that at the time you triggered the new request, those cached objects were still stored in local cache and had not yet expired.
304s, on the other hand, are the response of the server after the browser has checked if a file was modified since the last version it had cached (the answer being "no").
For most optimal web performance, you're best off setting a far-future Expires:
or Cache-Control: max-age
header for all assets, and then when an asset needs to be changed, changing the actual filename of the asset or appending a version string to requests for that asset. This eliminates the need for any request to be made unless the asset has definitely changed from the version in cache (no need for that 304 response). Google has more details on correct use of long-term caching.
I know it's a bit late to answer here but maybe I may save some once's day.
I have been dealing with the same problem. A model will not populate once you update the value of input from jQuery. I tried using trigger events but no result.
Here is what I did that may save your day.
Declare a variable within your script tag in HTML.
Like:
<script>
var inputValue="";
// update that variable using your jQuery function with appropriate value, you want...
</script>
Once you did that by using below service of angular.
$window
Now below getData function called from the same controller scope will give you the value you want.
var myApp = angular.module('myApp', []);
app.controller('imageManagerCtrl',['$scope','$window',function($scope,$window) {
$scope.getData = function () {
console.log("Window value " + $window.inputValue);
}}]);
There seems to be a much cleaner solution if you only want to reduce the spacing between the bullet point and the text:
li:before {
content: "";
margin-left: -0.5rem;
}
I have implemented the method from Varun Vohra's answer here for both lists and dicts.
import math
import numbers
import operator
import itertools
def round_list_percentages(number_list):
"""
Takes a list where all values are numbers that add up to 100,
and rounds them off to integers while still retaining a sum of 100.
A total value sum that rounds to 100.00 with two decimals is acceptable.
This ensures that all input where the values are calculated with [fraction]/[total]
and the sum of all fractions equal the total, should pass.
"""
# Check input
if not all(isinstance(i, numbers.Number) for i in number_list):
raise ValueError('All values of the list must be a number')
# Generate a key for each value
key_generator = itertools.count()
value_dict = {next(key_generator): value for value in number_list}
return round_dictionary_percentages(value_dict).values()
def round_dictionary_percentages(dictionary):
"""
Takes a dictionary where all values are numbers that add up to 100,
and rounds them off to integers while still retaining a sum of 100.
A total value sum that rounds to 100.00 with two decimals is acceptable.
This ensures that all input where the values are calculated with [fraction]/[total]
and the sum of all fractions equal the total, should pass.
"""
# Check input
# Only allow numbers
if not all(isinstance(i, numbers.Number) for i in dictionary.values()):
raise ValueError('All values of the dictionary must be a number')
# Make sure the sum is close enough to 100
# Round value_sum to 2 decimals to avoid floating point representation errors
value_sum = round(sum(dictionary.values()), 2)
if not value_sum == 100:
raise ValueError('The sum of the values must be 100')
# Initial floored results
# Does not add up to 100, so we need to add something
result = {key: int(math.floor(value)) for key, value in dictionary.items()}
# Remainders for each key
result_remainders = {key: value % 1 for key, value in dictionary.items()}
# Keys sorted by remainder (biggest first)
sorted_keys = [key for key, value in sorted(result_remainders.items(), key=operator.itemgetter(1), reverse=True)]
# Otherwise add missing values up to 100
# One cycle is enough, since flooring removes a max value of < 1 per item,
# i.e. this loop should always break before going through the whole list
for key in sorted_keys:
if sum(result.values()) == 100:
break
result[key] += 1
# Return
return result
This has the added benefit of being able to sort ascending or descending, using Java 8
import static java.util.Comparator.comparingInt;
import static java.util.stream.Collectors.toMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class Utils {
public static Map<String, Integer> sortMapBasedOnValues(Map<String, Integer> map, boolean descending) {
int multiplyBy = (descending) ? -1: 1;
Map<String, Integer> sorted = map.entrySet().stream()
.sorted(comparingInt(e -> multiplyBy * e.getValue() ))
.collect(toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(a, b) -> { throw new AssertionError();},
LinkedHashMap::new
));
return sorted;
}
}
Check out the documentation
Quote:
QString provides many functions for converting numbers into strings and strings into numbers. See the arg() functions, the setNum() functions, the number() static functions, and the toInt(), toDouble(), and similar functions.
Use isinstance
:
if isinstance(e, list):
If you want to check that an object is a list or a tuple, pass several classes to isinstance
:
if isinstance(e, (list, tuple)):
Add this in script
$(document).ready(function() {
$('#addBtn').focus(function() {
this.blur();
});
});
Temporarily update the retention time on the topic to one second:
kafka-topics.sh --zookeeper <zkhost>:2181 --alter --topic <topic name> --config retention.ms=1000
And in newer Kafka releases, you can also do it with kafka-configs --entity-type topics
kafka-configs.sh --zookeeper <zkhost>:2181 --entity-type topics --alter --entity-name <topic name> --add-config retention.ms=1000
then wait for the purge to take effect (about one minute). Once purged, restore the previous retention.ms
value.
Recursive solution to print all items in a list:
def printItems(l):
for i in l:
if isinstance(i,list):
printItems(i)
else:
print i
l = [['vegas','London'],['US','UK']]
printItems(l)
just for the record you can always compare using JSON.stringify
const arr = [1,2,3];
expect(JSON.stringify(arr)).toBe(JSON.stringify([1,2,3]));
expect(JSON.stringify(arr)).toEqual(JSON.stringify([1,2,3]));
It's all meter of taste, this will also work for complex literal objects
In Advance Tab -> scroll down and un-checked all options in advance security setting and try by checking one-by-one and finally app start running with one option TLS 1.1
that was the solution I got it.
as for react-router-dom 4.x.x (https://www.npmjs.com/package/react-router-dom) you can pass params to the component to route to via:
<Route path="/ideas/:value" component ={CreateIdeaView} />
linking via (considering testValue prop is passed to the corresponding component (e.g. the above App component) rendering the link)
<Link to={`/ideas/${ this.props.testValue }`}>Create Idea</Link>
passing props to your component constructor the value param will be available via
props.match.params.value
You can resave the image and literally find the src file of your project and add it to that when you save. For me I had to go to netbeans and found my project and when that comes up it had 3 files src was the last. Don't click on any of them just save your pic there. That should work. Now resizing it may be a different issue and one I'm working on now lol
Swift 4, I have used Enum for handling UserDefaults.
This is just a sample code. You can customize it as per your requirements.
For Storing, Retrieving, Removing. In this way just add a key for your UserDefaults key to the enum. Handle values while getting and storing according to dataType and your requirements.
enum UserDefaultsConstant : String {
case AuthToken, FcmToken
static let defaults = UserDefaults.standard
//Store
func setValue(value : Any) {
switch self {
case .AuthToken,.FcmToken:
if let _ = value as? String {
UserDefaults.standard.set(value, forKey: self.rawValue)
}
break
}
UserDefaults.standard.synchronize()
}
//Retrieve
func getValue() -> Any? {
switch self {
case .AuthToken:
if(UserDefaults.standard.value(forKey: UserDefaultsConstant.AuthToken.rawValue) != nil) {
return "Bearer "+(UserDefaults.standard.value(forKey: UserDefaultsConstant.AuthToken.rawValue) as! String)
}
else {
return ""
}
case .FcmToken:
if(UserDefaults.standard.value(forKey: UserDefaultsConstant.FcmToken.rawValue) != nil) {
print(UserDefaults.standard.value(forKey: UserDefaultsConstant.FcmToken.rawValue))
return (UserDefaults.standard.value(forKey: UserDefaultsConstant.FcmToken.rawValue) as! String)
}
else {
return ""
}
}
}
//Remove
func removeValue() {
UserDefaults.standard.removeObject(forKey: self.rawValue)
UserDefaults.standard.synchronize()
}
}
For storing a value in userdefaults,
if let authToken = resp.data?.token {
UserDefaultsConstant.AuthToken.setValue(value: authToken)
}
For retrieving a value from userdefaults,
//As AuthToken value is a string
(UserDefaultsConstant.AuthToken.getValue() as! String)
./a.exe at the prompt
Swift 3
For a simple solution without third party code:
Just use a normal UIAlertController but with style = actionSheet (look at code down below)
let alertDisapperTimeInSeconds = 2.0
let alert = UIAlertController(title: nil, message: "Toast!", preferredStyle: .actionSheet)
self.present(alert, animated: true)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + alertDisapperTimeInSeconds) {
alert.dismiss(animated: true)
}
The advantage of this solution:
$("#mainTable").css("width", "200px");
$("#mainTable").css("height", "2000px");
I had a similar problem . For this you can use a Hashmap which takes "string" and "object" as shown in code below:
/** stores the image database icons */
public static int[] imageIconDatabase = { R.drawable.ball,
R.drawable.catmouse, R.drawable.cube, R.drawable.fresh,
R.drawable.guitar, R.drawable.orange, R.drawable.teapot,
R.drawable.india, R.drawable.thailand, R.drawable.netherlands,
R.drawable.srilanka, R.drawable.pakistan,
};
private void initializeImageList() {
// TODO Auto-generated method stub
for (int i = 0; i < imageIconDatabase.length; i++) {
map = new HashMap<String, Object>();
map.put("Name", imageNameDatabase[i]);
map.put("Icon", imageIconDatabase[i]);
}
}
When you start a process from a batch file, it starts as a separate process with no hint towards the batch file that started it (since this would have finished running in the meantime, things like the parent process ID won't help you).
If you know the process name, and it is unique among all running processes, you can use taskkill
, like @IVlad suggests in a comment.
If it is not unique, you might want to look into jobs. These terminate all spawned child processes when they are terminated.
If you don't care about the columns where the missing files are, considering that the dataframe has the name New
and one wants to assign the new dataframe to the same variable, simply run
New = New.drop_duplicates()
If you specifically want to remove the rows for the empty values in the column Tenant
this will do the work
New = New[New.Tenant != '']
This may also be used for removing rows with a specific value - just change the string to the value that one wants.
Note: If instead of an empty string one has NaN
, then
New = New.dropna(subset=['Tenant'])
For a deep clone I use reflection as follows:
public List<T> CloneList<T>(IEnumerable<T> listToClone) {
Type listType = listToClone.GetType();
Type elementType = listType.GetGenericArguments()[0];
List<T> listCopy = new List<T>();
foreach (T item in listToClone) {
object itemCopy = Activator.CreateInstance(elementType);
foreach (PropertyInfo property in elementType.GetProperties()) {
elementType.GetProperty(property.Name).SetValue(itemCopy, property.GetValue(item));
}
listCopy.Add((T)itemCopy);
}
return listCopy;
}
You can use List or IEnumerable interchangeably.
how about something like this ...
a.register:link{
color:#FFFFFF;
}
You have to pass the route parameters to the route
method, for example:
<li><a href="{{ route('user.profile', $nickname) }}">Profile</a></li>
<li><a href="{{ route('user.settings', $nickname) }}">Settings</a></li>
It's because, both routes have a {nickname}
in the route declaration. I've used $nickname
for example but make sure you change the $nickname
to appropriate value/variable, for example, it could be something like the following:
<li><a href="{{ route('user.settings', auth()->user()->nickname) }}">Settings</a></li>
Try this: for the previous view use this:
navigationController?.popViewController(animated: true)
pop to root use this code:
navigationController?.popToRootViewController(animated: true)
I prefer this as the best way of reversing a string using a for loop.
def reverse_a_string(str):
result=" "
for i in range(len(str),1,-1):
result= result+ str[i-1]
return result
print reverse_a_string(input())
If you have numpy installed you can try:
data = numpy.asarray(im)
(I say "try" here, because it's unclear why getdata()
isn't working for you, and I don't know whether asarray
uses getdata, but it's worth a test.)
In my case a major update of Windows 10 removed some Windows packages, so other methods (reinstalling opencv etc.) did not help. To fix it, install:
a) Microsoft Visual C++ Redistributable for Visual Studio 2015, 2017 and 2019
b) Media Feature Pack for N versions - needed only if you have Windows 10 N
Both need restart of PC.
See Tejas Lagvankar's post about this subject. Below are some key differences between Service and IntentService and other components.
The easiest way is start the simulator from the Xcode
, and then on the dock, Ctrl
+ Click
on the icon and select Keep in Dock
If you're talking about ASP.NET MVC then you should have a controller method that returns the following:
return Redirect("http://www.google.com");
Otherwise we need more info on the error you're getting in the redirect. I'd step through to make sure the url isn't empty.
To answer the @ascobol
's question using @bobince
's suggestion from the comments:
for i in range(5000):
for j in range(3000):
if should_terminate_the_loop:
break
else:
continue # no break encountered
break
The indent for the else
block is correct. The code uses obscure else
after a loop Python syntax. See Why does python use 'else' after for and while loops?
Here is my code , To get Manufacturer,Brand name,Os version and support API Level
String manufacturer = Build.MANUFACTURER;
String model = Build.MODEL + " " + android.os.Build.BRAND +" ("
+ android.os.Build.VERSION.RELEASE+")"
+ " API-" + android.os.Build.VERSION.SDK_INT;
if (model.startsWith(manufacturer)) {
return capitalize(model);
} else {
return capitalize(manufacturer) + " " + model;
}
Output:
System.out: button press on device name = Lava Alfa L iris(5.0) API-21
Sounds like you need to round to the nearest 0.5. I see no version of round
in the C# API that does this (one version takes a number of decimal digits to round to, which isn't the same thing).
Assuming you only have to deal with integer numbers of tenths, it's sufficient to calculate round (num * 2) / 2
. If you're using arbitrarily precise decimals, it gets trickier. Let's hope you don't.
$('#ThisLink').one('click',function(){
$(this).bind('click',function(){
return false;
});
});
This would be another way to do this, the handler with return false
, which will disable the link, will be added after one click.
This answer is totally unrelated to the OP's situation, and is a very unlikely scenario for anyone else too, but just in case it may help someone ...
In my case I was getting "Could not load file or assembly 'System.Windows.Forms, Version=4.0.0.0 ..." because I had disassembled and reassembled the program using ILDAsm.exe and ILAsm.exe from .Net Framework / SDK version 2. Switching to ILDAsm.exe and ILAsm.exe from .Net Framework / SDK version 4 fixed the problem.
(Strangely, even though doing what I did may seem like an obvious error, the resulting EXE file that didn't work did indicate that it targeted .Net 4 when examined with JetBrains dotPeek.)
Create a new SSH key in your terminal/command line.
ssh-keygen -t rsa -C “your-email-address”
The following will then show:
Generating public/private rsa key pair. Enter file in which to save the key (/home/your_username/.ssh/id_rsa):
Copy and paste the path followed by an identifiable name for the file:
/home/your_username/.ssh/id_rsa_personal
4) It will then ask you for the following:
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
5) You can now type in the following command to see all the SSH keys you have on your local machine:
ls -al ~/.ssh
You should be able to see your new SSH key file. As you can see in my one I have both id_rsa_test and id_rsa_personal.pub.
drwx------ 2 gmadmin gmadmin 4096 Nov 16 22:20 .
drwxr-xr-x 42 gmadmin gmadmin 4096 Nov 16 21:03 ..
-rw------- 1 gmadmin gmadmin 1766 Nov 16 22:20 id_rsa_personal
-rw-r--r-- 1 gmadmin gmadmin 414 Nov 16 22:20 id_rsa_personal.pub
-rw-r--r-- 1 gmadmin gmadmin 444 Nov 6 11:32 known_hosts
6) Next you need to copy the SSH key which is stored in id_rsa_personal.pub file. You can open this in text editor of your choice. I am currently using atom so I opened the file using the following command:
atom ~/.ssh/id_rsa_personal.pub
You will then get something similar to this:
ssh-rsa AAB3HKJLKC1yc2EAAAADAQABAAABAQCgU5+ELtwsKkmcoeF3hNd7d6CjW+dWut83R/Dc01E/YzLc5ZFri18doOwuQoeTPpmIRVDGuQQsZshjDrTkFy8rwKWMlXl7va5olnGICcpg4qydEtsW+MELDmayW1HHsi2xHMMGHlNv
7) Copy this and navigate to your GitHub account ? Settings ? SSH and GPG keys 8) Click on New SSH key. Copy the key, give it a title and add it. 9) Add key from terminal
ssh-add ~/.ssh/id_rsa_personal
Enter passphrase for /home/your_username/.ssh/id_rsa_personal:
10) Configure user and password.
git config --global user.name "gitusername"
git config --global user.email "gitemail"
11) We are ready to commit and push now.
git init
git add .
git commit
git push
var bordT = $('img').outerWidth() - $('img').innerWidth();
var paddT = $('img').innerWidth() - $('img').width();
var margT = $('img').outerWidth(true) - $('img').outerWidth();
var formattedBord = bordT + 'px';
var formattedPadd = paddT + 'px';
var formattedMarg = margT + 'px';
Check the jQuery API docs for information on each:
Here's the edited jsFiddle showing the result.
You can perform the same type of operations for the Height to get its margin, border, and padding.
For horizontal and vertical alignment of text in graphics,
you might want to use the following CSS styles.
In particular, note that dominant-baseline:middle
is probably wrong,
since this is (usually) half way between the top and the baseline,
rather than half way between the top and the bottom.
Also, some some sources (e.g. Mozilla) use dominant-baseline:hanging
instead of
dominant-baseline:text-before-edge
. This is also probably wrong, since
hanging
is designed for Indic scripts.
Of course, if you're using a mixture of Latin, Indic, ideographs
or whatever, you'll probably need to read the documentation.
/* Horizontal alignment */
text.goesleft{text-anchor:end}
text.equalleftright{text-anchor:middle}
text.goesright{text-anchor:start}
/* Vertical alignment */
text.goesup{dominant-baseline:text-after-edge}
text.equalupdown{dominant-baseline:central}
text.goesdown{dominant-baseline:text-before-edge}
text.ruledpaper{dominant-baseline:alphabetic}
Edit: I've just noticed that Mozilla also uses dominant-baseline:baseline
which is definitely wrong: it's not even a recognized value! I assume it's defaulting to the font default, which is alphabetic
, so they got lucky.
More edit: Safari (11.1.2) understands text-before-edge
but not text-after-edge
. It also fails on ideographic
. Great stuff, Apple. So you might be forced to use alphabetic
and allow for descenders after all. Sorry.
Avoid using bind_address
in your my.cnf file, if you have any.
Ref: http://dev.mysql.com/doc/refman/5.5/en/can-not-connect-to-server.html
Another way is to use the object tag. This works on Chrome, IE, Firefox, Safari and Opera.
<object data="html/stuff_to_include.html">
Your browser doesn’t support the object tag.
</object>
more info at http://www.w3schools.com/tags/tag_object.asp
Mac Cmd+Shift+\
Windows Ctrl+Shift+\
Windows with spanish keyboard Ctrl+Shift+|
Windows with german keyboard Ctrl+Shift+^
Alternatively, you can do:
Ctrl+Shift+p
And select
Preferences: Open Keyboard Shortcuts
There you will be able to see all the shortcuts, and create your own.
DB_*/**/*.sql
Here is a variation to perform an action if one or more files exist corresponding to a wildcard filter. That is, you don't know the exact name of the file.
Here, we are looking for "*.sql" files in any sub-directories called "DB_*", recursively. You can adjust the filter to your needs.
NB: Apache Ant 1.7 and higher!
Here is the target to set a property if matching files exist:
<target name="check_for_sql_files">
<condition property="sql_to_deploy">
<resourcecount when="greater" count="0">
<fileset dir="." includes="DB_*/**/*.sql"/>
</resourcecount>
</condition>
</target>
Here is a "conditional" target that only runs if files exist:
<target name="do_stuff" depends="check_for_sql_files" if="sql_to_deploy">
<!-- Do stuff here -->
</target>
The answer by Steve Jessop explains well, why you can't use std::map::operator[]
on a const std::map
. Gabe Rainbow's answer suggests a nice alternative. I'd just like to provide some example code on how to use map::at()
. So, here is an enhanced example of your function()
:
void function(const MAP &map, const std::string &findMe) {
try {
const std::string& value = map.at(findMe);
std::cout << "Value of key \"" << findMe.c_str() << "\": " << value.c_str() << std::endl;
// TODO: Handle the element found.
}
catch (const std::out_of_range&) {
std::cout << "Key \"" << findMe.c_str() << "\" not found" << std::endl;
// TODO: Deal with the missing element.
}
}
And here is an example main()
function:
int main() {
MAP valueMap;
valueMap["string"] = "abc";
function(valueMap, "string");
function(valueMap, "strong");
return 0;
}
Output:
Value of key "string": abc
Key "strong" not found
Here are a couple basic examples to get started quick and dirty.
Set variable:
SET(INSTALL_ETC_DIR "etc")
Use variable:
SET(INSTALL_ETC_CROND_DIR "${INSTALL_ETC_DIR}/cron.d")
Set variable:
SET(PROGRAM_SRCS
program.c
program_utils.c
a_lib.c
b_lib.c
config.c
)
Use variable:
add_executable(program "${PROGRAM_SRCS}")
Something like BrowserShots?
Some time we need to set PATH variable for WINDOWS
%USERPROFILE%\AppData\Roaming\npm
After that test with where grunt
Note: Do not forget to close the command prompt window and reopen it.
There is always a reason why the nested method roll back. If you don't see the reason, you need to change your logger level to debug, where you will see the more details where transaction failed. I changed my logback.xml by adding
<logger name="org.springframework.transaction" level="debug"/>
<logger name="org.springframework.orm.jpa" level="debug"/>
then I got this line in the log:
Participating transaction failed - marking existing transaction as rollback-only
So I just stepped through my code to see where this line is generated and found that there is a catch block which did not throw anything.
private Student add(Student s) {
try {
Student retval = studentRepository.save(s);
return retval;
} catch (Exception e) {
}
return null;
}
You can change your model method to property and use it in serializer with this approach.
class Foo(models.Model):
. . .
@property
def my_field(self):
return stuff
. . .
class FooSerializer(ModelSerializer):
my_field = serializers.ReadOnlyField(source='my_field')
class Meta:
model = Foo
fields = ('my_field',)
Edit: With recent versions of rest framework (I tried 3.3.3), you don't need to change to property. Model method will just work fine.
For IE 6, you'll want to equal colspan to the number of columns in your table. If you have 5 columns, then you'll want: colspan="5"
.
The reason is that IE handles colspans differently, it uses the HTML 3.2 specification:
IE implements the HTML 3.2 definition, it sets
colspan=0
ascolspan=1
.
The bug is well documented.
ImageIcon
s. For a single image, I would think about making a custom subclass of JPanel
and overriding its paintComponent
method to draw the image.On my Fedora machine, when I typed "make" I got an error saying it could not find "cv.h". I fixed this by modifying my "OpenCVConfig.cmake" file.
Before:
SET(OpenCV_INCLUDE_DIRS "${OpenCV_INSTALL_PATH}/include/opencv;${OpenCV_INSTALL_PATH}/include")
SET(OpenCV_LIB_DIR "${OpenCV_INSTALL_PATH}/lib64")
After:
SET(OpenCV_INCLUDE_DIRS "/usr/include/opencv;/usr/include/opencv2")
SET(OpenCV_LIB_DIR "/usr/lib64")
Static classes can be useful in certain situations, but there is a potential to abuse and/or overuse them, like most language features.
As Dylan Smith already mentioned, the most obvious case for using a static class is if you have a class with only static methods. There is no point in allowing developers to instantiate such a class.
The caveat is that an overabundance of static methods may itself indicate a flaw in your design strategy. I find that when you are creating a static function, its a good to ask yourself -- would it be better suited as either a) an instance method, or b) an extension method to an interface. The idea here is that object behaviors are usually associated with object state, meaning the behavior should belong to the object. By using a static function you are implying that the behavior shouldn't belong to any particular object.
Polymorphic and interface driven design are hindered by overusing static functions -- they cannot be overriden in derived classes nor can they be attached to an interface. Its usually better to have your 'helper' functions tied to an interface via an extension method such that all instances of the interface have access to that shared 'helper' functionality.
One situation where static functions are definitely useful, in my opinion, is in creating a .Create() or .New() method to implement logic for object creation, for instance when you want to proxy the object being created,
public class Foo
{
public static Foo New(string fooString)
{
ProxyGenerator generator = new ProxyGenerator();
return (Foo)generator.CreateClassProxy
(typeof(Foo), new object[] { fooString }, new Interceptor());
}
This can be used with a proxying framework (like Castle Dynamic Proxy) where you want to intercept / inject functionality into an object, based on say, certain attributes assigned to its methods. The overall idea is that you need a special constructor because technically you are creating a copy of the original instance with special added functionality.
You'll need tail. Some examples:
$ tail great-big-file.log
< Last 10 lines of great-big-file.log >
If you really need to SKIP a particular number of "first" lines, use
$ tail -n +<N+1> <filename>
< filename, excluding first N lines. >
That is, if you want to skip N lines, you start printing line N+1. Example:
$ tail -n +11 /tmp/myfile
< /tmp/myfile, starting at line 11, or skipping the first 10 lines. >
If you want to just see the last so many lines, omit the "+":
$ tail -n <N> <filename>
< last N lines of file. >
You need to join
the two tables and then filter the result in where
clause:
SELECT country.name as country, country.headofstate
from country
inner join city on city.id = country.capital
where city.population > 100000
and country.headofstate like 'A%'
A Redirect can only happen if the first line in an HTTP message is "HTTP/1.x 3xx Redirect Reason
".
If you already called Response.Write()
or set some headers, it'll be too late for a redirect. You can try calling Response.Headers.Clear()
before the Redirect to see if that helps.
Another fast solution that saves boilerplate code is Lombok EqualsAndHashCode annotation. It is easy, elegant and customizable. And does not depends on the IDE. For example;
import lombok.EqualsAndHashCode;
@EqualsAndHashCode(of={"errorNumber","messageCode"}) // Will only use this fields to generate equals.
public class ErrorMessage{
private long errorNumber;
private int numberOfParameters;
private Level loggingLevel;
private String messageCode;
See the options avaliable to customize which fields to use in the equals. Lombok is avalaible in maven. Just add it with provided scope:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.14.8</version>
<scope>provided</scope>
</dependency>
RUN /bin/sh -c "apk add --no-cache bash"
worked for me.
Just Go to Model file of the corresponding Controller and check the primary key filed name
such as
protected $primaryKey = 'info_id';
here info id is field name available in database table
More info can be found at "Primary Keys" section of the docs.
I know it has been long since the original question was posted, but for future reference: check this project, https://github.com/gkorland/Eclipse-Fonts I have used it, and it's very simple and efficient.
This is how I implement singleton in my projects
Inspired from flutter firebase => FirebaseFirestore.instance.collection('collectionName')
class FooAPI {
foo() {
// some async func to api
}
}
class SingletonService {
FooAPI _fooAPI;
static final SingletonService _instance = SingletonService._internal();
static SingletonService instance = SingletonService();
factory SingletonService() {
return _instance;
}
SingletonService._internal() {
// TODO: add init logic if needed
// FOR EXAMPLE API parameters
}
void foo() async {
await _fooAPI.foo();
}
}
void main(){
SingletonService.instance.foo();
}
class FirebaseLessonRepository implements LessonRepository {
FirebaseLessonRepository._internal();
static final _instance = FirebaseLessonRepository._internal();
static final instance = FirebaseLessonRepository();
factory FirebaseLessonRepository() => _instance;
var lessonsCollection = fb.firestore().collection('lessons');
// ... other code for crud etc ...
}
// then in my widgets
FirebaseLessonRepository.instance.someMethod(someParams);
Yes you can use the for-each loop,
To do that you have to maintain a separate list to hold removing items and then remove that list from names list using removeAll()
method,
List<String> names = ....
// introduce a separate list to hold removing items
List<String> toRemove= new ArrayList<String>();
for (String name : names) {
// Do something: perform conditional checks
toRemove.add(name);
}
names.removeAll(toRemove);
// now names list holds expected values
This question is already answered here
The classpath never includes specific files. It includes directories and jar files. So, put that file in a directory that is in your classpath
.
Log4j
properties aren't (normally) used in developing apps (unless you're debugging Eclipse itself!). So what you really want to to build the executable Java app (Application, WAR, EAR or whatever) and include the Log4j
properties in the runtime classpath.
Using data.table
library(data.table)
setDT(dat)[, .N, keyby=ID] #(Using @Paul Hiemstra's `dat`)
Or using dplyr 0.3
res <- count(dat, ID)
head(res)
#Source: local data frame [6 x 2]
# ID n
#1 a 2
#2 b 3
#3 c 3
#4 d 3
#5 e 2
#6 f 4
Or
dat %>%
group_by(ID) %>%
tally()
Or
dat %>%
group_by(ID) %>%
summarise(n=n())
In a pinch, for those editors that don't support removal of trailing whitespace at all (e.g. the XML editor), you can remove it from all lines by doing a find and replace, enabling regular expressions, then finding "[\t ]+$" and replacing it with "" (blank). There's probably a better regex to do that but it works for me without needing to install AnyEdit.
I had the same problem. Solved using single quotes like this:
$ wget 'http://www.icerts.com/images/logo.jpg'
wget version in use:
$ wget --version
GNU Wget 1.11.4 Red Hat modified
const returnedTarget = Object.assign(target, source);
and pass empty array to target
in case complex objects this way works for me
$.extend(true, [], originalArray)
in case of array
$.extend(true, {}, originalObject)
in case of object
String u = request.getParameter("username");
String p = request.getParameter("password");
try {
st = con.createStatement();
String sql;
sql = "SELECT * FROM TableName where USERNAME = '" + u + "' and PASSWORD = '"
+ p + "'";
ResultSet rs = st.executeQuery(sql);
if (rs.next()) {
RequestDispatcher requestDispatcher = request
.getRequestDispatcher("/home.jsp");
requestDispatcher.forward(request, response);
} else {
RequestDispatcher requestDispatcher = request
.getRequestDispatcher("/invalidLogin.jsp");
requestDispatcher.forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
finally{
try {
rs.close();
ps.close();
con.close();
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I use my own function to print the contents of a table but not sure how well it translates to your environment:
---A helper function to print a table's contents.
---@param tbl table @The table to print.
---@param depth number @The depth of sub-tables to traverse through and print.
---@param n number @Do NOT manually set this. This controls formatting through recursion.
function PrintTable(tbl, depth, n)
n = n or 0;
depth = depth or 5;
if (depth == 0) then
print(string.rep(' ', n).."...");
return;
end
if (n == 0) then
print(" ");
end
for key, value in pairs(tbl) do
if (key and type(key) == "number" or type(key) == "string") then
key = string.format("[\"%s\"]", key);
if (type(value) == "table") then
if (next(value)) then
print(string.rep(' ', n)..key.." = {");
PrintTable(value, depth - 1, n + 4);
print(string.rep(' ', n).."},");
else
print(string.rep(' ', n)..key.." = {},");
end
else
if (type(value) == "string") then
value = string.format("\"%s\"", value);
else
value = tostring(value);
end
print(string.rep(' ', n)..key.." = "..value..",");
end
end
end
if (n == 0) then
print(" ");
end
end
You don't necessarily need to have the parameters inside the URL.
For instance, with:
$stateProvider
.state('home', {
url: '/',
views: {
'': {
templateUrl: 'home.html',
controller: 'MainRootCtrl'
},
},
params: {
foo: null,
bar: null
}
})
You will be able to send parameters to the state, using either:
$state.go('home', {foo: true, bar: 1});
// or
<a ui-sref="home({foo: true, bar: 1})">Go!</a>
Of course, if you reload the page once on the home
state, you will loose the state parameters, as they are not stored anywhere.
A full description of this behavior is documented here, under the params
row in the state(name, stateConfig)
section.
The connectivity: package does not guarantee the actual internet connection (could be just wifi connection without internet access).
Quote from the documentation:
Note that on Android, this does not guarantee connection to Internet. For instance, the app might have wifi access but it might be a VPN or a hotel WiFi with no access.
If you really need to check the connection to the www Internet the better choice would be
To help another people with my same problem, the complete answer to Use Toast inside Fragment is:
Activity activity = getActivity();
@Override
public void onClick(View arg0) {
Toast.makeText(activity,"Text!",Toast.LENGTH_SHORT).show();
}
I too ran into this error. All the configuration and permissions were correct. But I forgot to copy Global.asax to the server, and that's what gave the 403 error.
For Python3.x and starting Pillow==6.0.0
, Image
objects now provide a getexif()
method that returns a <class 'PIL.Image.Exif'>
instance or None
if the image has no EXIF data.
From Pillow 6.0.0 release notes:
getexif()
has been added, which returns anExif
instance. Values can be retrieved and set like a dictionary. When saving JPEG, PNG or WEBP, the instance can be passed as anexif
argument to include any changes in the output image.
As stated, you can iterate over the key-value pairs of the Exif
instance like a regular dictionary. The keys are 16-bit integers that can be mapped to their string names using the ExifTags.TAGS
module.
from PIL import Image, ExifTags
img = Image.open("sample.jpg")
img_exif = img.getexif()
print(type(img_exif))
# <class 'PIL.Image.Exif'>
if img_exif is None:
print('Sorry, image has no exif data.')
else:
for key, val in img_exif.items():
if key in ExifTags.TAGS:
print(f'{ExifTags.TAGS[key]}:{val}')
# ExifVersion:b'0230'
# ...
# FocalLength:(2300, 100)
# ColorSpace:1
# ...
# Model:'X-T2'
# Make:'FUJIFILM'
# LensSpecification:(18.0, 55.0, 2.8, 4.0)
# ...
# DateTime:'2019:12:01 21:30:07'
# ...
Tested with Python 3.8.8 and Pillow==8.1.0
.
You have set a fixed width and height in your svg tag. This is probably the root of your problem. Try not removing those and set the width and height (if needed) using CSS instead.
I found the problem. This code was placed in a separate file that was added with a php include() function. And this include was happening before the Bootstrap files were loaded. So the Bootstrap JS file was not loaded yet, causing this modal to not do anything.
With the above code sample is nothing wrong and works as intended when placed in the body part of a html page.
<script type="text/javascript">
$('#memberModal').modal('show');
</script>
If you can not switch to landscape(or portrait) while using ctr+f11/12 Maybe the virtual device (android phone) itself lock the rotation. Going to the android control center (pull down on the home page), and unlock.
from pyspark.sql.types import IntegerType
data_df = data_df.withColumn("Plays", data_df["Plays"].cast(IntegerType()))
data_df = data_df.withColumn("drafts", data_df["drafts"].cast(IntegerType()))
You can run loop for each column but this is the simplest way to convert string column into integer.
LinearLayout - In LinearLayout, views are organized either in vertical or horizontal orientation.
RelativeLayout - RelativeLayout is way more complex than LinearLayout, hence provides much more functionalities. Views are placed, as the name suggests, relative to each other.
FrameLayout - It behaves as a single object and its child views are overlapped over each other. FrameLayout takes the size of as per the biggest child element.
Coordinator Layout - This is the most powerful ViewGroup introduced in Android support library. It behaves as FrameLayout and has a lot of functionalities to coordinate amongst its child views, for example, floating button and snackbar, Toolbar with scrollable view.
Reason seems to be that the public key of the remote host is not stored or different from the stored one. (Be aware of security issues, see Greg Bacon's answer for details.)
I was used to git clone
prompting me in this case:
The authenticity of host 'host.net (10.0.0.42)' can't be established.
ECDSA key fingerprint is 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00.
Are you sure you want to continue connecting (yes/no)?
Not sure, why this error is thrown instead. Could be the configuration of your shell or the git SSH command.
Anyhow, you can get the same prompt by running ssh [email protected]
.
What I've done is to create a server side script that will resize and crop a picture on the server end so it'll send less data across the interweb.
It's fairly trivial, but if anyone is interested, I can dig up and post the code (asp.net)
I have found a fairly simple way to do this.
Initially, through your Anaconda Prompt, you can follow the steps in this official Tensorflow site - here. You have to follow the steps as is, no deviation.
Later, you open the Anaconda Navigator. In Anaconda Navigator, go to Applications On --- section. Select the drop down list, after following above steps you must see an entry - tensorflow into it. Select tensorflow and let the environment load.
Then, select Jupyter Notebook in this new context, and install it, let the installation get over.
After that you can run the Jupyter notebook like the regular notebook in tensorflow environment.
I need the exact same feature described in this question. Here is my solution and source code: https://github.com/laoyang/android-dynamic-views. And you can see the video demo in action here: http://www.youtube.com/watch?v=4HeqyG6FDhQ
Basically you'll two xml layout files:
TextEdit
, a Spinner
and an ImageButton
for deletion. In the Java code, you'll add and remove row views into the container dynamically, using inflate, addView, removeView, etc. There are some visibility control for better UX in the stock Android app. You need add a TextWatcher for the EditText view in each row: when the text is empty you need to hide the Add new button and the delete button. In my code, I wrote a void inflateEditRow(String)
helper function for all the logic.
android:animateLayoutChanges="true"
in xml to enable animationThe Java code of the main activity ( This explains all the logic, but quite a few properties are set in xml layout files, please refer to the Github source for complete solution):
public class MainActivity extends Activity {
// Parent view for all rows and the add button.
private LinearLayout mContainerView;
// The "Add new" button
private Button mAddButton;
// There always should be only one empty row, other empty rows will
// be removed.
private View mExclusiveEmptyView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.row_container);
mContainerView = (LinearLayout) findViewById(R.id.parentView);
mAddButton = (Button) findViewById(R.id.btnAddNewItem);
// Add some examples
inflateEditRow("Xiaochao");
inflateEditRow("Yang");
}
// onClick handler for the "Add new" button;
public void onAddNewClicked(View v) {
// Inflate a new row and hide the button self.
inflateEditRow(null);
v.setVisibility(View.GONE);
}
// onClick handler for the "X" button of each row
public void onDeleteClicked(View v) {
// remove the row by calling the getParent on button
mContainerView.removeView((View) v.getParent());
}
// Helper for inflating a row
private void inflateEditRow(String name) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.row, null);
final ImageButton deleteButton = (ImageButton) rowView
.findViewById(R.id.buttonDelete);
final EditText editText = (EditText) rowView
.findViewById(R.id.editText);
if (name != null && !name.isEmpty()) {
editText.setText(name);
} else {
mExclusiveEmptyView = rowView;
deleteButton.setVisibility(View.INVISIBLE);
}
// A TextWatcher to control the visibility of the "Add new" button and
// handle the exclusive empty view.
editText.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
// Some visibility logic control here:
if (s.toString().isEmpty()) {
mAddButton.setVisibility(View.GONE);
deleteButton.setVisibility(View.INVISIBLE);
if (mExclusiveEmptyView != null
&& mExclusiveEmptyView != rowView) {
mContainerView.removeView(mExclusiveEmptyView);
}
mExclusiveEmptyView = rowView;
} else {
if (mExclusiveEmptyView == rowView) {
mExclusiveEmptyView = null;
}
mAddButton.setVisibility(View.VISIBLE);
deleteButton.setVisibility(View.VISIBLE);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
// Inflate at the end of all rows but before the "Add new" button
mContainerView.addView(rowView, mContainerView.getChildCount() - 1);
}
If you don't have too many files that have changed, this will leave you with no extra commits.
1. Duplicate branch temporarily
$ git checkout -b temp_branch
2. Reset to last wanted commit
$ git reset --hard HEAD~n
, where n
is the number of commits you need to go back
3. Checkout each file from original branch
$ git checkout origin/original_branch filename.ext
Now you can commit and force push (to overwrite remote), if needed.
It would be better if you would describe the reason why you need garbage collection. If you are using SWT, you can dispose resources such as Image
and Font
to free memory. For instance:
Image img = new Image(Display.getDefault(), 16, 16);
img.dispose();
There are also tools to determine undisposed resources.
If you are having a lot activity like mine, in your application Or if you dont want to enter the code for each activity tag in manifest you can do this .
in your Application Base class you will get a lifecycle callback
so basically what happens in for each activity when creating the on create in Application Class get triggered here is the code ..
public class MyApplication extends Application{
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
activity.setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// for each activity this function is called and so it is set to portrait mode
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
});
}
i hope this helps.
import java.util.Scanner;
class my{
public static void main(String args[])
{
Scanner x=new Scanner(System.in);
double a,b,c=0,d;
d=1;
d=d/10;
int e,z=0;
System.out.print("Enter no:");
a=x.nextInt();
for(b=1;b<=a/2;b++)
{
if(b*b==a)
{
c=b;
break;
}
else
{
if(b*b>a)
break;
}
}
b--;
if(c==0)
{
for(e=1;e<=15;e++)
{
while(b*b<=a && z==0)
{
if(b*b==a){c=b;z=1;}
else
{
b=b+d; //*d==0.1 first time*//
if(b*b>=a){z=1;b=b-d;}
}
}
d=d/10;
z=0;
}
c=b;
}
System.out.println("Squre root="+c);
}
}
This XPath:
count(//Property[long = '11007'])
returns the same value as:
count(//Property/long[text() = '11007'])
...except that the first counts Property
nodes that match the criterion and the second counts long
child nodes that match the criterion.
As per your comment and reading your question a couple of times, I believe that you want to find uniqueness based on a combination of criteria. Therefore, in actuality, I think you are actually checking multiple conditions. The following would work as well:
count(//Property[@Name = 'Alive'][long = '11007'])
because it means the same thing as:
count(//Property[@Name = 'Alive' and long = '11007'])
Of course, you would substitute the values for parameters in your template. The above code only illustrates the point.
EDIT (after question edit)
You were quite right about the XML being horrible. In fact, this is a downright CodingHorror candidate! I had to keep recounting to keep track of the "Property" node I was on presently. I feel your pain!
Here you go:
count(/root/ac/Properties/Property[Properties/Property/Properties/Property/long = $parPropId])
Note that I have removed all the other checks (for ID and Value). They appear not to be required since you are able to arrive at the relevant node using the hierarchy in the XML. Also, you already mentioned that the check for uniqueness is based only on the contents of the long
element.
What is JNDI ?
The Java Naming and Directory InterfaceTM (JNDI) is an application programming interface (API) that provides naming and directory functionality to applications written using the JavaTM programming language. It is defined to be independent of any specific directory service implementation. Thus a variety of directories(new, emerging, and already deployed) can be accessed in a common way.
What is its basic use?
Most of it is covered in the above answer but I would like to provide architecture here so that above will make more sense.
To use the JNDI, you must have the JNDI classes and one or more service providers. The Java 2 SDK, v1.3 includes three service providers for the following naming/directory services:
So basically you create objects and register them on the directory services which you can later do lookup and execute operation on.
Best way to locate anchor elements is to use link=Re-Call
:
selenium.click("link=Re-Call");
It will work..
Add each line of the code to a variable and then write the variable to your inner HTML. See below:
var div = document.createElement('div');
div.setAttribute('class', 'post block bc2');
var str = "First Line";
str += "Second Line";
str += "So on, all of your lines";
div.innerHTML = str;
document.getElementById('posts').appendChild(div);
This may do the trick:
\b\p{L}*Id\b
Where \p{L}
matches any (Unicode) letter and \b
matches a word boundary.
Afterall, you could edit the .vimrc,then add the conf
set tabstop=4
Or exec the command
The best option I found to solve this without getting into trouble with my styles was using a separate route for my printed output and load this route into an iframe.
My surrounding component is shown as a tab page.
@Component({
template: '<iframe id="printpage" name="printpage" *ngIf="printSrc" [src]="printSrc"></iframe>',
styleUrls: [ 'previewTab.scss' ]
})
export class PreviewTabPage {
printSrc: SafeUrl;
constructor(
private navParams: NavParams,
private sanitizer: DomSanitizer,
) {
// item to print is passed as url parameter
const itemId = navParams.get('itemId');
// set print page source for iframe in template
this.printSrc = this.sanitizer.bypassSecurityTrustResourceUrl(this.getAbsoluteUrl(itemId));
}
getAbsoluteUrl(itemId: string): string {
// some code to generate an absolute url for your item
return itemUrl;
}
}
The iframe just loads the print route that renders a print component in the app. In this page the print might be triggered after the view is fully initialized. Another way could be a print button on the parent component that triggers the print on the iframe by window.frames["printpage"].print();
.
@Component({
templateUrl: './print.html',
styleUrls: [ 'print.scss' ]
})
export class PrintPage implements AfterViewInit {
constructor() {}
ngAfterViewInit() {
// wait some time, so all images or other async data are loaded / rendered.
// print could be triggered after button press in the parent component as well.
setTimeout(() => {
// print current iframe
window.print();
}, 2000);
}
}
Refer to the "undo" and "redo" part of Vim document.
:red[o] (Redo one change which was undone) and {count} Ctrl+r (Redo {count} changes which were undone) are both ok.
Also, the :earlier {count} (go to older text state {count} times) could always be a substitute for undo and redo.
I will let the code speak for itself:
Mesh mesh = new Mesh();
BoundingVolume vol = new BoundingVolume();
mesh.boundingVolume = vol;
vol.mesh = mesh;
vol.compute();
Do you like it? Here is with the setters:
Mesh mesh = new Mesh();
BoundingVolume vol = new BoundingVolume();
mesh.setBoundingVolume(vol);
.length
is a field, containing the capacity (NOT the number of elements the array contains at the moment) of arrays.
length()
is a method used by Strings (amongst others), it returns the number of chars in the String; with Strings, capacity and number of containing elements (chars) have the same value.
size()
is a method implemented by all members of Collection (lists, sets, stacks,...). It returns the number of elements (NOT the capacity; some collections even don´t have a defined capacity) the collection contains.Thank you everyone, for all your precise replys.
Using the svg in a shadow dom, I add the 3 linear gradients I need within the svg, inside a . I place the css fill rule on the web component and the inheritance od fill does the job.
<svg viewbox="0 0 512 512" xmlns="http://www.w3.org/2000/svg">
<path
d="m258 0c-45 0-83 38-83 83 0 45 37 83 83 83 45 0 83-39 83-84 0-45-38-82-83-82zm-85 204c-13 0-24 10-24 23v48c0 13 11 23 24 23h23v119h-23c-13 0-24 11-24 24l-0 47c0 13 11 24 24 24h168c13 0 24-11 24-24l0-47c0-13-11-24-24-24h-21v-190c0-13-11-23-24-23h-123z"></path>
</svg>
<svg height="0" width="0">
<defs>
<linearGradient id="lgrad-p" gradientTransform="rotate(75)"><stop offset="45%" stop-color="#4169e1"></stop><stop offset="99%" stop-color="#c44764"></stop></linearGradient>
<linearGradient id="lgrad-s" gradientTransform="rotate(75)"><stop offset="45%" stop-color="#ef3c3a"></stop><stop offset="99%" stop-color="#6d5eb7"></stop></linearGradient>
<linearGradient id="lgrad-g" gradientTransform="rotate(75)"><stop offset="45%" stop-color="#585f74"></stop><stop offset="99%" stop-color="#b6bbc8"></stop></linearGradient>
</defs>
</svg>
<div></div>
<style>
:first-child {
height:150px;
width:150px;
fill:url(#lgrad-p) blue;
}
div{
position:relative;
width:150px;
height:150px;
fill:url(#lgrad-s) red;
}
</style>
<script>
const shadow = document.querySelector('div').attachShadow({mode: 'open'});
shadow.innerHTML="<svg viewbox=\"0 0 512 512\">\
<path d=\"m258 0c-45 0-83 38-83 83 0 45 37 83 83 83 45 0 83-39 83-84 0-45-38-82-83-82zm-85 204c-13 0-24 10-24 23v48c0 13 11 23 24 23h23v119h-23c-13 0-24 11-24 24l-0 47c0 13 11 24 24 24h168c13 0 24-11 24-24l0-47c0-13-11-24-24-24h-21v-190c0-13-11-23-24-23h-123z\"></path>\
</svg>\
<svg height=\"0\">\
<defs>\
<linearGradient id=\"lgrad-s\" gradientTransform=\"rotate(75)\"><stop offset=\"45%\" stop-color=\"#ef3c3a\"></stop><stop offset=\"99%\" stop-color=\"#6d5eb7\"></stop></linearGradient>\
<linearGradient id=\"lgrad-g\" gradientTransform=\"rotate(75)\"><stop offset=\"45%\" stop-color=\"#585f74\"></stop><stop offset=\"99%\" stop-color=\"#b6bbc8\"></stop></linearGradient>\
</defs>\
</svg>\
";
</script>
_x000D_
The first one is normal SVG, the second one is inside a shadow dom.
It seems many indie developers like me are desperately looking for an answer to these questions for years. Strangely, even after 5 years this question was asked, it seems the answer to this question is still not clear.
As far as I can see, there is not any official statement in Google AdMob
documentation or website about how a developer can safely answer these questions. It seems developers are left on their own in the mystery about answering some legally binding questions about the SDK
.
In their support forums they can advice questioners to reach out to Apple Support:
Hi there,
I believe it would be best for you to reach out to Apple Support for your concern as it tackles with Apple Submission Guidelines rather than our SDK.
Regards, Joshua Lagonera Mobile Ads SDK Team
Or they can say that it is out of their scope of support:
Hello Robert,
On this forum, we deal with Mobile Ads SDK related technical concerns only. We would not be able to address you question as this is out of scope for our team.
Regards, Deepika Uragayala Mobile Ads SDK Team
The only answer I could find from a "Google person" is about the 4th question. It is not in the AdMob forum but in the "Tag Manager" forum but still related. It is like so:
Hi Jorn,
Apple asks you about your use of IDFA when submitting your application (https://developer.apple.com/Library/ios/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/Chapters/SubmittingTheApp.html). For an app that doesn't display advertising, but includes the AdSupport framework for conversion attribution, you would select the appropriate checkbox(es). In respect to the Limit Ad Tracking stipulation, all of GTM's tags that utilize IDFA respect the limit ad tracking stipulations of the SDK.
Thanks,
Eric Burley Google Tag Manager.
Here is an Internet Archive link in case they remove this page.
Lastly, let me mention about AdMob's only statement I've seen about this issue (here is the Internet Archive link):
The Mobile Ads SDK for iOS utilizes Apple's advertising identifier (IDFA). The SDK uses IDFA under the guidelines laid out in the iOS developer program license agreement. You must ensure you are in compliance with the iOS developer program license agreement policies governing the use of this identifier.
In conclusion, it seems most developers using AdMob simply checks 1st and 4th checkmarks and submit their apps without being completely sure about what Google exactly does in its SDK and without any official information about it. I wish good luck to us all.
Here's an alternative solution using javascipt:
document.querySelector('.slick-prev').innerHTML = '<img src="path/to/chevron-left-image.svg">'>;
document.querySelector('.slick-next').innerHTML = '<img src="path/to/chevron-right-image.svg">'>;
Change the img to text or what ever you require.
You are posting the data, so it should be $_POST. But 'name' is not the best name to use.
name = "name"
will only cause confusion IMO.
I use a library called ExcelDataReader, you can find it on NuGet. Be sure to install both ExcelDataReader and the ExcelDataReader.DataSet extension (the latter provides the required AsDataSet method referenced below).
I encapsulated everything in one function, you can copy it in your code directly. Give it a path to CSV file, it gets you a dataset with one table.
public static DataSet GetDataSet(string filepath)
{
var stream = File.OpenRead(filepath);
try
{
var reader = ExcelReaderFactory.CreateCsvReader(stream, new ExcelReaderConfiguration()
{
LeaveOpen = false
});
var result = reader.AsDataSet(new ExcelDataSetConfiguration()
{
// Gets or sets a value indicating whether to set the DataColumn.DataType
// property in a second pass.
UseColumnDataType = true,
// Gets or sets a callback to determine whether to include the current sheet
// in the DataSet. Called once per sheet before ConfigureDataTable.
FilterSheet = (tableReader, sheetIndex) => true,
// Gets or sets a callback to obtain configuration options for a DataTable.
ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
{
// Gets or sets a value indicating the prefix of generated column names.
EmptyColumnNamePrefix = "Column",
// Gets or sets a value indicating whether to use a row from the
// data as column names.
UseHeaderRow = true,
// Gets or sets a callback to determine which row is the header row.
// Only called when UseHeaderRow = true.
ReadHeaderRow = (rowReader) =>
{
// F.ex skip the first row and use the 2nd row as column headers:
//rowReader.Read();
},
// Gets or sets a callback to determine whether to include the
// current row in the DataTable.
FilterRow = (rowReader) =>
{
return true;
},
// Gets or sets a callback to determine whether to include the specific
// column in the DataTable. Called once per column after reading the
// headers.
FilterColumn = (rowReader, columnIndex) =>
{
return true;
}
}
});
return result;
}
catch (Exception ex)
{
return null;
}
finally
{
stream.Close();
stream.Dispose();
}
}
OpenCV image format supports the numpy array interface. A helper function can be made to support either grayscale or color images. This means the BGR -> RGB conversion can be conveniently done with a numpy slice, not a full copy of image data.
Note: this is a stride trick, so modifying the output array will also change the OpenCV image data. If you want a copy, use .copy()
method on the array!
import numpy as np
def img_as_array(im):
"""OpenCV's native format to a numpy array view"""
w, h, n = im.width, im.height, im.channels
modes = {1: "L", 3: "RGB", 4: "RGBA"}
if n not in modes:
raise Exception('unsupported number of channels: {0}'.format(n))
out = np.asarray(im)
if n != 1:
out = out[:, :, ::-1] # BGR -> RGB conversion
return out
@echo off
setlocal
set "list=a b c d"
(
for %%i in (%list%) do (
echo(%%i
echo(
)
)>file.txt
You don't need - actually, can't "declare" variables in batch. Assigning a value to a variable creates it, and assigning an empty string deletes it. Any variable name that doesn't have an assigned value HAS a value of an empty string. ALL variables are strings - WITHOUT exception. There ARE operations that appear to perform (integer) mathematical functions, but they operate by converting back and forth from strings.
Batch is sensitive to spaces in variable names, so your assignment as posted would assign the string "A B C D"
- including the quotes, to the variable "list "
- NOT including the quotes, but including the space. The syntax set "var=string"
is used to assign the value string
to var
whereas set var=string
will do the same thing. Almost. In the first case, any stray trailing spaces after the closing quote are EXCLUDED from the value assigned, in the second, they are INCLUDED. Spaces are a little hard to see when printed.
ECHO
echoes strings. Clasically, it is followed by a space - one of the default separators used by batch (the others are TAB, COMMA, SEMICOLON - any of these do just as well BUT TABS often get transformed to a space-squence by text-editors and the others have grown quirks of their own over the years.) Other characters following the O
in ECHO
have been found to do precisely what the documented SPACE should do. DOT is common. Open-parenthesis (
is probably the most useful since the command
ECHO.%emptyvalue%
will produce a report of the ECHO
state (ECHO is on/off
) whereas
ECHO(%emptyvalue%
will produce an empty line.
The problem with ECHO(
is that the result "looks" unbalanced.
Since this is at least the third time I've wasted more than 5 min on this problem I figured I'd post the Q & A. I hope it helps someone else down the road... probably me!
I typed in
instead of of
in the ngFor expression.
Befor 2-beta.17, it should be:
<div *ngFor="#talk of talks">
As of beta.17, use the let
syntax instead of #
. See the UPDATE further down for more info.
Note that the ngFor syntax "desugars" into the following:
<template ngFor #talk [ngForOf]="talks">
<div>...</div>
</template>
If we use in
instead, it turns into
<template ngFor #talk [ngForIn]="talks">
<div>...</div>
</template>
Since ngForIn
isn't an attribute directive with an input property of the same name (like ngIf
), Angular then tries to see if it is a (known native) property of the template
element, and it isn't, hence the error.
UPDATE - as of 2-beta.17, use the let
syntax instead of #
. This updates to the following:
<div *ngFor="let talk of talks">
Note that the ngFor syntax "desugars" into the following:
<template ngFor let-talk [ngForOf]="talks">
<div>...</div>
</template>
If we use in
instead, it turns into
<template ngFor let-talk [ngForIn]="talks">
<div>...</div>
</template>
<html>
<title>Practice Session</title>
<body>
<form name="RegForm" onsubmit="return validate()" method="post">
<p>Name: <input type="text" name="Name"> </p><br>
<p>Contact: <input type="text" name="Telephone"> </p><br>
<p><input type="submit" value="send" name="Submit"></p>
</form>
</body>
<script>
function validate()
{
var name = document.forms["RegForm"]["Name"];
var phone = document.forms["RegForm"]["Telephone"];
if (name.value == "")
{
window.alert("Please enter your name.");
name.focus();
return false;
}
else if(isNaN(name.value) /*"%d[10]"*/)
{
alert("name confirmed");
}
else{
window.alert("please enter character");
}
if (phone.value == "")
{
window.alert("Please enter your telephone number.");
phone.focus();
return false;
}
else if(!isNaN(phone.value) /*phone.value == isNaN(phone.value)*/)
{
alert("number confirmed");
}
else{
window.alert("please enter numbers only");
}
}
</script>
</html>
Just one line will be OK.
cat "`dirname $0`"/../some.txt
I'm not sure I understand completely, but you might be looking for the 'formatoptions' configuration setting. Try something like :set formatoptions-=t
. The t
option will insert line breaks to make text wrap at the width set by textwidth
. You can also put this command in your .vimrc
, just remove the colon (:
).
Installing both webpack and CLI globally worked for me.
npm i -g webpack webpack-cli
In my case, I was using the ASP.NET Identity Framework. I had used the built in UserManager.FindByNameAsync
method to retrieve an ApplicationUser
entity. I then tried to reference this entity on a newly created entity on a different DbContext
. This resulted in the exception you originally saw.
I solved this by creating a new ApplicationUser
entity with only the Id
from the UserManager
method and referencing that new entity.
Not sure if this counts as an answer - but here is YouTube Video From Google's Course (Developing Android Apps with Kotlin) that explains the difference.
According to docs:
Bitcode is an intermediate representation of a compiled program. Apps you upload to iTunes Connect that contain bitcode will be compiled and linked on the App Store. Including bitcode will allow Apple to re-optimize your app binary in the future without the need to submit a new version of your app to the store.
Update: This phrase in "New Features in Xcode 7" made me to think for a long time that Bitcode is needed for Slicing to reduce app size:
When you archive for submission to the App Store, Xcode will compile your app into an intermediate representation. The App Store will then compile the bitcode down into the 64 or 32 bit executables as necessary.
However that's not true, Bitcode and Slicing work independently: Slicing is about reducing app size and generating app bundle variants, and Bitcode is about certain binary optimizations. I've verified this by checking included architectures in executables of non-bitcode apps and founding that they only include necessary ones.
Bitcode allows other App Thinning component called Slicing to generate app bundle variants with particular executables for particular architectures, e.g. iPhone 5S variant will include only arm64 executable, iPad Mini armv7 and so on.
For iOS apps, bitcode is the default, but optional. If you provide bitcode, all apps and frameworks in the app bundle need to include bitcode. For watchOS and tvOS apps, bitcode is required.
From Xcode 7 reference:
Activating this setting indicates that the target or project should generate bitcode during compilation for platforms and architectures which support it. For Archive builds, bitcode will be generated in the linked binary for submission to the app store. For other builds, the compiler and linker will check whether the code complies with the requirements for bitcode generation, but will not generate actual bitcode.
Here's a couple of links that will help in deeper understanding of Bitcode:
select * from *tablename* where 1 having length(*fieldname*)=*fieldlength*
Example if you want to select from customer the entry's with a name shorter then 2 chars.
select * from customer where 1 **having length(name)<2**
Same way you'd hide anything: visibility: hidden;
Notice you're not dynamically allocating the variable, which pretty much means the data inside str
, in your function, will be lost by the end of the function.
You should have:
char * createStr() {
char char1= 'm';
char char2= 'y';
char *str = malloc(3);
str[0] = char1;
str[1] = char2;
str[2] = '\0';
return str;
}
Then, when you call the function, the type of the variable that will receive the data must match that of the function return. So, you should have:
char *returned_str = createStr();
It worths mentioning that the returned value must be freed to prevent memory leaks.
char *returned_str = createStr();
//doSomething
...
free(returned_str);
Some Android phones contain Busybox. Was hard to find.
To see if busybox was around:
ls -lR / | grep busybox
If you know it's around. You need some read/write space. Try you flash drive, /sdcard
cd /sdcard
ls -lR / >lsoutput.txt
upload to your computer. Upload the file. Get some text editor. Search for busybox. Will see what directory the file was found in.
busybox find /sdcard -iname 'python*'
to make busybox easier to access, you could:
cd /sdcard
ln -s /where/ever/busybox/is busybox
/sdcard/busybox find /sdcard -iname 'python*'
Or any other place you want. R
Events are really delegates under the hood and any delegate object can have multiple functions attached to it and detatched from it using the += and -= operators, respectively.
Events can also be controlled with the add/remove, similar to get/set except they're invoked when += and -= are used:
public event EventHandler SelectiveEvent(object sender, EventArgs args)
{ add
{ if (value.Target == null) throw new Exception("No static handlers!");
_SelectiveEvent += value;
}
remove
{ _SelectiveEvent -= value;
}
} EventHandler _SelectiveEvent;
If you are trying to allocate space for an array of pointers, such as
char** my_array_of_strings; // or some array of pointers such as int** or even void**
then you will need to consider word size (8 bytes in a 64-bit system, 4 bytes in a 32-bit system) when allocating space for n pointers. The size of a pointer is the same of your word size.
So while you may wish to allocate space for n pointers, you are actually going to need n times 8 or 4 (for 64-bit or 32-bit systems, respectively)
To avoid overflowing your allocated memory for n elements of 8 bytes:
my_array_of_strings = (char**) malloc( n * 8 ); // for 64-bit systems
my_array_of_strings = (char**) malloc( n * 4 ); // for 32-bit systems
This will return a block of n pointers, each consisting of 8 bytes (or 4 bytes if you're using a 32-bit system)
I have noticed that Linux will allow you to use all n pointers when you haven't compensated for word size, but when you try to free that memory it realizes its mistake and it gives out that rather nasty error. And it is a bad one, when you overflow allocated memory, many security issues lie in wait.
d4 = dict(d1.items() + d2.items() + d3.items())
alternatively (and supposedly faster):
d4 = dict(d1)
d4.update(d2)
d4.update(d3)
Previous SO question that both of these answers came from is here.
String str = " Text with multiple spaces ";
str = org.apache.commons.lang3.StringUtils.normalizeSpace(str);
// str = "Text with multiple spaces"
If you want to modify the original array instead of returning a new array, use .push()
...
array1.push.apply(array1, array2);
array1.push.apply(array1, array3);
I used .apply
to push the individual members of arrays 2
and 3
at once.
or...
array1.push.apply(array1, array2.concat(array3));
To deal with large arrays, you can do this in batches.
for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
array1.push.apply(array1, to_add.slice(n, n+300));
}
If you do this a lot, create a method or function to handle it.
var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);
Object.defineProperty(Array.prototype, "pushArrayMembers", {
value: function() {
for (var i = 0; i < arguments.length; i++) {
var to_add = arguments[i];
for (var n = 0; n < to_add.length; n+=300) {
push_apply(this, slice_call(to_add, n, n+300));
}
}
}
});
and use it like this:
array1.pushArrayMembers(array2, array3);
var push_apply = Function.apply.bind([].push);_x000D_
var slice_call = Function.call.bind([].slice);_x000D_
_x000D_
Object.defineProperty(Array.prototype, "pushArrayMembers", {_x000D_
value: function() {_x000D_
for (var i = 0; i < arguments.length; i++) {_x000D_
var to_add = arguments[i];_x000D_
for (var n = 0; n < to_add.length; n+=300) {_x000D_
push_apply(this, slice_call(to_add, n, n+300));_x000D_
}_x000D_
}_x000D_
}_x000D_
});_x000D_
_x000D_
var array1 = ['a','b','c'];_x000D_
var array2 = ['d','e','f'];_x000D_
var array3 = ['g','h','i'];_x000D_
_x000D_
array1.pushArrayMembers(array2, array3);_x000D_
_x000D_
document.body.textContent = JSON.stringify(array1, null, 4);
_x000D_
If everything works as it should it shouldn't, BUT we all know everything doesn't work the way it should especially when it comes to the query optimizer, query plan caching and statistics.
First I would suggest rebuilding index and statistics, then clearing the query plan cache just to make sure that's not screwing things up. However I've experienced problems even when that's done.
I've experienced some cases where a left join has been faster than a inner join.
The underlying reason is this: If you have two tables and you join on a column with an index (on both tables). The inner join will produce the same result no matter if you loop over the entries in the index on table one and match with index on table two as if you would do the reverse: Loop over entries in the index on table two and match with index in table one. The problem is when you have misleading statistics, the query optimizer will use the statistics of the index to find the table with least matching entries (based on your other criteria). If you have two tables with 1 million in each, in table one you have 10 rows matching and in table two you have 100000 rows matching. The best way would be to do an index scan on table one and matching 10 times in table two. The reverse would be an index scan that loops over 100000 rows and tries to match 100000 times and only 10 succeed. So if the statistics isn't correct the optimizer might choose the wrong table and index to loop over.
If the optimizer chooses to optimize the left join in the order it is written it will perform better than the inner join.
BUT, the optimizer may also optimize a left join sub-optimally as a left semi join. To make it choose the one you want you can use the force order hint.
In order to replace text using regular expression use the re.sub function:
sub(pattern, repl, string[, count, flags])
It will replace non-everlaping instances of pattern
by the text passed as string
. If you need to analyze the match to extract information about specific group captures, for instance, you can pass a function to the string
argument. more info here.
Examples
>>> import re
>>> re.sub(r'a', 'b', 'banana')
'bbnbnb'
>>> re.sub(r'/\d+', '/{id}', '/andre/23/abobora/43435')
'/andre/{id}/abobora/{id}'
from google.colab import drive
drive.mount('/content/drive')
This worked perfect for me
I was later able to use the os
library to access my files just like how I access them on my PC
Upon installation, the Android SDK generates a debug
signing certificate for you in a keystore called debug.keystore
. The Eclipse plug-in uses this certificate to sign each application build that is generated.
Unfortunately a debug certificate is only valid for 365 days. To generate a new one you must delete the existing debug.keystore
file. Its location is platform dependent - you can find it in Preferences - Android - Build - Default debug keystore.
What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.
On a rooted device, you may be able to bypass the message using either
the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup>
is set to any value but "mifareclassic" or "all". For instance, you could use:
<CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet>
that already exists in that file).
Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).
This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode
) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK
.
The colon is a built-in command that does nothing, but returns 0 (success). Thus, it's shorter (and faster) than calling an actual command to do the same thing.
I tried a couple of those suggestions above, the best solution for me was to disable backgroundquery for each connection.
With ActiveWorkbook.Connections("Query - DL_3").OLEDBConnection
.BackgroundQuery = False
End With
$string = "233718_This_is_a_string";
$withCharacter = strstr($string, '_'); // "_This_is_a_string"
echo substr($withCharacter, 1); // "This_is_a_string"
In a single statement it would be.
echo substr(strstr("233718_This_is_a_string", '_'), 1); // "This_is_a_string"
It is impossible to safely escape a string without a DB connection. mysql_real_escape_string()
and prepared statements need a connection to the database so that they can escape the string using the appropriate character set - otherwise SQL injection attacks are still possible using multi-byte characters.
If you are only testing, then you may as well use mysql_escape_string()
, it's not 100% guaranteed against SQL injection attacks, but it's impossible to build anything safer without a DB connection.
I Stumbled on this post many times, as I often need to handle huge files (10 Gigas+).
After being tired of buggy and pretty limited freeware, and not willing to pay fo costly editors after trial expired (not worth the money after all), I just used VIM for Windows with great success and satisfaction.
It is simply PERFECT for this need, fully customizable, with ALL feature one can think of when dealing with text files (searching, replacing, reading, etc. you name it)
I am very surprised nobody answered that (Except a previous answer but for MacOS)...
For the record I stumbled on it on this blog post, which wisely adviced it.
Try:
select distinct T1.id
from TABLE1 T1
where not exists (select distinct T2.id
from TABLE2 T2
where T2.id = T1.id)
With sql oracle 11g+
create a pair of client / server, so that after the execution, client server sends the correct time and date. Then, the client asks the server pm GMT and the server sends back the answer right.
I'm late to the party, but searching for the correct way to do it I came across this page it was one of the top Google search returns, so I will like to share my view on the problem, which I consider it to be up to date at the time of writing this post (beginning of 2017). From PHP 7.1.0 the mcrypt_decrypt
and mcrypt_encrypt
is going to be deprecated, so building future proof code should use openssl_encrypt and openssl_decrypt
You can do something like:
$string_to_encrypt="Test";
$password="password";
$encrypted_string=openssl_encrypt($string_to_encrypt,"AES-128-ECB",$password);
$decrypted_string=openssl_decrypt($encrypted_string,"AES-128-ECB",$password);
Important: This uses ECB mode, which isn't secure. If you want a simple solution without taking a crash course in cryptography engineering, don't write it yourself, just use a library.
You can use any other chipper methods as well, depending on your security need. To find out the available chipper methods please see the openssl_get_cipher_methods function.
Only the "Continue For" is an acceptable standard (the rest leads to "spaghetti code").
At least with "continue for" the programmer knows the code goes directly to the top of the loop.
For purists though, something like this is best since it is pure "non-spaghetti" code.
Dim bKeepGoing as Boolean
For Each I As Item In Items
bKeepGoing = True
If I = x Then
bKeepGoing = False
End If
if bKeepGoing then
' Do something
endif
Next
For ease of coding though, "Continue For" is OK. (Good idea to comment it though).
Using "Continue For"
For Each I As Item In Items
If I = x Then
Continue For 'skip back directly to top of loop
End If
' Do something
Next
Thanks to Ian Henry!
In case if you need to get file from MS SQL Server here is the solution.
public FileResult DownloadDocument(string id)
{
if (!string.IsNullOrEmpty(id))
{
try
{
var fileId = Guid.Parse(id);
var myFile = AppModel.MyFiles.SingleOrDefault(x => x.Id == fileId);
if (myFile != null)
{
byte[] fileBytes = myFile.FileData;
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, myFile.FileName);
}
}
catch
{
}
}
return null;
}
Where AppModel is EntityFramework
model and MyFiles presents table in your database.
FileData is varbinary(MAX)
in MyFiles table.
Your script works when you run it from the console but fails in cron.
Your crontab doesn't have the right path variables (and possibly shell)
Add your current shell and path the crontab
#!/bin/bash
#
# Date: August 22, 2013
# Author: Steve Stonebraker
# File: add_current_shell_and_path_to_crontab.sh
# Description: Add current user's shell and path to crontab
# Source: http://brakertech.com/add-current-path-to-crontab
# Github: hhttps://github.com/ssstonebraker/braker-scripts/blob/master/working-scripts/add_current_shell_and_path_to_crontab.sh
# function that is called when the script exits (cleans up our tmp.cron file)
function finish { [ -e "tmp.cron" ] && rm tmp.cron; }
#whenver the script exits call the function "finish"
trap finish EXIT
########################################
# pretty printing functions
function print_status { echo -e "\x1B[01;34m[*]\x1B[0m $1"; }
function print_good { echo -e "\x1B[01;32m[*]\x1B[0m $1"; }
function print_error { echo -e "\x1B[01;31m[*]\x1B[0m $1"; }
function print_notification { echo -e "\x1B[01;33m[*]\x1B[0m $1"; }
function printline {
hr=-------------------------------------------------------------------------------------------------------------------------------
printf '%s\n' "${hr:0:${COLUMNS:-$(tput cols)}}"
}
####################################
# print message and exit program
function die { print_error "$1"; exit 1; }
####################################
# user must have at least one job in their crontab
function require_gt1_user_crontab_job {
crontab -l &> /dev/null
[ $? -ne 0 ] && die "Script requires you have at least one user crontab job!"
}
####################################
# Add current shell and path to user's crontab
function add_shell_path_to_crontab {
#print info about what's being added
print_notification "Current SHELL: ${SHELL}"
print_notification "Current PATH: ${PATH}"
#Add current shell and path to crontab
print_status "Adding current SHELL and PATH to crontab \nold crontab:"
printline; crontab -l; printline
#keep old comments but start new crontab file
crontab -l | grep "^#" > tmp.cron
#Add our current shell and path to the new crontab file
echo -e "SHELL=${SHELL}\nPATH=${PATH}\n" >> tmp.cron
#Add old crontab entries but ignore comments or any shell or path statements
crontab -l | grep -v "^#" | grep -v "SHELL" | grep -v "PATH" >> tmp.cron
#load up the new crontab we just created
crontab tmp.cron
#Display new crontab
print_good "New crontab:"
printline; crontab -l; printline
}
require_gt1_user_crontab_job
add_shell_path_to_crontab
The enctype attribute specifies how the form-data should be encoded when submitting it to the server.
The enctype attribute can be used only if method="post".
No characters are encoded. This value is required when you are using forms that have a file upload control
From W3Schools
I have been using the snippet below when working with CLI tools and I want to know if some resource exist or not, but I don't care about the output.
if [ -z "$(cat no_exist 2>&1 >/dev/null)" ]; then
echo "none exist actually exist!"
fi
You can't. The emulator does not support Bluetooth, as mentioned in the SDK's docs and several other places. Android emulator does not have bluetooth capabilities".
You can only use real devices.
Emulator Limitations
The functional limitations of the emulator include:
Refer to the documentation
Yes, it should be a field. And I think this value is assigned when you create your array (you have to choose the length of array while creating, for example: int[] a = new int[5];
).
<script type="text/javascript">
$(document).ready(function() {
var asdf = $('.capsf').text();
$('.capsf').text(asdf.toLowerCase());
});
</script>
<div style="text-transform: capitalize;" class="capsf">sd GJHGJ GJHgjh gh hghhjk ku</div>
Answer for your question is below:
Swift 2.1
do {
if let postData : NSData = try NSJSONSerialization.dataWithJSONObject(dictDataToBeConverted, options: NSJSONWritingOptions.PrettyPrinted){
let json = NSString(data: postData, encoding: NSUTF8StringEncoding)! as String
print(json)}
}
catch {
print(error)
}
git clone <Repo> <DestinationDirectory>
Clone the repository located at Repo into the folder called DestinationDirectory on the local machine.
Open a terminal:
Check MySQL system pref panel, if it says something along the line "Warning, /usr/local/mysql/data is not owned by 'mysql' or '_mysql'
If yes, go to the mysql folder cd /usr/local/mysql
do a sudo chown -R _mysql data/
This will change ownership of the /usr/local/mysql/data and all of its content to own by user '_mysql'
Check MySQL system pref panel, it should be saying it's running now, auto-magically. If not start again.
Another way to confirm is to do a
netstat -na | grep 3306
It should say:
tcp46 0 0 *.3306 *.* LISTEN
To see the process owner and process id of the mysqld:
ps aux | grep mysql
You can try the following code to request camera permission in marshmallow. First check if the user grant the permission. If user has not granted the permission, then request the camera permission:
private static final int MY_CAMERA_REQUEST_CODE = 100;
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_REQUEST_CODE);
}
After requesting the permission, dialog will display to ask permission containing allow
and deny
options. After clicking action we can get result of the request with the following method:
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_CAMERA_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
}
}
}
I had a similar problem and for encrypt/decrypt i came up with this solution:
public static byte[] generateKey(String password) throws Exception
{
byte[] keyStart = password.getBytes("UTF-8");
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
sr.setSeed(keyStart);
kgen.init(128, sr);
SecretKey skey = kgen.generateKey();
return skey.getEncoded();
}
public static byte[] encodeFile(byte[] key, byte[] fileData) throws Exception
{
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(fileData);
return encrypted;
}
public static byte[] decodeFile(byte[] key, byte[] fileData) throws Exception
{
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(fileData);
return decrypted;
}
To save a encrypted file to sd do:
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "your_folder_on_sd", "file_name");
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
byte[] yourKey = generateKey("password");
byte[] filesBytes = encodeFile(yourKey, yourByteArrayContainigDataToEncrypt);
bos.write(fileBytes);
bos.flush();
bos.close();
To decode a file use:
byte[] yourKey = generateKey("password");
byte[] decodedData = decodeFile(yourKey, bytesOfYourFile);
For reading in a file to a byte Array there a different way out there. A Example: http://examples.javacodegeeks.com/core-java/io/fileinputstream/read-file-in-byte-array-with-fileinputstream/
Here are slightly different options to accomplish the task at hand.
using toMap
:
list.stream()
.collect(Collectors.toMap(Function.identity(), e -> 1, Math::addExact));
using Map::merge
:
Map<String, Integer> accumulator = new HashMap<>();
list.forEach(s -> accumulator.merge(s, 1, Math::addExact));
I just wanted to add this version because this is such a useful thread and I think this is a very simple implementation. I have used this multiple times in various types if multithreaded application:
Task.Factory.StartNew(() =>
{
DoLongRunningWork();
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
{ txt.Text = "Complete"; }));
});
Anyone else stumbling upon this answer should note that jQuery now (>=1.3) has outerHeight
/outerWidth
functions to retrieve the width including padding/borders, e.g.
$(elem).outerWidth(); // Returns the width + padding + borders
To include the margin as well, simply pass true
:
$(elem).outerWidth( true ); // Returns the width + padding + borders + margins
In the case you need to remove line breaks from the begin or end of the string, you may use this:
UPDATE table
SET field = regexp_replace(field, E'(^[\\n\\r]+)|([\\n\\r]+$)', '', 'g' );
Have in mind that the hat ^
means the begin of the string and the dollar sign $
means the end of the string.
Hope it help someone.
I was able to get this to work by using the Invoke-Expression
cmdlet.
Invoke-Expression "& `"$scriptPath`" test -r $number -b $testNumber -f $FileVersion -a $ApplicationID"
Keeping it simple, I personally like string concatenation:
print("Total score for " + name + " is " + score)
It works with both Python 2.7 an 3.X.
NOTE: If score is an int, then, you should convert it to str:
print("Total score for " + name + " is " + str(score))
For 2.3 seconds you should do:
System.Threading.Thread.Sleep(2300);
You could do
if item not in mylist:
mylist.append(item)
But you should really use a set, like this :
myset = set()
myset.add(item)
EDIT: If order is important but your list is very big, you should probably use both a list and a set, like so:
mylist = []
myset = set()
for item in ...:
if item not in myset:
mylist.append(item)
myset.add(item)
This way, you get fast lookup for element existence, but you keep your ordering. If you use the naive solution, you will get O(n) performance for the lookup, and that can be bad if your list is big
Or, as @larsman pointed out, you can use OrderedDict to the same effect:
from collections import OrderedDict
mydict = OrderedDict()
for item in ...:
mydict[item] = True
I had the same problem after setting up my environment on Windows 10. I have Python 3.6.2 x64 installed as my default Python distribution and is in my PATH so I can launch from cmd prompt.
I installed PyQt5 (pip install pyqt5
) and Spyder (pip install spyder
) which both installed w/out error and included all of the necessary dependencies.
To launch Spyder, I created a simple Python script (Spyder.py):
# Spyder Start Script
from spyder.app import start
start.main()
Then I created a Windows batch file (Spyder.bat):
@echo off
python c:\<path_to_Spyder_py>\Spyder.py
Lastly, I created a shortcut on my desktop which launches Spyder.bat and updated the icon to one I downloaded from the Spyder github project.
Works like a charm for me.
if you want put a input required if other is written:
<input type='text'
name='name'
ng-model='person.name'/>
<input type='text'
ng-model='person.lastname'
ng-required='person.name' />
Regards.
onclick="window.open('your_html', '_blank')"
I also looked for a simple console replacement, just to dump text. So what I did was this function:
function remoteLog (arg) {
var file = '/files/remoteLog.php';
$.post(file, {text: arg});
}
The remote PHP file recorded all the output to a database in arg
. It took me 5 minutes (OK, on the server side I used a simple logging library that records and displays text messages, but still...).
Probably the easiest to hide a div and show a div in PHP based on a variables and the operator.
<?php
$query3 = mysql_query($query3);
$numrows = mysql_num_rows($query3);
?>
<html>
<?php if($numrows > null){ ?>
no meow :-(
<?php } ?>
<?php if($numrows < null){ ?>
lots of meow
<?php } ?>
</html>
Here is my original code before adding your requirements:
<?php
$address = 'meow';
?>
<?php if($address == null){ ?>
no meow :-(
<?php } ?>
<?php if($address != null){ ?>
lots of meow
<?php } ?>
For multicolumn listbox extract data from any column of selected row by
listboxControl.List(listboxControl.ListIndex,col_num)
where col_num is required column ( 0 for first column)
You can use "Gena" library. It closely resembles stl::vector
in pure C89.
From the README, it features:
vec[k][j]
;You can check it out here:
For the official CLI client "psql" see here. And "pgAdmin3" 1.10 (still in beta) has "pgScript".