To keep this question current it is worth highlighting that AssemblyInformationalVersion
is used by NuGet and reflects the package version including any pre-release suffix.
For example an AssemblyVersion of 1.0.3.* packaged with the asp.net core dotnet-cli
dotnet pack --version-suffix ci-7 src/MyProject
Produces a package with version 1.0.3-ci-7 which you can inspect with reflection using:
CustomAttributeExtensions.GetCustomAttribute<AssemblyInformationalVersionAttribute>(asm);
Assuming you alredy tried to "Add Reference..." as explained above and did not succeed, you can have a look here. They say you have to meet some prerequisites: - .NET 3.5 SP1 - Windows Installer 4.5
EDIT: According to this post it is a known issue.
And this could be the solution you're looking for :)
Syntax is not a minor thing, it has a direct impact on how we think. It also has a direct effect on the rules we create for the systems we use. As an example we have the order of operations because of the way we write mathematical equations or sentences. The standard notation for mathematics allows people to read it more than one way and arrive at different answers given the same equation. If we had used prefix or postfix notation we would have created rules to distinguish what the numbers to be manipulated were rather than only having rules for the order in which to compute values.
The standard notation makes it plain what numbers we are talking about while making the order in which to compute them ambiguous. Prefix and postfix notation make the order in which to compute plain while making the numbers ambiguous. Python would already have multiline lambdas if it were not for the difficulties caused by the syntactic whitespace. (Proposals do exist for pulling this kind of thing off without necessarily adding explicit block delimiters.)
I find it easier to write conditions where I want something to occur if a condition is false much easier to write with the unless statement in Ruby than the semantically equivalent "if-not" construction in Ruby or other languages for example. If most of the languages that people are using today are equal in power, how can the syntax of each language be considered a trivial thing? After specific features like blocks and inheritance mechanisms etc. syntax is the most important part of a language,hardly a superficial thing.
What is superficial are the aesthetic qualities of beauty that we ascribe to syntax. Aesthetics have nothing to do with how our cognition works, syntax does.
When you have image into yours drawable gallery then you just need to pick the option of image view pick and drag into app activity you want to show and select the required image.
Double stars (**
) are exponentiation. So "2 times 2" and "2 to the power 2" are the same. Change the numbers and you'll see a difference.
public <T extends Iterable> T nullGuard(T item) {
if (item == null) {
return Collections.EmptyList;
} else {
return item;
}
}
or, if saving lines of text is a priority (it shouldn't be)
public <T extends Iterable> T nullGuard(T item) {
return (item == null) ? Collections.EmptyList : item;
}
would allow you to write
for (Object obj : nullGuard(list)) {
...
}
Of course, this really just moves the complexity elsewhere.
You can get a list of the first element in each tuple using a list comprehension:
>>> my_tuples = [(1, 2, 3), ('a', 'b', 'c', 'd', 'e'), (True, False), 'qwerty']
>>> first_elts = [x[0] for x in my_tuples]
>>> first_elts
[1, 'a', True, 'q']
I just spent like 40 minutes trying to debug a non-working /status with:
$ SCRIPT_NAME=/status SCRIPT_FILENAME=/status QUERY_STRING= REQUEST_METHOD=GET cgi-fcgi -bind -connect /var/run/php5-fpm.sock
It just produced "File not found" error, while the actual scripts (that are found on the filesystem) worked just fine.
Turned out, I had a couple of orphaned processes of php5-fpm. After I killed everything and restarted php5-fpm cleanly, it just went back to normal.
Hope this helps.
I am fairly sure that Linq can do this.... but MyList does not have a select method on it (which is what I would have used).
Yes, LINQ can do this. It's simply:
MyList.Select(x => x.Name).ToArray();
Most likely the issue is that you either don't have a reference to System.Core
, or you are missing an using
directive for System.Linq
.
You can execute sql queries directly as follows :
private int DeleteData()
{
using (var ctx = new MyEntities(this.ConnectionString))
{
if (ctx != null)
{
//Delete command
return ctx.ExecuteStoreCommand("DELETE FROM ALARM WHERE AlarmID > 100");
}
}
return 0;
}
For select we may use
using (var context = new MyContext())
{
var blogs = context.MyTable.SqlQuery("SELECT * FROM dbo.MyTable").ToList();
}
Another option is to change the version number in the packages.config
file. This will cause NuGet to download the dlls for that version the next time you build.
You need to install this
https://pypi.python.org/pypi/six
If you still don't know what pip is , then please also google for pip install
Python has it's own package manager which is supposed to help you finding packages and their dependencies: http://www.pip-installer.org/en/latest/
More accurately, your mod1
and lib
directories are not modules, they are packages. The file mod11.py
is a module.
Python does not automatically import subpackages or modules. You have to explicitly do it, or "cheat" by adding import statements in the initializers.
>>> import lib
>>> dir(lib)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
>>> import lib.pkg1
>>> import lib.pkg1.mod11
>>> lib.pkg1.mod11.mod12()
mod12
An alternative is to use the from
syntax to "pull" a module from a package into you scripts namespace.
>>> from lib.pkg1 import mod11
Then reference the function as simply mod11.mod12()
.
$("#select-id").chosen().val()
Quoted from http://webdesign.about.com/od/beginningcss/f/css_import_link.htm
The main purpose of @import method is to use multiple style sheets on a page, but only one link in your < head >. For example, a corporation might have a global style sheet for every page on the site, with sub-sections having additional styles that only apply to that sub-section. By linking to the sub-section style sheet and importing the global styles at the top of that style sheet, you don't have to maintain a gigantic style sheet with all the styles for the site and every sub-section. The only requirement is that any @import rules need to come before the rest of your style rules. And remember that inheritance can still be a problem.
Try using the WHERE
clause:
SELECT column1 FROM table WHERE Isnumeric(column1);
My solution was that I had recently upgraded my iOS device to 8.3 and Xcode still didn't recognize it. The fix was to simply upgrade Xcode to 6.3 :)
This is what you may want
$ echo "continuation"\
> "lines"
continuation lines
If this creates two arguments to echo and you only want one, then let's look at string concatenation. In bash, placing two strings next to each other concatenate:
$ echo "continuation""lines"
continuationlines
So a continuation line without an indent is one way to break up a string:
$ echo "continuation"\
> "lines"
continuationlines
But when an indent is used:
$ echo "continuation"\
> "lines"
continuation lines
You get two arguments because this is no longer a concatenation.
If you would like a single string which crosses lines, while indenting but not getting all those spaces, one approach you can try is to ditch the continuation line and use variables:
$ a="continuation"
$ b="lines"
$ echo $a$b
continuationlines
This will allow you to have cleanly indented code at the expense of additional variables. If you make the variables local it should not be too bad.
If you don't have to use the support library then have a look at Roman's answer.
But if you want to use the support library you have to use the old animation framework as described below.
After consulting Reto's and blindstuff's answers I have gotten the following code working.
The fragments appear sliding in from the right and sliding out to the left when back is pressed.
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.pop_enter, R.anim.pop_exit);
CustomFragment newCustomFragment = CustomFragment.newInstance();
transaction.replace(R.id.fragment_container, newCustomFragment );
transaction.addToBackStack(null);
transaction.commit();
The order is important. This means you must call setCustomAnimations()
before replace()
or the animation will not take effect!
Next these files have to be placed inside the res/anim folder.
enter.xml:
<?xml version="1.0" encoding="utf-8"?>
<set>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="100%"
android:toXDelta="0"
android:interpolator="@android:anim/decelerate_interpolator"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
exit.xml:
<set>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0"
android:toXDelta="-100%"
android:interpolator="@android:anim/accelerate_interpolator"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
pop_enter.xml:
<set>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="-100%"
android:toXDelta="0"
android:interpolator="@android:anim/decelerate_interpolator"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
pop_exit.xml:
<?xml version="1.0" encoding="utf-8"?>
<set>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0"
android:toXDelta="100%"
android:interpolator="@android:anim/accelerate_interpolator"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
The duration of the animations can be changed to any of the default values like @android:integer/config_shortAnimTime
or any other number.
Note that if in between fragment replacements a configuration change happens (for example rotation) the back action isn't animated. This is a documented bug that still exists in the rev 20 of the support library.
Run BIDS as administrator despite of existing membership of Administrators group.
find all tabs and replaced by 4 spaces in notepad ++ .It worked.
In older versions of IIS, you will not find Advance Settings
so to enable Enable 32-bit Applications
you have to execute the following commands:
cscript %SYSTEMDRIVE%\inetpub\adminscripts\adsutil.vbs SET W3SVC/AppPools/Enable32bitAppOnWin64 1
and
%SYSTEMROOT%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -i
Reference : Here
Check out this snippet:
Private Sub openDialog()
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
' Set the title of the dialog box.
.Title = "Please select the file."
' Clear out the current filters, and add our own.
.Filters.Clear
.Filters.Add "Excel 2003", "*.xls"
.Filters.Add "All Files", "*.*"
' Show the dialog box. If the .Show method returns True, the
' user picked at least one file. If the .Show method returns
' False, the user clicked Cancel.
If .Show = True Then
txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox
End If
End With
End Sub
I think this is what you are asking for.
Oracle have announced a "statement of direction" for ODP.net and the Entity Framework:
In summary, ODP.Net beta around the end of 2010, production sometime in 2011.
A quick way to list your FKs (Foreign Key references) using the
KEY_COLUMN_USAGE view:
SELECT CONCAT( table_name, '.',
column_name, ' -> ',
referenced_table_name, '.',
referenced_column_name ) AS list_of_fks
FROM information_schema.KEY_COLUMN_USAGE
WHERE REFERENCED_TABLE_SCHEMA = (your schema name here)
AND REFERENCED_TABLE_NAME is not null
ORDER BY TABLE_NAME, COLUMN_NAME;
This query does assume that the constraints and all referenced and referencing tables are in the same schema.
Add your own comment.
Source: the official mysql manual.
Here is 2018 updated solution as described in the Mozilla Development Resources
TO ENCODE FROM UNICODE TO B64
function b64EncodeUnicode(str) {
// first we use encodeURIComponent to get percent-encoded UTF-8,
// then we convert the percent encodings into raw bytes which
// can be fed into btoa.
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
function toSolidBytes(match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
b64EncodeUnicode('? à la mode'); // "4pyTIMOgIGxhIG1vZGU="
b64EncodeUnicode('\n'); // "Cg=="
TO DECODE FROM B64 TO UNICODE
function b64DecodeUnicode(str) {
// Going backwards: from bytestream, to percent-encoding, to original string.
return decodeURIComponent(atob(str).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
}
b64DecodeUnicode('4pyTIMOgIGxhIG1vZGU='); // "? à la mode"
b64DecodeUnicode('Cg=='); // "\n"
For any future googlers ending up here like me, I used @tatu Ulmanen's concept and just turned it into an array of objects. This simple function takes a string of pasted excel (or Google sheet) data (preferably from a textarea
) and turns it into an array of objects. It uses the first row for column/property names.
function excelToObjects(stringData){
var objects = [];
//split into rows
var rows = stringData.split('\n');
//Make columns
columns = rows[0].split('\t');
//Note how we start at rowNr = 1, because 0 is the column row
for (var rowNr = 1; rowNr < rows.length; rowNr++) {
var o = {};
var data = rows[rowNr].split('\t');
//Loop through all the data
for (var cellNr = 0; cellNr < data.length; cellNr++) {
o[columns[cellNr]] = data[cellNr];
}
objects.push(o);
}
return objects;
}
Hopefully it helps someone in the future.
Wrap it in a function.
NodeT = namedtuple('Node', 'val left right')
def Node(val, left=None, right=None):
return NodeT(val, left, right)
In Matlab I did something similar using the delaunay
function on the x
, y
coords only (not the z
), then plotting with trimesh
or trisurf
, using z
as the height.
SciPy has the Delaunay class, which is based on the same underlying QHull library that the Matlab's delaunay
function is, so you should get identical results.
From there, it should be a few lines of code to convert this Plotting 3D Polygons in python-matplotlib example into what you wish to achieve, as Delaunay
gives you the specification of each triangular polygon.
Also you can check using Keras backend function:
from keras import backend as K
K.tensorflow_backend._get_available_gpus()
I test this on Keras (2.1.1)
In any web application, there will be a web.xml
in the WEB-INF/
folder.
If you dont have one in your web app, as it seems to be the case in your folder structure, the default Tomcat web.xml
is under TOMCAT_HOME/conf/web.xml
Either way, the relevant lines of the web.xml are
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
so any file matching this pattern when found will be shown as the home page.
In Tomcat, a web.xml setting within your web app will override the default, if present.
Further Reading
Add
<form target="_blank" ...></form>
or
form.setAttribute("target", "_blank");
to your form's definition.
Okay, first intuition is here:
handlers = java.util.logging.FileHandler, java.util.logging.ConsoleHandler
.level = ALL
The Java prop file parser isn't all that smart, I'm not sure it'll handle this. But I'll go look at the docs again....
In the mean time, try:
handlers = java.util.logging.FileHandler
java.util.logging.ConsoleHandler.level = ALL
Update
No, duh, needed more coffee. Nevermind.
While I think more, note that you can use the methods in Properties to load and print a prop-file: it might be worth writing a minimal program to see what java thinks it reads in that file.
Another update
This line:
FileInputStream configFile = new FileInputStream("/path/to/app.properties"));
has an extra end-paren. It won't compile. Make sure you're working with the class file you think you are.
In case someone being a beginner who tried all of the above and still didn't manage to get the project to work. Check your namespace. In an instance where you copy code from one project to another and you forget to change the namespace of the project then it will also give you this error.
Hope it helps someone.
To Get TEXT
attributes added from admin to front end on product listing page.
Thanks Anita Mourya
I have found there is two methods. Let say product attribute called "na_author" is added from backend as text field.
METHOD 1
on list.phtml
<?php $i=0; foreach ($_productCollection as $_product): ?>
FOR EACH PRODUCT LOAD BY SKU AND GET ATTRIBUTE INSIDE FOREACH
<?php
$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$_product->getSku());
$author = $product['na_author'];
?>
<?php
if($author!=""){echo "<br /><span class='home_book_author'>By ".$author ."</span>";} else{echo "";}
?>
METHOD 2
Mage/Catalog/Block/Product/List.phtml
OVER RIDE and set in 'local folder'
i.e. Copy From
Mage/Catalog/Block/Product/List.phtml
and PASTE TO
app/code/local/Mage/Catalog/Block/Product/List.phtml
change the function by adding 2 lines shown in bold below.
protected function _getProductCollection()
{
if (is_null($this->_productCollection)) {
$layer = Mage::getSingleton('catalog/layer');
/* @var $layer Mage_Catalog_Model_Layer */
if ($this->getShowRootCategory()) {
$this->setCategoryId(Mage::app()->getStore()->getRootCategoryId());
}
// if this is a product view page
if (Mage::registry('product')) {
// get collection of categories this product is associated with
$categories = Mage::registry('product')->getCategoryCollection()
->setPage(1, 1)
->load();
// if the product is associated with any category
if ($categories->count()) {
// show products from this category
$this->setCategoryId(current($categories->getIterator()));
}
}
$origCategory = null;
if ($this->getCategoryId()) {
$category = Mage::getModel('catalog/category')->load($this->getCategoryId());
if ($category->getId()) {
$origCategory = $layer->getCurrentCategory();
$layer->setCurrentCategory($category);
}
}
$this->_productCollection = $layer->getProductCollection();
$this->prepareSortableFieldsByCategory($layer->getCurrentCategory());
if ($origCategory) {
$layer->setCurrentCategory($origCategory);
}
}
**//CMI-PK added na_author to filter on product listing page//
$this->_productCollection->addAttributeToSelect('na_author');**
return $this->_productCollection;
}
and you will be happy to see it....!!
It should be a problem in your version of grep.
Your test cases are working correctly here on my machine:
$ echo "abc" | grep -io abc
abc
$ echo "ABC" | grep -io abc
ABC
And my version is:
$ grep --version
grep (GNU grep) 2.10
express
In order to cover all HTTP verbs and all remaining paths you could use:
app.all('*', cb)
Final solution would look like so:
app.all('*', (req, res) =>{
res.status(404).json({
success: false,
data: '404'
})
})
You shouldn't forget to put the router in the end. Because order of routers matter.
If you are using npm you can use the shelljs package
To install: npm install [-g] shelljs
var shell = require('shelljs');
shell.ls('*.js').forEach(function (file) {
// do something
});
See more: https://www.npmjs.com/package/shelljs
Using an element-wise logical or and setting the take_last argument of the pandas duplicated method to both True and False you can obtain a set from your dataframe that includes all of the duplicates.
df_bigdata_duplicates =
df_bigdata[df_bigdata.duplicated(cols='ID', take_last=False) |
df_bigdata.duplicated(cols='ID', take_last=True)
]
To sum it up for vb.net users, the free option (must have office installed):
Microsoft office assembies download:
Add reference to Microsoft.Office.Interop.Word.Application
Add using or import (vb.net) statement to Microsoft.Office.Interop.Word.Application
VB.NET example:
Dim word As Application = New Application()
Dim doc As Document = word.Documents.Open("c:\document.docx")
doc.Activate()
doc.SaveAs2("c:\document.pdf", WdSaveFormat.wdFormatPDF)
doc.Close()
select * from tab1 where (col1,col2) in (select col1,col2 from tab2)
Note:
Oracle ignores rows where one or more of the selected columns is NULL. In these cases you probably want to make use of the NVL-Funktion to map NULL to a special value (that should not be in the values);
select * from tab1
where (col1, NVL(col2, '---') in (select col1, NVL(col2, '---') from tab2)
Of course, never fails. Found the solution about a minute after posting the above question... solution for those that may have had the same issue:
ContextWrapper.getFilesDir()
Found here.
Adding another "Same symptoms, but different solution" response, just in case somebody is having the same problem, but none of the common solutions are working.
In my case, I had an app that started development prior to the instruction of asset catalogs and the flexibility in icon naming conventions, but was first submitted to the store after the transition. To resolve the issue I had to:
If you turn-on 2-Step Verification, you need generate a special app password instead of using your common password. https://myaccount.google.com/security#signin
I had a similar problem to this one. It got solved by deleting the java:comp/env/
prefix and using jdbc/myDataSource
in the context lookup. Just as someone pointed out in the comments.
You could subscribe for the .click event for the links and change the contents of the div using the .html
method:
$('.click').click(function() {
// get the contents of the link that was clicked
var linkText = $(this).text();
// replace the contents of the div with the link text
$('#content-container').html(linkText);
// cancel the default action of the link by returning false
return false;
});
Note however that if you replace the contents of this div the click handler that you have assigned will be destroyed. If you intend to inject some new DOM elements inside the div for which you need to attach event handlers, this attachments should be performed inside the .click handler after inserting the new contents. If the original selector of the event is preserved you may also take a look at the .delegate
method to attach the handler.
There is an implicit call to super()
with no arguments for all classes that have a parent - which is every user defined class in Java - so calling it explicitly is usually not required. However, you may use the call to super()
with arguments if the parent's constructor takes parameters, and you wish to specify them. Moreover, if the parent's constructor takes parameters, and it has no default parameter-less constructor, you will need to call super()
with argument(s).
An example, where the explicit call to super()
gives you some extra control over the title of the frame:
class MyFrame extends JFrame
{
public MyFrame() {
super("My Window Title");
...
}
}
A "sort merge" join is performed by sorting the two data sets to be joined according to the join keys and then merging them together. The merge is very cheap, but the sort can be prohibitively expensive especially if the sort spills to disk. The cost of the sort can be lowered if one of the data sets can be accessed in sorted order via an index, although accessing a high proportion of blocks of a table via an index scan can also be very expensive in comparison to a full table scan.
A hash join is performed by hashing one data set into memory based on join columns and reading the other one and probing the hash table for matches. The hash join is very low cost when the hash table can be held entirely in memory, with the total cost amounting to very little more than the cost of reading the data sets. The cost rises if the hash table has to be spilled to disk in a one-pass sort, and rises considerably for a multipass sort.
(In pre-10g, outer joins from a large to a small table were problematic performance-wise, as the optimiser could not resolve the need to access the smaller table first for a hash join, but the larger table first for an outer join. Consequently hash joins were not available in this situation).
The cost of a hash join can be reduced by partitioning both tables on the join key(s). This allows the optimiser to infer that rows from a partition in one table will only find a match in a particular partition of the other table, and for tables having n partitions the hash join is executed as n independent hash joins. This has the following effects:
You should note that hash joins can only be used for equi-joins, but merge joins are more flexible.
In general, if you are joining large amounts of data in an equi-join then a hash join is going to be a better bet.
This topic is very well covered in the documentation.
http://download.oracle.com/docs/cd/B28359_01/server.111/b28274/optimops.htm#i51523
12.1 docs: https://docs.oracle.com/database/121/TGSQL/tgsql_join.htm
Add a build task to concatenate and register your html partials in the Angular $templateCache
. (This answer is a more detailed variant of karlgold's answer.)
For grunt, use grunt-angular-templates. For gulp, use gulp-angular-templatecache.
Below are config/code snippets to illustrate.
gruntfile.js Example:
ngtemplates: {
app: {
src: ['app/partials/**.html', 'app/views/**.html'],
dest: 'app/scripts/templates.js'
},
options: {
module: 'myModule'
}
}
gulpfile.js Example:
var templateCache = require('gulp-angular-templatecache');
var paths = ['app/partials/.html', 'app/views/.html'];
gulp.task('createTemplateCache', function () {
return gulp.src(paths)
.pipe(templateCache('templates.js', { module: 'myModule', root:'app/views'}))
.pipe(gulp.dest('app/scripts'));
});
templates.js (this file is autogenerated by the build task)
$templateCache.put('app/views/main.html', "<div class=\"main\">\r"...
index.html
<script src="app/scripts/templates.js"></script>
<div ng-include ng-controller="main as vm" src="'app/views/main.html'"></div>
You should look at the documentation for the Action method; it's explained well. For your case, this should work:
@Html.Action("GetOptions", new { pk="00", rk="00" });
The controllerName
parameter will default to the controller from which Html.Action
is being invoked. So if you're trying to invoke an action from another controller, you'll have to specify the controller name like so:
@Html.Action("GetOptions", "ControllerName", new { pk="00", rk="00" });
It works in samsung touchwiz launcher
public static void setBadge(Context context, int count) {
String launcherClassName = getLauncherClassName(context);
if (launcherClassName == null) {
return;
}
Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
intent.putExtra("badge_count", count);
intent.putExtra("badge_count_package_name", context.getPackageName());
intent.putExtra("badge_count_class_name", launcherClassName);
context.sendBroadcast(intent);
}
public static String getLauncherClassName(Context context) {
PackageManager pm = context.getPackageManager();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
for (ResolveInfo resolveInfo : resolveInfos) {
String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
if (pkgName.equalsIgnoreCase(context.getPackageName())) {
String className = resolveInfo.activityInfo.name;
return className;
}
}
return null;
}
Case 1 : Yes, this works fine.
Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.
Share and enjoy.
Thanks @Arnaud & @Conny for highlighting this answer. This really helped me.
I would like to add one more thing here is, adding this line <meta http-equiv="x-ua-compatible" content="IE=edge">
just after the title in tag prior to all meta tags is must for to work as it overrides the compatibility mode of IE.
Atleast it is not mandatory in Java. According to JLS, it says atmost one default case can be present. Which means no default case is acceptable . It at times also depends on the context that you are using the switch statement. For example in Java, the following switch block does not require default case
private static void switch1(String name) {
switch (name) {
case "Monday":
System.out.println("Monday");
break;
case "Tuesday":
System.out.println("Tuesday");
break;
}
}
But in the following method which expects to return a String, default case comes handy to avoid compilation errors
private static String switch2(String name) {
switch (name) {
case "Monday":
System.out.println("Monday");
return name;
case "Tuesday":
System.out.println("Tuesday");
return name;
default:
return name;
}
}
though you can avoid compilation error for the above method without having default case by just having a return statement at the end, but providing default case makes it more readable.
Another table that is useful is:
SELECT * FROM user_objects WHERE object_type='TRIGGER';
You can also use this to query views, indexes etc etc
This is just off the top of my head, but you could do an onClick event for each radio button, give them all different IDs, and then make a for loop in the event to go through each radio button in the group and find which is was checked by looking at the 'checked' attribute. The id of the checked one would be stored as a variable, but you might want to use a temp variable first to make sure that the value of that variable changed, since the click event would fire whether or not a new radio button was checked.
SELECT CREATED FROM USER_OBJECTS WHERE OBJECT_NAME='<<YOUR TABLE NAME>>'
We often want to get more information when there is an exception. The following configuration has two targets, a file and the console, which filter on whether or not there is any exception info. (EDIT: Jarek has posted about a new method of doing this in vNext.)
The key is to have a wrapper target with xsi:type="FilteringWrapper" condition="length('${exception}')>0"
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.mono2.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogLevel="Warn"
internalLogFile="nlog log.log"
>
<variable name="VerboseLayout"
value="${longdate} ${level:upperCase=true} ${message}
(${callsite:includSourcePath=true})" />
<variable name="ExceptionVerboseLayout"
value="${VerboseLayout} (${stacktrace:topFrames=10})
${exception:format=ToString}" />
<targets async="true">
<target name="file" xsi:type="File" fileName="log.log"
layout="${VerboseLayout}">
</target>
<target name="fileAsException"
xsi:type="FilteringWrapper"
condition="length('${exception}')>0">
<target xsi:type="File"
fileName="log.log"
layout="${ExceptionVerboseLayout}" />
</target>
<target xsi:type="ColoredConsole"
name="console"
layout="${NormalLayout}"/>
<target xsi:type="FilteringWrapper"
condition="length('${exception}')>0"
name="consoleException">
<target xsi:type="ColoredConsole"
layout="${ExceptionVerboseLayout}" />
</target>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="console,consoleException" />
<logger name="*" minlevel="Warn" writeTo="file,fileAsException" />
</rules>
</nlog>
With AFNetworking I have successfully consumed https webservice with below code,
NSString *aStrServerUrl = WS_URL;
// Initialize AFHTTPRequestOperationManager...
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
manager.securityPolicy.allowInvalidCertificates = YES;
[manager POST:aStrServerUrl parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
{
successBlock(operation, responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
errorBlock(operation, error);
}];
trim()
{
local trimmed="$1"
# Strip leading space.
trimmed="${trimmed## }"
# Strip trailing space.
trimmed="${trimmed%% }"
echo "$trimmed"
}
For example:
test1="$(trim " one leading")"
test2="$(trim "one trailing ")"
test3="$(trim " one leading and one trailing ")"
echo "'$test1', '$test2', '$test3'"
Output:
'one leading', 'one trailing', 'one leading and one trailing'
trim()
{
local trimmed="$1"
# Strip leading spaces.
while [[ $trimmed == ' '* ]]; do
trimmed="${trimmed## }"
done
# Strip trailing spaces.
while [[ $trimmed == *' ' ]]; do
trimmed="${trimmed%% }"
done
echo "$trimmed"
}
For example:
test4="$(trim " two leading")"
test5="$(trim "two trailing ")"
test6="$(trim " two leading and two trailing ")"
echo "'$test4', '$test5', '$test6'"
Output:
'two leading', 'two trailing', 'two leading and two trailing'
First of all: The difference between i++
and ++i
is neglegible in C.
To the details.
++i
is fasterIn C++, ++i
is more efficient iff i
is some kind of an object with an overloaded increment operator.
Why?
In ++i
, the object is first incremented, and can subsequently passed as a const reference to any other function. This is not possible if the expression is foo(i++)
because now the increment needs to be done before foo()
is called, but the old value needs to be passed to foo()
. Consequently, the compiler is forced to make a copy of i
before it executes the increment operator on the original. The additional constructor/destructor calls are the bad part.
As noted above, this does not apply to fundamental types.
i++
may be fasterIf no constructor/destructor needs to be called, which is always the case in C, ++i
and i++
should be equally fast, right? No. They are virtually equally fast, but there may be small differences, which most other answerers got the wrong way around.
How can i++
be faster?
The point is data dependencies. If the value needs to be loaded from memory, two subsequent operations need to be done with it, incrementing it, and using it. With ++i
, the incrementation needs to be done before the value can be used. With i++
, the use does not depend on the increment, and the CPU may perform the use operation in parallel to the increment operation. The difference is at most one CPU cycle, so it is really neglegible, but it is there. And it is the other way round then many would expect.
how about this:
string fullPath = ofd.FileName;
string fileName = ofd.SafeFileName;
string path = fullPath.Replace(fileName, "");
What can be really convenient:
Find the commit hash you want to squash on top of, say d43e15
.
Now use
git reset d43e15
git commit -am 'new commit name'
You can use:
width: -webkit-fit-content;
height: -webkit-fit-content;
width: -moz-fit-content;
height: -moz-fit-content;
EDIT: No. see http://red-team-design.com/horizontal-centering-using-css-fit-content-value/
Don't really know how they compare for speed, but the first one looks like the right idea for scaling to really big JSON data, since it parses only a small chunk at a time so they don't need to hold all the data in memory at once (This can be faster or slower depending on the library/use case)
To solve CLR20r3 problem set - Local User Policy \ Computer Configuration \ Windows Settings \ Security Settings \ Local Policies \ Security Options - System cryptography
: Use FIPS 140 compliant cryptographic algorithms, including encryption, hashing and signing - Disable
try this method, working fine for me
position: absolute;
left: 50%;
transform: translateX(-50%);
val drawable = ContextCompat.getDrawable(context, R.drawable.my_icon)
// or resources.getDrawable(R.drawable.my_icon, theme)
val sizePx = 25
drawable?.setBounds(0, 0, sizePx, sizePx)
// (left, top, right, bottom)
my_button.setCompoundDrawables(drawable, null, null, null)
I suggest creating an extension function on TextView (Button extends it) for easy reuse.
button.leftDrawable(R.drawable.my_icon, 25)
// Button extends TextView
fun TextView.leftDrawable(@DrawableRes id: Int = 0, @DimenRes sizeRes: Int) {
val drawable = ContextCompat.getDrawable(context, id)
val size = context.resources.getDimensionPixelSize(sizeRes)
drawable?.setBounds(0, 0, size, size)
this.setCompoundDrawables(drawable, null, null, null)
}
I had a column where the first and last name were both were in one column. The first and last name were separated by a comma. The code below worked. There is NO error checking/correction. Just a dumb split. Used phpMyAdmin to execute the SQL statement.
UPDATE tblAuthorList SET AuthorFirst = SUBSTRING_INDEX(AuthorLast,',',-1) , AuthorLast = SUBSTRING_INDEX(AuthorLast,',',1);
Can be pretty easily done assuming you're using jQuery and css3:
HTML:
<div id="clicker">Click Here</div>
<div id="rotating"></div>
CSS:
#clicker {
width: 100px;
height: 100px;
background-color: Green;
}
#rotating {
width: 100px;
height: 100px;
background-color: Red;
margin-top: 50px;
-webkit-transition: all 0.3s ease-in-out;
-moz-transition: all 0.3s ease-in-out;
-o-transition: all 0.3s ease-in-out;
transition: all 0.3s ease-in-out;
}
.rotated {
transform:rotate(25deg);
-webkit-transform:rotate(25deg);
-moz-transform:rotate(25deg);
-o-transform:rotate(25deg);
}
JS:
$(document).ready(function() {
$('#clicker').click(function() {
$('#rotating').toggleClass('rotated');
});
});
You can look at the docs for the SlugField
to get to know more about it in more descriptive way.
It sounds like you currently have 3 copies of the entire file in memory: the byte array, the string, and the array of the lines.
Instead of reading the bytes into a byte array and then converting to characters using new String()
it would be better to use an InputStreamReader, which will convert to characters incrementally, rather than all up-front.
Also, instead of using String.split("\n") to get the individual lines, you should read one line at a time. You can use the readLine()
method in BufferedReader
.
Try something like this:
BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream, "UTF-8"));
try {
while (true) {
String line = reader.readLine();
if (line == null) break;
String[] fields = line.split(",");
// process fields here
}
} finally {
reader.close();
}
Both ItemListener
as well as ActionListener
, in case of JCheckBox
have the same behaviour.
However, major difference is ItemListener
can be triggered by calling the setSelected(true)
on the checkbox.
As a coding practice do not register both ItemListener
as well as ActionListener
with the JCheckBox
, in order to avoid inconsistency.
Hmmm...
As Darin said, you can specify a higher connection timeout value, but I doubt that's really the issue.
When you get connection timeouts, it's typically a problem with one of the following:
Network configuration - slow connection between your web server/dev box and the SQL server. Increasing the timeout may correct this, but it'd be wise to investigate the underlying problem.
Connection string. I've seen issues where an incorrect username/password will, for some reason, give a timeout error instead of a real error indicating "access denied." This shouldn't happen, but such is life.
Connection String 2: If you're specifying the name of the server incorrectly, or incompletely (for instance, mysqlserver
instead of mysqlserver.webdomain.com
), you'll get a timeout. Can you ping the server using the server name exactly as specified in the connection string from the command line?
Connection string 3 : If the server name is in your DNS (or hosts file), but the pointing to an incorrect or inaccessible IP, you'll get a timeout rather than a machine-not-found-ish error.
The query you're calling is timing out. It can look like the connection to the server is the problem, but, depending on how your app is structured, you could be making it all the way to the stage where your query is executing before the timeout occurs.
Connection leaks. How many processes are running? How many open connections? I'm not sure if raw ADO.NET performs connection pooling, automatically closes connections when necessary ala Enterprise Library, or where all that is configured. This is probably a red herring. When working with WCF and web services, though, I've had issues with unclosed connections causing timeouts and other unpredictable behavior.
Things to try:
Do you get a timeout when connecting to the server with SQL Management Studio? If so, network config is likely the problem. If you do not see a problem when connecting with Management Studio, the problem will be in your app, not with the server.
Run SQL Profiler, and see what's actually going across the wire. You should be able to tell if you're really connecting, or if a query is the problem.
Run your query in Management Studio, and see how long it takes.
Good luck!
A super key is any combination of columns that uniquely identifies a row in a table. A candidate key is a super key which cannot have any columns removed from it without losing the unique identification property. This property is sometimes known as minimality or (better) irreducibility.
A super key ? a primary key in general. The primary key is simply a candidate key chosen to be the main key. However, in dependency theory, candidate keys are important and the primary key is not more important than any of the other candidate keys. Non-primary candidate keys are also known as alternative keys.
Consider this table of Elements:
CREATE TABLE elements
(
atomic_number INTEGER NOT NULL PRIMARY KEY
CHECK (atomic_number > 0 AND atomic_number < 120),
symbol CHAR(3) NOT NULL UNIQUE,
name CHAR(20) NOT NULL UNIQUE,
atomic_weight DECIMAL(8,4) NOT NULL,
period SMALLINT NOT NULL
CHECK (period BETWEEN 1 AND 7),
group CHAR(2) NOT NULL
-- 'L' for Lanthanoids, 'A' for Actinoids
CHECK (group IN ('1', '2', 'L', 'A', '3', '4', '5', '6',
'7', '8', '9', '10', '11', '12', '13',
'14', '15', '16', '17', '18')),
stable CHAR(1) DEFAULT 'Y' NOT NULL
CHECK (stable IN ('Y', 'N'))
);
It has three unique identifiers - atomic number, element name, and symbol. Each of these, therefore, is a candidate key. Further, unless you are dealing with a table that can only ever hold one row of data (in which case the empty set (of columns) is a candidate key), you cannot have a smaller-than-one-column candidate key, so the candidate keys are irreducible.
Consider a key made up of { atomic number, element name, symbol }. If you supply a consistent set of values for these three fields (say { 6, Carbon, C }), then you uniquely identify the entry for an element - Carbon. However, this is very much a super key that is not a candidate key because it is not irreducible; you can eliminate any two of the three fields without losing the unique identification property.
As another example, consider a key made up of { atomic number, period, group }. Again, this is a unique identifier for a row; { 6, 2, 14 } identifies Carbon (again). If it were not for the Lanthanoids and Actinoids, then the combination of { period, group } would be unique, but because of them, it is not. However, as before, atomic number on its own is sufficient to uniquely identify an element, so this is a super key and not a candidate key.
onProgressChanged() should be called on every progress changed, not just on first and last touch (that why you have onStartTrackingTouch() and onStopTrackingTouch() methods).
Make sure that your SeekBar have more than 1 value, that is to say your MAX>=3.
In your onCreate:
yourSeekBar=(SeekBar) findViewById(R.id.yourSeekBar);
yourSeekBar.setOnSeekBarChangeListener(new yourListener());
Your listener:
private class yourListener implements SeekBar.OnSeekBarChangeListener {
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// Log the progress
Log.d("DEBUG", "Progress is: "+progress);
//set textView's text
yourTextView.setText(""+progress);
}
public void onStartTrackingTouch(SeekBar seekBar) {}
public void onStopTrackingTouch(SeekBar seekBar) {}
}
Please share some code and the Log results for furter help.
As of Laravel >= 5.3, best way is to use value:
$groupName = \App\User::where('username',$username)->value('groupName');
or
use App\User;//at top of controller
$groupName = User::where('username',$username)->value('groupName');//inside controller function
Of course you have to create a model User for users table which is most efficient way to interact with database tables in Laravel.
You have already executed your query here
$sql = mysql_query("UPDATE anstalld SET mandag = '$mandag', tisdag = '$tisdag', onsdag = '$onsdag', torsdag = '$torsdag', fredag = '$fredag' WHERE namn = '$namn'");
So this line has the problem
$retval = mysql_query( $sql, $conn ); //$sql is not a query its a result set here
Try something like this:
$sql = "UPDATE anstalld SET mandag = '$mandag', tisdag = '$tisdag', onsdag = '$onsdag', torsdag = '$torsdag', fredag = '$fredag' WHERE namn = '$namn'";
$retval = mysql_query( $sql, $conn ); //execute your query
As a sidenote: MySQL_* extension is deprecated use MySQLi_* or PDO instead.
I just tried to make a transparent image with powerpoint after failing miserably with other online systems. I was successful. Amazing.
First I used word art to give me typefaces which convert well to PNG or JPEG. The ordinary text in powerpoint does not convert well. It gets fuzzy. Anyway, I typed in my words in white (my choice of colour as i wanted it against a navy blue background), arranged it how i wanted, then right clicked and selected format shape to remove lines, then shadow to set the transparency.
I took the transparency to 100%. It came out fine. i then right clicked to save as png. Opened the image with MS Picture manager and resized the image to my suiting. It did not come out with the powerpoint white background at all. Once resized, i dropped the image against my navy blue background and it was like magic.
I've used this successfully inside R script:
library("reshape2",lib.loc="/path/to/R-packages/")
useful if for whatever reason libraries are in more than one place.
Please try this one:
function used_to_compare_two_arrays(a, b)
{
// This block will make the array of indexed that array b contains a elements
var c = a.filter(function(value, index, obj) {
return b.indexOf(value) > -1;
});
// This is used for making comparison that both have same length if no condition go wrong
if (c.length !== a.length) {
return 0;
} else{
return 1;
}
}
I had a form with 11 submit buttons on it, and it would always use the first submit button when the user pressed enter. I read elsewhere that it is not a good idea (bad practice) to have more than one submit button on a form, and the best way to do this is have the button you want as default, as the only submit button on the form. The other buttons should be made into "TYPE=BUTTON" and an onClick event added that calls your own submit routine in Javascript. Something like this :-
<SCRIPT Language="JavaScript">
function validform()
{
// do whatever you need to validate the form, and return true or false accordingly
}
function mjsubmit()
{
if (validform()) { document.form1.submit(); return true;}
return false;
}
</SCRIPT>
<INPUT TYPE=BUTTON NAME="button1" VALUE="button1" onClick="document.form1.submitvalue='button1'; return mjsubmit();">
<INPUT TYPE=BUTTON NAME="button2" VALUE="button2" onClick="document.form1.submitvalue='button2'; return mjsubmit();">
<INPUT TYPE=SUBMIT NAME="button3" VALUE="button3" onClick="document.form1.submitvalue='button3'; return validform();">
<INPUT TYPE=BUTTON NAME="button4" VALUE="button4" onClick="document.form1.submitvalue='button4'; return mjsubmit();">
Here, button3 is the default, and although you are programmatically submitting the form with the other buttons, the mjsubmit routine validates them. HTH.
var jsonIssues = [
{ID:'1',Name:'Some name',Notes:'NOTES'},
{ID:'2',Name:'Some name 2',Notes:'NOTES 2'}
];
If you want to add to the array then you can do this
jsonIssues[jsonIssues.length] = {ID:'3',Name:'Some name 3',Notes:'NOTES 3'};
Or you can use the push technique that the other guy posted, which is also good.
Your method is right, all you have to do is add a .0 after both the tens and it will fix your problem!
double example = Math.round((187/35) * 10.0) / 10.0;
The output would be:
5.3
If you want for some reason to convert your file to base-64 string. Like if you want to pass it via internet, etc... you can do this
Byte[] bytes = File.ReadAllBytes("path");
String file = Convert.ToBase64String(bytes);
And correspondingly, read back to file:
Byte[] bytes = Convert.FromBase64String(b64Str);
File.WriteAllBytes(path, bytes);
<?php
function current_url()
{
$url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$validURL = str_replace("&", "&", $url);
return $validURL;
}
//echo "page URL is : ".current_url();
$offer_url = current_url();
?>
<?php
if ($offer_url == "checking url name") {
?> <p> hi this is manip5595 </p>
<?php
}
?>
mydata$sCode
is a vector, it's why nrow output is NULL.mydata[mydata$sCode == 'CA',]
returns data.frame
where sCode == 'CA'
. sCode includes character. That's why sum
gives you the error.subset(mydata, sCode='CA', select=c(sCode))
, you should use sCode=='CA'
instead sCode='CA'
. Then subset returns you vector where sCode equals CA, so you should use
length(subset(na.omit(mydata), sCode='CA', select=c(sCode)))
Or you can try this: sum(na.omit(mydata$sCode) == "CA")
The default value for the type
attribute of button
elements is "submit". Set it to type="button"
to produce a button that doesn't submit the form.
<button type="button">Submit</button>
In the words of the HTML Standard: "Does nothing."
Check something with echo
, print()
or printr()
in the include file, header.php
.
It might be that this is the problem OR if any MVC file, then check the number of spaces after ?>
. This could also make a problem.
Use entrySet
,
/**
*Output:
D: 99.22
A: 3434.34
C: 1378.0
B: 123.22
E: -19.08
B's new balance: 1123.22
*/
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MainClass {
public static void main(String args[]) {
HashMap<String, Double> hm = new HashMap<String, Double>();
hm.put("A", new Double(3434.34));
hm.put("B", new Double(123.22));
hm.put("C", new Double(1378.00));
hm.put("D", new Double(99.22));
hm.put("E", new Double(-19.08));
Set<Map.Entry<String, Double>> set = hm.entrySet();
for (Map.Entry<String, Double> me : set) {
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
double balance = hm.get("B");
hm.put("B", balance + 1000);
System.out.println("B's new balance: " + hm.get("B"));
}
}
see complete example here:
Also, don't forget the === operator when you're working with numbers that could mean null or 0 or return some form of false or null that isn't what you're looking for.
Addition to the above answer by @djechlin
d = '1394104654000';
new Date(parseInt(d));
converts EPOCH time to human readable date. Just don't forget that type of EPOCH time must be an Integer.
I have modified @rahul kumars answer, so that it uses Observables instead:
import { Injectable } from "@angular/core";
import { Observable } from "rxjs/Observable";
import { Observer } from "rxjs/Observer";
@Injectable()
export class ScriptLoaderService {
private scripts: ScriptModel[] = [];
public load(script: ScriptModel): Observable<ScriptModel> {
return new Observable<ScriptModel>((observer: Observer<ScriptModel>) => {
var existingScript = this.scripts.find(s => s.name == script.name);
// Complete if already loaded
if (existingScript && existingScript.loaded) {
observer.next(existingScript);
observer.complete();
}
else {
// Add the script
this.scripts = [...this.scripts, script];
// Load the script
let scriptElement = document.createElement("script");
scriptElement.type = "text/javascript";
scriptElement.src = script.src;
scriptElement.onload = () => {
script.loaded = true;
observer.next(script);
observer.complete();
};
scriptElement.onerror = (error: any) => {
observer.error("Couldn't load script " + script.src);
};
document.getElementsByTagName('body')[0].appendChild(scriptElement);
}
});
}
}
export interface ScriptModel {
name: string,
src: string,
loaded: boolean
}
First you should try with Proguard (This clean all code unused)
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
minSdkVersion 16
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
strace -tfp PID will monitor the PID process's system calls, thus we can debug/monitor our process/program status.
Actually, there's more than one issue here. The main one is that xargs
by default executes the command you specified, even when no arguments have been passed. To change that you might use a GNU extension to xargs
:
--no-run-if-empty
-r
If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension.
Simple example:
find . -mmin -60 | xargs -r ls -l
But this might match to all subdirectories, including .
(the current directory), and ls
will list each of them individually. So the output will be a mess. Solution: pass -d
to ls
, which prohibits listing the directory contents:
find . -mmin -60 | xargs -r ls -ld
Now you don't like .
(the current directory) in your list? Solution: exclude the first directory level (0
) from find output:
find . -mindepth 1 -mmin -60 | xargs -r ls -ld
Now you'd need only the files in your list? Solution: exclude the directories:
find . -type f -mmin -60 | xargs -r ls -l
Now you have some files with names containing white space, quote marks, or backslashes? Solution: use null-terminated output (find) and input (xargs) (these are also GNU extensions, afaik):
find . -type f -mmin -60 -print0 | xargs -r0 ls -l
For complete the accepted answer, Had the same issue. First specified the remote
git remote add origin https://github.com/XXXX/YYY.git
git fetch
Then get the code
git pull origin master
you can do something like this:
DataTable dt = new DataTable();
for (int i = 0; i < GridView1.Columns.Count; i++)
{
dt.Columns.Add("column"+i.ToString());
}
foreach (GridViewRow row in GridView1.Rows)
{
DataRow dr = dt.NewRow();
for(int j = 0;j<GridView1.Columns.Count;j++)
{
dr["column" + j.ToString()] = row.Cells[j].Text;
}
dt.Rows.Add(dr);
}
And that will show that it works.
GridView6.DataSource = dt;
GridView6.DataBind();
Oracle Setup:
CREATE OR REPLACE FUNCTION split_String(
i_str IN VARCHAR2,
i_delim IN VARCHAR2 DEFAULT ','
) RETURN SYS.ODCIVARCHAR2LIST DETERMINISTIC
AS
p_result SYS.ODCIVARCHAR2LIST := SYS.ODCIVARCHAR2LIST();
p_start NUMBER(5) := 1;
p_end NUMBER(5);
c_len CONSTANT NUMBER(5) := LENGTH( i_str );
c_ld CONSTANT NUMBER(5) := LENGTH( i_delim );
BEGIN
IF c_len > 0 THEN
p_end := INSTR( i_str, i_delim, p_start );
WHILE p_end > 0 LOOP
p_result.EXTEND;
p_result( p_result.COUNT ) := SUBSTR( i_str, p_start, p_end - p_start );
p_start := p_end + c_ld;
p_end := INSTR( i_str, i_delim, p_start );
END LOOP;
IF p_start <= c_len + 1 THEN
p_result.EXTEND;
p_result( p_result.COUNT ) := SUBSTR( i_str, p_start, c_len - p_start + 1 );
END IF;
END IF;
RETURN p_result;
END;
/
Query
SELECT ROWNUM AS ID,
COLUMN_VALUE AS Data
FROM TABLE( split_String( 'A,B,C,D' ) );
Output:
ID DATA
-- ----
1 A
2 B
3 C
4 D
user:Array[]=[1,2,3];
if(this.user.length)
{
console.log("user has contents");
}
else{
console.log("user is empty");
}
Created an overall rehauled and fail-safe implementation from all comments and suggestions:
# collect stats about the dir
- name: check directory exists
stat:
path: '{{ directory_path }}'
register: dir_to_delete
# delete directory if condition is true
- name: purge {{directory_path}}
file:
state: absent
path: '{{ directory_path }}'
when: dir_to_delete.stat.exists and dir_to_delete.stat.isdir
# create directory if deleted (or if it didn't exist at all)
- name: create directory again
file:
state: directory
path: '{{ directory_path }}'
when: dir_to_delete is defined or dir_to_delete.stat.exist == False
Your problem is most likely with the video file, not the code. Your video is most likely not "safe for streaming". See where to place videos to stream android for more.
Also, this could make it works:
@{
Html.RenderPartial("your view", your_model, ViewData);
}
or
@{
Html.RenderPartial("your view", your_model);
}
For more information on RenderPartial and similar HTML helpers in MVC see this popular StackOverflow thread
Using java.io.File
:
File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) {
// do something
}
A rect
can't contain a text
element. Instead transform a g
element with the location of text and rectangle, then append both the rectangle and the text to it:
var bar = chart.selectAll("g")
.data(data)
.enter().append("g")
.attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });
bar.append("rect")
.attr("width", x)
.attr("height", barHeight - 1);
bar.append("text")
.attr("x", function(d) { return x(d) - 3; })
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.text(function(d) { return d; });
http://bl.ocks.org/mbostock/7341714
Multi-line labels are also a little tricky, you might want to check out this wrap function.
That depends on a lot of factors. Processes are more heavy-weight than threads, and have a higher startup and shutdown cost. Interprocess communication (IPC) is also harder and slower than interthread communication.
Conversely, processes are safer and more secure than threads, because each process runs in its own virtual address space. If one process crashes or has a buffer overrun, it does not affect any other process at all, whereas if a thread crashes, it takes down all of the other threads in the process, and if a thread has a buffer overrun, it opens up a security hole in all of the threads.
So, if your application's modules can run mostly independently with little communication, you should probably use processes if you can afford the startup and shutdown costs. The performance hit of IPC will be minimal, and you'll be slightly safer against bugs and security holes. If you need every bit of performance you can get or have a lot of shared data (such as complex data structures), go with threads.
Solution for me (Android Studio) :
1) Use shortcut Ctrl+Shift+Alt+S or File -> Project Structure
2) and increase the level of SDK "Compile SDK Version".
Why not to use Static Initialization Blocks
? Additional details here:
Static Initialization Blocks
I don't know about elegant, but it's certainly doable:
oldlist = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]]
# change into: list = [["A", "C"], ["B"], ["D", "E"]]
order=[]
dic=dict()
for value,key in oldlist:
try:
dic[key].append(value)
except KeyError:
order.append(key)
dic[key]=[value]
newlist=map(dic.get, order)
print newlist
This preserves the order of the first occurence of each key, as well as the order of items for each key. It requires the key to be hashable, but does not otherwise assign meaning to it.
I have an utility method to switch to the required window as shown below
public class Utility
{
public static WebDriver getHandleToWindow(String title){
//parentWindowHandle = WebDriverInitialize.getDriver().getWindowHandle(); // save the current window handle.
WebDriver popup = null;
Set<String> windowIterator = WebDriverInitialize.getDriver().getWindowHandles();
System.err.println("No of windows : " + windowIterator.size());
for (String s : windowIterator) {
String windowHandle = s;
popup = WebDriverInitialize.getDriver().switchTo().window(windowHandle);
System.out.println("Window Title : " + popup.getTitle());
System.out.println("Window Url : " + popup.getCurrentUrl());
if (popup.getTitle().equals(title) ){
System.out.println("Selected Window Title : " + popup.getTitle());
return popup;
}
}
System.out.println("Window Title :" + popup.getTitle());
System.out.println();
return popup;
}
}
It will take you to desired window once title of the window is passed as parameter. In your case you can do.
Webdriver childDriver = Utility.getHandleToWindow("titleOfChildWindow");
and then again switch to parent window using the same method
Webdriver parentDriver = Utility.getHandleToWindow("titleOfParentWindow");
This method works effectively when dealing with multiple windows.
echo test > afile.txt
redirects stdout to afile.txt
. This is the same as doing
echo test 1> afile.txt
To redirect stderr, you do:
echo test 2> afile.txt
>&
is the syntax to redirect a stream to another file descriptor - 0 is stdin, 1 is stdout, and 2 is stderr.
You can redirect stdout to stderr by doing:
echo test 1>&2 # or echo test >&2
Or vice versa:
echo test 2>&1
So, in short... 2>
redirects stderr to an (unspecified) file, appending &1
redirects stderr to stdout.
if ujava's solution can't help you,you can try to use try/catch to catch this fatal,this works fine on me.
try{
$res = $client->__call('LineStopQueryJson',array('Parameters' => $params));
}catch(SoapFault $e){
print_r($client);
}
I was trying to do this but having problems with Kjetil Watnedal's solution because I don't use the inline linq syntax - I prefer method-style syntax. My specific problem was in trying to do dynamic sorting using a custom IComparer
.
My solution ended up like this:
Given an IQueryable query like so:
List<DATA__Security__Team> teams = TeamManager.GetTeams();
var query = teams.Where(team => team.ID < 10).AsQueryable();
And given a run-time sort field argument:
string SortField; // Set at run-time to "Name"
The dynamic OrderBy looks like so:
query = query.OrderBy(item => item.GetReflectedPropertyValue(SortField));
And that's using a little helper method called GetReflectedPropertyValue():
public static string GetReflectedPropertyValue(this object subject, string field)
{
object reflectedValue = subject.GetType().GetProperty(field).GetValue(subject, null);
return reflectedValue != null ? reflectedValue.ToString() : "";
}
One last thing - I mentioned that I wanted the OrderBy
to use custom IComparer
- because I wanted to do Natural sorting.
To do that, I just alter the OrderBy
to:
query = query.OrderBy(item => item.GetReflectedPropertyValue(SortField), new NaturalSortComparer<string>());
See this post for the code for NaturalSortComparer()
.
Easiest solution to force UTF-8 encoding in Spring MVC returning String:
In @RequestMapping
, use:
produces = MediaType.APPLICATION_JSON_VALUE + "; charset=utf-8"
Use this inside of query, no need to create extra variables.
CASE WHEN CreatedDate = '19000101' THEN '' WHEN CreatedDate =
'18000101' THEN '' ELSE CONVERT(CHAR(10), CreatedDate, 120) + ' ' +
CONVERT(CHAR(8), CreatedDate, 108) END as 'Created Date'
Works like a charm.
Hera's the function UpdateWindowsList_WindowMenu() that you must call after any operations are performed on Tabs.Here windowToolStripMenuItem is the menu item added to Window Menu to menu strip.
public void UpdateWindowsList_WindowMenu()
{
//get all tab pages from tabControl1
TabControl.TabPageCollection tabcoll = tabControl1.TabPages;
//get windowToolStripMenuItem drop down menu items count
int n = windowToolStripMenuItem.DropDownItems.Count;
//remove all menu items from of windowToolStripMenuItem
for (int i = n - 1; i >=2; i--)
{
windowToolStripMenuItem.DropDownItems.RemoveAt(i);
}
//read each tabpage from tabcoll and add each tabpage text to windowToolStripMenuItem
foreach (TabPage tabpage in tabcoll)
{
//create Toolstripmenuitem
ToolStripMenuItem menuitem = new ToolStripMenuItem();
String s = tabpage.Text;
menuitem.Text = s;
if (tabControl1.SelectedTab == tabpage)
{
menuitem.Checked = true;
}
else
{
menuitem.Checked = false;
}
//add menuitem to windowToolStripMenuItem
windowToolStripMenuItem.DropDownItems.Add(menuitem);
//add click events to each added menuitem
menuitem.Click += new System.EventHandler(WindowListEvent_Click);
}
}
private void WindowListEvent_Click(object sender, EventArgs e)
{
//casting ToolStripMenuItem to ToolStripItem
ToolStripItem toolstripitem = (ToolStripItem)sender;
//create collection of tabs of tabContro1
//check every tab text is equal to clicked menuitem then select the tab
TabControl.TabPageCollection tabcoll = tabControl1.TabPages;
foreach (TabPage tb in tabcoll)
{
if (toolstripitem.Text == tb.Text)
{
tabControl1.SelectedTab = tb;
//call UpdateWindowsList_WindowMenu() to perform changes on menuitems
UpdateWindowsList_WindowMenu();
}
}
}
In later versions of Angular2 there is no need of manually setting Content-Type
header and encoding the body if you pass an object of the right type as body
.
You simply can do this
import { URLSearchParams } from "@angular/http"
testRequest() {
let data = new URLSearchParams();
data.append('username', username);
data.append('password', password);
this.http
.post('/api', data)
.subscribe(data => {
alert('ok');
}, error => {
console.log(error.json());
});
}
This way angular will encode the body for you and will set the correct Content-Type
header.
P.S. Do not forget to import URLSearchParams
from @angular/http
or it will not work.
Clustered Index
Clustered indexes sort and store the data rows in the table or view based on their key values. These are the columns included in the index definition. There can be only one clustered index per table, because the data rows themselves can be sorted in only one order.
The only time the data rows in a table are stored in sorted order is when the table contains a clustered index. When a table has a clustered index, the table is called a clustered table. If a table has no clustered index, its data rows are stored in an unordered structure called a heap.
Nonclustered
Nonclustered indexes have a structure separate from the data rows. A nonclustered index contains the nonclustered index key values and each key value entry has a pointer to the data row that contains the key value. The pointer from an index row in a nonclustered index to a data row is called a row locator. The structure of the row locator depends on whether the data pages are stored in a heap or a clustered table. For a heap, a row locator is a pointer to the row. For a clustered table, the row locator is the clustered index key.
You can add nonkey columns to the leaf level of the nonclustered index to by-pass existing index key limits, and execute fully covered, indexed, queries. For more information, see Create Indexes with Included Columns. For details about index key limits see Maximum Capacity Specifications for SQL Server.
Code Example : Reading data from DataGridView and storing it in an array
int[,] n = new int[3, 19];
for (int i = 0; i < (StartDataView.Rows.Count - 1); i++)
{
for (int j = 0; j < StartDataView.Columns.Count; j++)
{
if(this.StartDataView.Rows[i].Cells[j].Value.ToString() != string.Empty)
{
try
{
n[i, j] = int.Parse(this.StartDataView.Rows[i].Cells[j].Value.ToString());
}
catch (Exception Ee)
{ //get exception of "null"
MessageBox.Show(Ee.ToString());
}
}
}
}
Something like:
var min = dates.reduce(function (a, b) { return a < b ? a : b; });
var max = dates.reduce(function (a, b) { return a > b ? a : b; });
Tested on Chrome 15.0.854.0 dev
please, something went xxx*x, and that's not true at all, check that
JButton Size - java.awt.Dimension[width=400,height=40]
JPanel Size - java.awt.Dimension[width=640,height=480]
JFrame Size - java.awt.Dimension[width=646,height=505]
code (basic stuff from Trail: Creating a GUI With JFC/Swing , and yet I still satisfied that that would be outdated )
EDIT: forget setDefaultCloseOperation()
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class FrameSize {
private JFrame frm = new JFrame();
private JPanel pnl = new JPanel();
private JButton btn = new JButton("Get ScreenSize for JComponents");
public FrameSize() {
btn.setPreferredSize(new Dimension(400, 40));
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("JButton Size - " + btn.getSize());
System.out.println("JPanel Size - " + pnl.getSize());
System.out.println("JFrame Size - " + frm.getSize());
}
});
pnl.setPreferredSize(new Dimension(640, 480));
pnl.add(btn, BorderLayout.SOUTH);
frm.add(pnl, BorderLayout.CENTER);
frm.setLocation(150, 100);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // EDIT
frm.setResizable(false);
frm.pack();
frm.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
FrameSize fS = new FrameSize();
}
});
}
}
There are 2 main kinds of transactions; connection transactions and ambient transactions. A connection transaction (such as SqlTransaction) is tied directly to the db connection (such as SqlConnection), which means that you have to keep passing the connection around - OK in some cases, but doesn't allow "create/use/release" usage, and doesn't allow cross-db work. An example (formatted for space):
using (IDbTransaction tran = conn.BeginTransaction()) {
try {
// your code
tran.Commit();
} catch {
tran.Rollback();
throw;
}
}
Not too messy, but limited to our connection "conn". If we want to call out to different methods, we now need to pass "conn" around.
The alternative is an ambient transaction; new in .NET 2.0, the TransactionScope object (System.Transactions.dll) allows use over a range of operations (suitable providers will automatically enlist in the ambient transaction). This makes it easy to retro-fit into existing (non-transactional) code, and to talk to multiple providers (although DTC will get involved if you talk to more than one).
For example:
using(TransactionScope tran = new TransactionScope()) {
CallAMethodThatDoesSomeWork();
CallAMethodThatDoesSomeMoreWork();
tran.Complete();
}
Note here that the two methods can handle their own connections (open/use/close/dispose), yet they will silently become part of the ambient transaction without us having to pass anything in.
If your code errors, Dispose() will be called without Complete(), so it will be rolled back. The expected nesting etc is supported, although you can't roll-back an inner transaction yet complete the outer transaction: if anybody is unhappy, the transaction is aborted.
The other advantage of TransactionScope is that it isn't tied just to databases; any transaction-aware provider can use it. WCF, for example. Or there are even some TransactionScope-compatible object models around (i.e. .NET classes with rollback capability - perhaps easier than a memento, although I've never used this approach myself).
All in all, a very, very useful object.
Some caveats:
My suggestion is to run
openssl enc -aes-256-cbc -in plain.txt -out encrypted.bin
under debugger and see what exactly what it is doing. openssl.c is the only real tutorial/getting started/reference guide OpenSSL has. All other documentation is just an API reference.
U1: My guess is that you are not setting some other required options, like mode of operation (padding).
U2: this is probably a duplicate of this question: AES CTR 256 Encryption Mode of operation on OpenSSL and answers there will likely help.
in fact there is a subtelty with the c()
function. If you do:
x <- list()
x <- c(x,2)
x = c(x,"foo")
you will obtain as expected:
[[1]]
[1]
[[2]]
[1] "foo"
but if you add a matrix with x <- c(x, matrix(5,2,2)
, your list will have another 4 elements of value 5
!
You would better do:
x <- c(x, list(matrix(5,2,2))
It works for any other object and you will obtain as expected:
[[1]]
[1]
[[2]]
[1] "foo"
[[3]]
[,1] [,2]
[1,] 5 5
[2,] 5 5
Finally, your function becomes:
push <- function(l, ...) c(l, list(...))
and it works for any type of object. You can be smarter and do:
push_back <- function(l, ...) c(l, list(...))
push_front <- function(l, ...) c(list(...), l)
In case that might help, I found a workaround for a similar problem, looking at the cmake doc : https://cmake.org/cmake/help/v3.0/module/FindPythonLibs.html
You must set two env vars for cmake to find coherent versions. Unfortunately this is not a generic solution...
cmake -DPYTHON_LIBRARY=${HOME}/.pyenv/versions/3.8.0/lib/libpython3.8.a -DPYTHON_INCLUDE_DIR=${HOME}/.pyenv/versions/3.8.0/include/python3.8/ cern_root/
jPDFImages is not free but a commercial library which converts PDF pages to images in JPEG, TIFF or PNG format. The output image size is customizable.
This one works for me:
<?php
if(isset($_GET['action']))
{
//your code
echo 'Welcome';
}
?>
<form id="frm" method="post" action="?action" >
<input type="submit" value="Submit" id="submit" />
</form>
This link can be helpful:
Performance wise StringBuffer is much better than String ; because whenever you apply concatenation on String Object then new String object are created on each concatenation.
Principal Rule : String are immutable(Non Modifiable) and StringBuffer are mutable(Modifiable)
Here is the programmatic experiment where you get the performance difference
public class Test {
public static int LOOP_ITERATION= 100000;
public static void stringTest(){
long startTime = System.currentTimeMillis();
String string = "This";
for(int i=0;i<LOOP_ITERATION;i++){
string = string+"Yasir";
}
long endTime = System.currentTimeMillis();
System.out.println(endTime - startTime);
}
public static void stringBufferTest(){
long startTime = System.currentTimeMillis();
StringBuffer stringBuffer = new StringBuffer("This");
for(int i=0;i<LOOP_ITERATION;i++){
stringBuffer.append("Yasir");
}
long endTime = System.currentTimeMillis();
System.out.println(endTime - startTime);
}
public static void main(String []args){
stringTest()
stringBufferTest();
}
}
Output of String are in my machine 14800
Output of StringBuffer are in my machine 14
I know I'm replying to an old question, but I just went through this same exercise and found out a bit more information, that I think will contribute a lot to the discussion and help out anyone else who finds this question and sees where the existing answers fall short.
The accepted answer is close, and can be corrected using Nedko's comment to it. A more detailed understanding of the WMI Classes involved helps complete the picture.
Win32_USBHub
returns only USB Hubs. That seems obvious in hindsight but the discussion above misses it. It does not include all possible USB devices, only those which can (in theory, at least) act as a hub for additional devices. It misses some devices that are not hubs (particularly parts of composite devices).
Win32_PnPEntity
does include all the USB devices, and hundreds more non-USB devices. Russel Gantman's advice to use a WHERE clause search Win32_PnPEntity
for a DeviceID beginning with "USB%" to filter the list is helpful but slightly incomplete; it misses bluetooth devices, some printers/print servers, and HID-compliant mice and keyboards. I have seen "USB\%", "USBSTOR\%", "USBPRINT\%", "BTH\%", "SWD\%", and "HID\%". Win32_PnPEntity
is, however, a good "master" reference to look up information once you are in possession of the PNPDeviceID from other sources.
What I found was the best way to enumerate USB devices was to query Win32_USBControllerDevice
. While it doesn't give detailed information for the devices, it does completely enumerate your USB devices and gives you an Antecedent/Dependent pair of PNPDeviceID
s for every USB Device (including Hubs, non-Hub devices, and HID-compliant devices) on your system. Each Dependent returned from the query will be a USB Device. The Antecedent will be the Controller it is assigned to, one of the USB Controllers returned by querying Win32_USBController
.
As a bonus, it appears that under the hood, WMI walks the Device Tree when responding to the Win32_USBControllerDevice
query, so the order in which these results are returned can help identify parent/child relationships. (This is not documented and is thus only a guess; use the SetupDi API's CM_Get_Parent (or Child + Sibling) for definitive results.) As an option to the SetupDi API, it appears that for all the devices listed under Win32_USBHub
they can be looked up in the registry (at HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\ + PNPDeviceID
) and will have a parameter ParentIdPrefix
which will be the prefix of the last field in the PNPDeviceID of its children, so this could also be used in a wildcard match to filter the Win32_PnPEntity
query.
In my application, I did the following:
Win32_PnPEntity
and stored the results in a key-value map (with PNPDeviceID as the key) for later retrieval. This is optional if you want to do individual queries later.Win32_USBControllerDevice
for a definitive list of USB devices on my system (all the Dependents) and extracted the PNPDeviceIDs of these. I went further, based on order following the device tree, to assign devices to the root hub (the first device returned, rather than the controller) and built a tree based on the parentIdPrefix. The order the query returns, which matches device tree enumeration via SetupDi, is each root hub (for whom the Antecedent identifies the controller), followed by an iteration of devices under it, e.g., on my system:
Win32_USBController
. This gave me the detailed information of the PNPDeviceIDs of my controllers which are at the top of the device tree (which were the Antecedents of the previous query). Using the tree derived in the previous step, recursively iterated over its children (the root hubs) and their children (the other hubs) and their children (non-hub devices and composite devices) and their children, etc.
Win32_PnPEntity
individually using the PNPDeviceId to get the information at this step; probably a cpu vs. memory tradeoff determining which order is better.)In summary, Win32USBControllerDevice
Dependents are a complete list of USB Devices on a system (other than the Controllers themselves, which are the Antecedents in that same query), and by cross-referencing these PNPDeviceId
pairs with information from the registry and from the other queries mentioned, a detailed picture can be constructed.
You can do it as simple as this using swift 2:
let alertController = UIAlertController(title: "iOScreator", message:
"Hello, world!", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Destructive,handler: { action in
self.pressed()
}))
func pressed()
{
print("you pressed")
}
**or**
let alertController = UIAlertController(title: "iOScreator", message:
"Hello, world!", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Destructive,handler: { action in
print("pressed")
}))
All the answers above are correct i am just showing another way that can be done.
By including:
#include <byteswap.h>
you can get an optimized version of machine-dependent byte-swapping functions. Then, you can easily use the following functions:
__bswap_32 (uint32_t input)
or
__bswap_16 (uint16_t input)
Here's a performance comparison of the two. HTTP is more responsive for request-response of small files, but FTP may be better for large files if tuned properly. FTP used to be generally considered faster. FTP requires a control channel and state be maintained besides the TCP state but HTTP does not. There are 6 packet transfers before data starts transferring in FTP but only 4 in HTTP.
I think a properly tuned TCP layer would have more effect on speed than the difference between application layer protocols. The Sun Blueprint Understanding Tuning TCP has details.
Heres another good comparison of individual characteristics of each protocol.
I had been having the exact same problem!
To get the internal SD card you can use
String extStore = System.getenv("EXTERNAL_STORAGE");
File f_exts = new File(extStore);
To get the external SD card you can use
String secStore = System.getenv("SECONDARY_STORAGE");
File f_secs = new File(secStore);
On running the code
extStore = "/storage/emulated/legacy"
secStore = "/storage/extSdCarcd"
works perfectly!
grep
is made for this.
Use grep myword *
And check man grep
.
Do this:
if (denominator == 0) throw new ArithmeticException("denominator == 0");
ArithmeticException is the exception which is normally thrown when you divide by 0.
It worked: Project Properties -> ProjectFacets -> Runtimes -> jdk1.8.0_45 -> Apply
It can be done via https and oauth or ssh.
https and oauth: create an access token that has "repo" scope and then use this syntax:
"package-name": "git+https://<github_token>:[email protected]/<user>/<repo>.git"
or
ssh: setup ssh and then use this syntax:
"package-name": "git+ssh://[email protected]:<user>/<repo>.git"
(note the use of colon instead of slash before user)
You are missing JUnit 5 platform launcher with group: 'org.junit.platform', name: 'junit-platform-launcher'
Just add in ur POM:
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
</dependency>
If you have to use java.util.Calendar
, I suspect you want:
int days = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
Personally, however, I'd suggest using Joda Time instead of java.util.{Calendar, Date}
to start with, in which case you could use:
int days = chronology.dayOfMonth().getMaximumValue(date);
Note that rather than parsing the string values individually, it would be better to get whichever date/time API you're using to parse it. In java.util.*
you might use SimpleDateFormat
; in Joda Time you'd use a DateTimeFormatter
.
I was also stuck by this problem.But in my case I delete all .png
images from drawable
folder ,clean and rebuild
application and then paste all .png
images to my drawable
, rebuild again. It worked fine for me.
The default password for Mariadb is blank.
$ mysql -u root -p
Enter Password: <--- press enter
The Run/Debug configuration you're using is meant to let you run Maven on your workspace as if from the command line without leaving Eclipse.
Assuming your tests are JUnit based you should be able to debug them by choosing a source folder containing tests with the right button and choose Debug as...
-> JUnit tests
.
The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.
When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.
Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:
http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database
Update Collation of all fields in database on the fly
http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx
If you need to have different collation on two objects or can't change collations - you can still JOIN
between them using COLLATE
command, and choosing the collation you want for join.
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS
or using default database collation:
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT
public static void ExportToExcel(DataGridView dgView)
{
Microsoft.Office.Interop.Excel.Application excelApp = null;
try
{
// instantiating the excel application class
excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook currentWorkbook = excelApp.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel.Worksheet currentWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)currentWorkbook.ActiveSheet;
currentWorksheet.Columns.ColumnWidth = 18;
if (dgView.Rows.Count > 0)
{
currentWorksheet.Cells[1, 1] = DateTime.Now.ToString("s");
int i = 1;
foreach (DataGridViewColumn dgviewColumn in dgView.Columns)
{
// Excel work sheet indexing starts with 1
currentWorksheet.Cells[2, i] = dgviewColumn.Name;
++i;
}
Microsoft.Office.Interop.Excel.Range headerColumnRange = currentWorksheet.get_Range("A2", "G2");
headerColumnRange.Font.Bold = true;
headerColumnRange.Font.Color = 0xFF0000;
//headerColumnRange.EntireColumn.AutoFit();
int rowIndex = 0;
for (rowIndex = 0; rowIndex < dgView.Rows.Count; rowIndex++)
{
DataGridViewRow dgRow = dgView.Rows[rowIndex];
for (int cellIndex = 0; cellIndex < dgRow.Cells.Count; cellIndex++)
{
currentWorksheet.Cells[rowIndex + 3, cellIndex + 1] = dgRow.Cells[cellIndex].Value;
}
}
Microsoft.Office.Interop.Excel.Range fullTextRange = currentWorksheet.get_Range("A1", "G" + (rowIndex + 1).ToString());
fullTextRange.WrapText = true;
fullTextRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
}
else
{
string timeStamp = DateTime.Now.ToString("s");
timeStamp = timeStamp.Replace(':', '-');
timeStamp = timeStamp.Replace("T", "__");
currentWorksheet.Cells[1, 1] = timeStamp;
currentWorksheet.Cells[1, 2] = "No error occured";
}
using (SaveFileDialog exportSaveFileDialog = new SaveFileDialog())
{
exportSaveFileDialog.Title = "Select Excel File";
exportSaveFileDialog.Filter = "Microsoft Office Excel Workbook(*.xlsx)|*.xlsx";
if (DialogResult.OK == exportSaveFileDialog.ShowDialog())
{
string fullFileName = exportSaveFileDialog.FileName;
// currentWorkbook.SaveCopyAs(fullFileName);
// indicating that we already saved the workbook, otherwise call to Quit() will pop up
// the save file dialogue box
currentWorkbook.SaveAs(fullFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, System.Reflection.Missing.Value, Missing.Value, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution, true, Missing.Value, Missing.Value, Missing.Value);
currentWorkbook.Saved = true;
MessageBox.Show("Error memory exported successfully", "Exported to Excel", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (excelApp != null)
{
excelApp.Quit();
}
}
}
I fixed this issue by adding following code in my file.
@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
XML configuration -
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
Above we can do using Java configuration -
@Configuration
@WebListener
public class MyRequestContextListener extends RequestContextListener {
}
How to add a RequestContextListener with no-xml configuration?
I am using spring version 5.1.4.RELEASE and no need to add below changes in pom.
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.10</version>
</dependency>
As @Nakilon said, their is a comparing tool built in github if that's what you use.
To use it, append the url of the repo with "/compare".
C++03's categories are too restricted to capture the introduction of rvalue references correctly into expression attributes.
With the introduction of them, it was said that an unnamed rvalue reference evaluates to an rvalue, such that overload resolution would prefer rvalue reference bindings, which would make it select move constructors over copy constructors. But it was found that this causes problems all around, for example with Dynamic Types and with qualifications.
To show this, consider
int const&& f();
int main() {
int &&i = f(); // disgusting!
}
On pre-xvalue drafts, this was allowed, because in C++03, rvalues of non-class types are never cv-qualified. But it is intended that const
applies in the rvalue-reference case, because here we do refer to objects (= memory!), and dropping const from non-class rvalues is mainly for the reason that there is no object around.
The issue for dynamic types is of similar nature. In C++03, rvalues of class type have a known dynamic type - it's the static type of that expression. Because to have it another way, you need references or dereferences, which evaluate to an lvalue. That isn't true with unnamed rvalue references, yet they can show polymorphic behavior. So to solve it,
unnamed rvalue references become xvalues. They can be qualified and potentially have their dynamic type different. They do, like intended, prefer rvalue references during overloading, and won't bind to non-const lvalue references.
What previously was an rvalue (literals, objects created by casts to non-reference types) now becomes an prvalue. They have the same preference as xvalues during overloading.
What previously was an lvalue stays an lvalue.
And two groupings are done to capture those that can be qualified and can have different dynamic types (glvalues) and those where overloading prefers rvalue reference binding (rvalues).
I would do it something along these lines:
class Foo{
...
};
int main(){
Foo* arrayOfFoo[100]; //[1]
arrayOfFoo[0] = new Foo; //[2]
}
[1] This makes an array of 100 pointers to Foo-objects. But no Foo-objects are actually created.
[2] This is one possible way to instantiate an object, and at the same time save a pointer to this object in the first position of your array.
We used the following mod_rewrite rule:
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/test/
RewriteCond %{REQUEST_URI} !^/my-folder/
RewriteRule (.*) http://www.newdomain.com/$1 [R=301,L]
This redirects (permanently with a 301 redirect) all traffic to the site to http://www.newdomain.com, except requests to resources in the /test and /my-folder directories. We transfer the user to the exact resource they requested by using the (.*) capture group and then including $1 in the new URL. Mind the spaces.
your panel class don't have a constructor that accepts a string
try change
RLS_strid_panel p = new RLS_strid_panel(namn1);
to
RLS_strid_panel p = new RLS_strid_panel();
p.setName1(name1);
This article is a good primer on fetching data with hooks: https://www.robinwieruch.de/react-hooks-fetch-data/
Essentially, include the fetch function definition inside useEffect
:
useEffect(() => {
const fetchBusinesses = () => {
return fetch("theUrl"...
// ...your fetch implementation
);
}
fetchBusinesses();
}, []);
Nothing like these two lines appears in Mike Williams' tutorial:
wait = true;
setTimeout("wait = true", 2000);
Here's a Version 3 port:
http://acleach.me.uk/gmaps/v3/plotaddresses.htm
The relevant bit of code is
// ====== Geocoding ======
function getAddress(search, next) {
geo.geocode({address:search}, function (results,status)
{
// If that was successful
if (status == google.maps.GeocoderStatus.OK) {
// Lets assume that the first marker is the one we want
var p = results[0].geometry.location;
var lat=p.lat();
var lng=p.lng();
// Output the data
var msg = 'address="' + search + '" lat=' +lat+ ' lng=' +lng+ '(delay='+delay+'ms)<br>';
document.getElementById("messages").innerHTML += msg;
// Create a marker
createMarker(search,lat,lng);
}
// ====== Decode the error status ======
else {
// === if we were sending the requests to fast, try this one again and increase the delay
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
nextAddress--;
delay++;
} else {
var reason="Code "+status;
var msg = 'address="' + search + '" error=' +reason+ '(delay='+delay+'ms)<br>';
document.getElementById("messages").innerHTML += msg;
}
}
next();
}
);
}
On the data dictionary side there are a lot of tools you can use to such as Schema Spy
To look at what queries are running look at views sys.v_$sql and sys.v_$sqltext. You will also need access to sys.all_users
One thing to note that queries that use parameters will show up once with entries like
and TABLETYPE=’:b16’
while others that dont will show up multiple times such as:
and TABLETYPE=’MT’
An example of these tables in action is the following SQL to find the top 20 diskread hogs. You could change this by removing the WHERE rownum <= 20 and maybe add ORDER BY module. You often find the module will give you a bog clue as to what software is running the query (eg: "TOAD 9.0.1.8", "JDBC Thin Client", "runcbl@somebox (TNS V1-V3)" etc)
SELECT
module,
sql_text,
username,
disk_reads_per_exec,
buffer_gets,
disk_reads,
parse_calls,
sorts,
executions,
rows_processed,
hit_ratio,
first_load_time,
sharable_mem,
persistent_mem,
runtime_mem,
cpu_time,
elapsed_time,
address,
hash_value
FROM
(SELECT
module,
sql_text ,
u.username ,
round((s.disk_reads/decode(s.executions,0,1, s.executions)),2) disk_reads_per_exec,
s.disk_reads ,
s.buffer_gets ,
s.parse_calls ,
s.sorts ,
s.executions ,
s.rows_processed ,
100 - round(100 * s.disk_reads/greatest(s.buffer_gets,1),2) hit_ratio,
s.first_load_time ,
sharable_mem ,
persistent_mem ,
runtime_mem,
cpu_time,
elapsed_time,
address,
hash_value
FROM
sys.v_$sql s,
sys.all_users u
WHERE
s.parsing_user_id=u.user_id
and UPPER(u.username) not in ('SYS','SYSTEM')
ORDER BY
4 desc)
WHERE
rownum <= 20;
Note that if the query is long .. you will have to query v_$sqltext. This stores the whole query. You will have to look up the ADDRESS and HASH_VALUE and pick up all the pieces. Eg:
SELECT
*
FROM
sys.v_$sqltext
WHERE
address = 'C0000000372B3C28'
and hash_value = '1272580459'
ORDER BY
address, hash_value, command_type, piece
;
Change your constructor to pass true as the second argument.
TextWriter tsw = new StreamWriter(@"C:\Hello.txt", true);
If all above methods fails use something like this:
import React, { Component } from 'react';
import { Redirect } from "react-router";
export default class Reedirect extends Component {
state = {
redirect: false
}
redirectHandler = () => {
this.setState({ redirect: true })
this.renderRedirect();
}
renderRedirect = () => {
if (this.state.redirect) {
return <Redirect to='/' />
}
}
render() {
return (
<>
<button onClick={this.redirectHandler}>click me</button>
{this.renderRedirect()}
</>
)
}
}
byte[] myvar = "Any String you want".getBytes();
String literals can be escaped to provide any character:
byte[] CDRIVES = "\u00e0\u004f\u00d0\u0020\u00ea\u003a\u0069\u0010\u00a2\u00d8\u0008\u0000\u002b\u0030\u0030\u009d".getBytes();
For non-printing characters, you can do the following:
NOTE: Colin's solution didn't work for me. Facebook may have changed their markup. Using *
should be more future-proof.
Wrap the Like box with a div:
<div id="likebox-wrapper">
<iframe src="..."></iframe> <!-- likebox code -->
</div>
and add this to your css file:
#likebox-wrapper * {
width: 100% !important;
}
None of the current solutions worked for me with git bash 2.26.2. This should work in any case if you are using the windows credential manager.
One issue is the windows credential manager runs for the logged user. In my case for example, I run git bash with right click, run as admin. Therefore, my stored credentials are in a credentials manager which I can't access with the windows GUI if I don't login to windows as admin.
To fix this:
cmdkey /list
. Your old credentials should appear here, with a part that reads ...target:xxx...cmdkey /delete:xxx
, where xxx is the target from the previous lineIt should confirm you that your credentials have been removed. Next time you do any operation in git bash that requires authentication, a popup will ask for your credentials.
The one reason I have which made switching to MacVim worth it: Yank uses the system clipboard.
I can finally copy paste between MacVim on my terminal and the rest of my applications.
With no intentions to critique John Hartsock, just in case the number of delimiters may vary for anyone using the given code, I would formally suggest to use this instead...
var mystr = '0000000020C90037:TEMP:data';
var myarr = mystr.split(":");
var arrlen = myarr.length;
var myvar = myarr[arrlen-2] + ":" + myarr[arrlen-1];
Make sure you import MaterialModule as well since you are using md-input which does not belong to FormsModule
Though the first approach is advocated as 'the angular like' approach, I feel this adds overheads.
Consider if I want to use this myservice.foo function in 10 different controllers. I will have to specify this 'myService' dependency and then $scope.callFoo scope property in all ten of them. This is simply a repetition and somehow violates the DRY principle.
Whereas, if I use the $rootScope approach, I specify this global function gobalFoo only once and it will be available in all my future controllers, no matter how many.
objArray.sort((a, b) => a.DepartmentName.localeCompare(b.DepartmentName))
In PL/SQL, there is a trick to use the undocumented OWA_UTIL.ITE
function.
SET SERVEROUTPUT ON
DECLARE
x VARCHAR2(10);
BEGIN
x := owa_util.ite('a' = 'b','T','F');
dbms_output.put_line(x);
END;
/
F
PL/SQL procedure successfully completed.
Yes Fiddler is an option for me:
CustomRules.js
).OnBeforeResponse
Add the following lines:
oSession.oResponse.headers.Remove("X-Frame-Options");
oSession.oResponse.headers.Add("Access-Control-Allow-Origin", "*");
Since this hasn't been closed yet, here are a few more options.
$FCEDIT
or $EDITOR
or emacs
(tried in that order).option25
(in this case). The line will be displayed. Hit Tab to start editing at this point.s///
modifier. E.g. !-2:s/--option25/--newoption/
would rerun the second-to-last command, but replace option25. To modify the last ./cmd
command, use the !string
syntax: !./cmd:s/--option25/--newoption/
^--option25^--newoption
I recommend the second option. Ctrl+r is really handy and fast, no mucking about with editors, and you see the results before the command is run (unlike the history expansions).
This does not strictly answer the original question but some people have mentioned that with session.autoflush = True
you don't have to use session.flush()
... And this is not always true.
If you want to use the id of a newly created object in the middle of a transaction, you must call session.flush()
.
# Given a model with at least this id
class AModel(Base):
id = Column(Integer, primary_key=True) # autoincrement by default on integer primary key
session.autoflush = True
a = AModel()
session.add(a)
a.id # None
session.flush()
a.id # autoincremented integer
This is because autoflush
does NOT auto fill the id (although a query of the object will, which sometimes can cause confusion as in "why this works here but not there?" But snapshoe already covered this part).
One related aspect that seems pretty important to me and wasn't really mentioned:
Why would you not commit all the time? - The answer is atomicity.
A fancy word to say: an ensemble of operations have to all be executed successfully OR none of them will take effect.
For example, if you want to create/update/delete some object (A) and then create/update/delete another (B), but if (B) fails you want to revert (A). This means those 2 operations are atomic.
Therefore, if (B) needs a result of (A), you want to call flush
after (A) and commit
after (B).
Also, if session.autoflush is True
, except for the case that I mentioned above or others in Jimbo's answer, you will not need to call flush
manually.
First, you need to compile your code with appropriate flags, enabling debug into code.
$ gcc -Wall -g -ggdb -o ex1 ex1.c
then just run you code with your favourite debugger
$ gdb ./ex1
show me the code.
(gdb) list
1 #include <stdio.h>
2 int main(void)
3 {
4 int i = 0;
5 for(i=0;i<7;++i)
6 printf("%d\n", i);
7
8 return 0;
9 }
break on lines 5 and looks if i == 5.
(gdb) b 5
Breakpoint 1 at 0x4004fb: file ex1.c, line 5.
(gdb) rwatch i if i==5
Hardware read watchpoint 5: i
checking breakpoints
(gdb) info b
Num Type Disp Enb Address What
1 breakpoint keep y 0x00000000004004fb in main at ex1.c:5
breakpoint already hit 1 time
5 read watchpoint keep y i
stop only if i==5
running the program
(gdb) c
Continuing.
0
1
2
3
4
Hardware read watchpoint 5: i
Value = 5
0x0000000000400523 in main () at ex1.c:5
5 for(i=0;i<7;++i)
You can use offsets to make a column appear centered, just use an offset equal to half of the remaining size of the row, in your case I would suggest using col-lg-4
with col-lg-offset-4
, that's (12-4)/2
.
<div class="row">
<div class="col-lg-4 col-lg-offset-4">
<div class="input-group">
<input type="text" class="form-control" />
<span class="input-group-btn">
<button class="btn btn-default" type="button">Go!</button>
</span>
</div><!-- /input-group -->
</div><!-- /.col-lg-4 -->
</div><!-- /.row -->
Note that this technique only works for even column sizes (.col-X-2
, .col-X-4
, col-X-6
, etc...), if you want to support any size you can use margin: 0 auto;
but you need to remove the float from the element too, I recommend a custom CSS class like the following:
.col-centered{
margin: 0 auto;
float: none;
}
My code from my library phery got a serialization routine that can deal with really complex forms (like in the demo https://github.com/pocesar/phery/blob/master/demo.php#L1664 ), and it's not a one-size-fits-all. It actually checks what the type of each field is. For example, a radio box isn't the same as a range, that isn't the same as keygen, that isn't the same as select multiple. My function covers it all, and you can see it at https://github.com/pocesar/phery/blob/master/phery.js#L1851.
serializeForm:function (opt) {
opt = $.extend({}, opt);
if (typeof opt['disabled'] === 'undefined' || opt['disabled'] === null) {
opt['disabled'] = false;
}
if (typeof opt['all'] === 'undefined' || opt['all'] === null) {
opt['all'] = false;
}
if (typeof opt['empty'] === 'undefined' || opt['empty'] === null) {
opt['empty'] = true;
}
var
$form = $(this),
result = {},
formValues =
$form
.find('input,textarea,select,keygen')
.filter(function () {
var ret = true;
if (!opt['disabled']) {
ret = !this.disabled;
}
return ret && $.trim(this.name);
})
.map(function () {
var
$this = $(this),
radios,
options,
value = null;
if ($this.is('[type="radio"]') || $this.is('[type="checkbox"]')) {
if ($this.is('[type="radio"]')) {
radios = $form.find('[type="radio"][name="' + this.name + '"]');
if (radios.filter('[checked]').size()) {
value = radios.filter('[checked]').val();
}
} else if ($this.prop('checked')) {
value = $this.is('[value]') ? $this.val() : 1;
}
} else if ($this.is('select')) {
options = $this.find('option').filter(':selected');
if ($this.prop('multiple')) {
value = options.map(function () {
return this.value || this.innerHTML;
}).get();
} else {
value = options.val();
}
} else {
value = $this.val();
}
return {
'name':this.name || null,
'value':value
};
}).get();
if (formValues) {
var
i,
value,
name,
$matches,
len,
offset,
j,
fields;
for (i = 0; i < formValues.length; i++) {
name = formValues[i].name;
value = formValues[i].value;
if (!opt['all']) {
if (value === null) {
continue;
}
} else {
if (value === null) {
value = '';
}
}
if (value === '' && !opt['empty']) {
continue;
}
if (!name) {
continue;
}
$matches = name.split(/\[/);
len = $matches.length;
for (j = 1; j < len; j++) {
$matches[j] = $matches[j].replace(/\]/g, '');
}
fields = [];
for (j = 0; j < len; j++) {
if ($matches[j] || j < len - 1) {
fields.push($matches[j].replace("'", ''));
}
}
if ($matches[len - 1] === '') {
offset = assign_object(result, fields, [], true, false, false);
if (value.constructor === Array) {
offset[0][offset[1]].concat(value);
} else {
offset[0][offset[1]].push(value);
}
} else {
assign_object(result, fields, value);
}
}
}
return result;
}
It's part of my library phery, but it can be ported to your own project. It creates arrays where there should be arrays, it gets the correct selected options from the select, normalize checkbox options, etc. If you want to convert it to JSON (a real JSON string), just do JSON.stringify($('form').serializeForm());
In my case I wanted to access an array inside a custom helper like so,
{{#ifCond arr.[@index] "foo" }}
Which did not work, but the answer suggested by @julesbou worked.
Working code:
{{#ifCond (lookup arr @index) "" }}
Hope this helps! Cheers.
Set
html { height: 100%; }
body { min-height: 100%; }
instead of height: 100%
.
The result jQuery returns is correct, because you've set the height of the body to 100%, and that's probably the height of the viewport. These three DIVs were causing an overflow, because there weren't enough space for them in the BODY element. To see what I mean, set a border to the BODY tag and check where the border ends.
While drive allows you to edit plain text and HTML files I don't believe they allow the HTML to actually be displayed. I don't think they want people hosting websites from their drive space.
function myStringify(obj, maxDeepLevel = 2) {
if (obj === null) {
return 'null';
}
if (obj === undefined) {
return 'undefined';
}
if (maxDeepLevel < 0 || typeof obj !== 'object') {
return obj.toString();
}
return Object
.entries(obj)
.map(x => x[0] + ': ' + myStringify(x[1], maxDeepLevel - 1))
.join('\r\n');
}
First of all, tf.train.GradientDescentOptimizer
is designed to use a constant learning rate for all variables in all steps. TensorFlow also provides out-of-the-box adaptive optimizers including the tf.train.AdagradOptimizer
and the tf.train.AdamOptimizer
, and these can be used as drop-in replacements.
However, if you want to control the learning rate with otherwise-vanilla gradient descent, you can take advantage of the fact that the learning_rate
argument to the tf.train.GradientDescentOptimizer
constructor can be a Tensor
object. This allows you to compute a different value for the learning rate in each step, for example:
learning_rate = tf.placeholder(tf.float32, shape=[])
# ...
train_step = tf.train.GradientDescentOptimizer(
learning_rate=learning_rate).minimize(mse)
sess = tf.Session()
# Feed different values for learning rate to each training step.
sess.run(train_step, feed_dict={learning_rate: 0.1})
sess.run(train_step, feed_dict={learning_rate: 0.1})
sess.run(train_step, feed_dict={learning_rate: 0.01})
sess.run(train_step, feed_dict={learning_rate: 0.01})
Alternatively, you could create a scalar tf.Variable
that holds the learning rate, and assign it each time you want to change the learning rate.
Perhaps you're looking for the x86_64 ABI?
If that's not precisely what you're after, use 'x86_64 abi' in your preferred search engine to find alternative references.
In my situation the problem was different. I don't know why, but even if directory on host had chmod 777
run on it, inside docker it was visible as 755
.
Running inside container sudo chmod 777 my_volume_dir
fixed it.
Just adding more info, I wasn't able to find sn.exe utility in the mentioned locations, in my case it was in C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin
You can always use a hidden div and use javascript to "popup" the div and have buttons that are like yes and or no. Pretty easy stuff to do.
the input.value = null
is a working method, however it will only trigger input's change
event if called from an onclick
event.
Solution to that would be calling that onchange
handler manually whenever you need to reset the input.
function reset_input(input) {
$(input)[0].value = null;
input_change_handler();
}
function input_change_handler() {
// this happens when there's been a change in file selection
if ($(input)[0].files.length) {
// file(s) selected
} else {
// nothing is selected
}
}
$(input).on('change', input_change_handler);
The best practice is selecting the most appropriate one.
.Net Framework 4.0 Beta 2 has a new IsNullOrWhiteSpace() method for strings which generalizes the IsNullOrEmpty() method to also include other white space besides empty string.
The term “white space” includes all characters that are not visible on screen. For example, space, line break, tab and empty string are white space characters*.
Reference : Here
For performance, IsNullOrWhiteSpace is not ideal but is good. The method calls will result in a small performance penalty. Further, the IsWhiteSpace method itself has some indirections that can be removed if you are not using Unicode data. As always, premature optimization may be evil, but it is also fun.
Reference : Here
Check the source code (Reference Source .NET Framework 4.6.2)
[Pure]
public static bool IsNullOrEmpty(String value) {
return (value == null || value.Length == 0);
}
[Pure]
public static bool IsNullOrWhiteSpace(String value) {
if (value == null) return true;
for(int i = 0; i < value.Length; i++) {
if(!Char.IsWhiteSpace(value[i])) return false;
}
return true;
}
Examples
string nullString = null;
string emptyString = "";
string whitespaceString = " ";
string nonEmptyString = "abc123";
bool result;
result = String.IsNullOrEmpty(nullString); // true
result = String.IsNullOrEmpty(emptyString); // true
result = String.IsNullOrEmpty(whitespaceString); // false
result = String.IsNullOrEmpty(nonEmptyString); // false
result = String.IsNullOrWhiteSpace(nullString); // true
result = String.IsNullOrWhiteSpace(emptyString); // true
result = String.IsNullOrWhiteSpace(whitespaceString); // true
result = String.IsNullOrWhiteSpace(nonEmptyString); // false
You should also keep in mind that when using like
, some sql flavors will ignore indexes, and that will kill performance. This is especially true if you don't use the "starts with" pattern like your example.
You should really look at the execution plan for the query and see what it's doing, guess as little as possible.
This being said, the "starts with" pattern can and is optimized in sql server. It will use the table index. EF 4.0 switched to like
for StartsWith
for this very reason.
You're misunderstanding the meaning of the merge here.
The --no-commit
prevents the MERGE COMMIT from occuring, and that only happens when you merge two divergent branch histories; in your example that's not the case since Git indicates that it was a "fast-forward" merge and then Git only applies the commits already present on the branch sequentially.
A quick search using...
apt search Xlib.h
Turns up the package libx11-dev but you shouldn't need this for pure OpenGL programming. What tutorial are you using?
You can add Xlib.h to your system by running the following...
sudo apt install libx11-dev
There is a HOC included for React-Table that allows for selection, even when filtering and paginating the table, the setup is slightly more advanced than the basic table so read through the info in the link below first.
After importing the HOC you can then use it like this with the necessary methods:
/**
* Toggle a single checkbox for select table
*/
toggleSelection(key: number, shift: string, row: string) {
// start off with the existing state
let selection = [...this.state.selection];
const keyIndex = selection.indexOf(key);
// check to see if the key exists
if (keyIndex >= 0) {
// it does exist so we will remove it using destructing
selection = [
...selection.slice(0, keyIndex),
...selection.slice(keyIndex + 1)
];
} else {
// it does not exist so add it
selection.push(key);
}
// update the state
this.setState({ selection });
}
/**
* Toggle all checkboxes for select table
*/
toggleAll() {
const selectAll = !this.state.selectAll;
const selection = [];
if (selectAll) {
// we need to get at the internals of ReactTable
const wrappedInstance = this.checkboxTable.getWrappedInstance();
// the 'sortedData' property contains the currently accessible records based on the filter and sort
const currentRecords = wrappedInstance.getResolvedState().sortedData;
// we just push all the IDs onto the selection array
currentRecords.forEach(item => {
selection.push(item._original._id);
});
}
this.setState({ selectAll, selection });
}
/**
* Whether or not a row is selected for select table
*/
isSelected(key: number) {
return this.state.selection.includes(key);
}
<CheckboxTable
ref={r => (this.checkboxTable = r)}
toggleSelection={this.toggleSelection}
selectAll={this.state.selectAll}
toggleAll={this.toggleAll}
selectType="checkbox"
isSelected={this.isSelected}
data={data}
columns={columns}
/>
See here for more information:
https://github.com/tannerlinsley/react-table/tree/v6#selecttable
Here is a working example:
https://codesandbox.io/s/react-table-select-j9jvw
There is another way to have multiple dataSources by using @EnableAutoConfiguration and application.properties.
Basically put multiple dataSource configuration info on application.properties and generate default setup (dataSource and entityManagerFactory) automatically for first dataSource by @EnableAutoConfiguration. But for next dataSource, create dataSource, entityManagerFactory and transactionManager all manually by the info from property file.
Below is my example to setup two dataSources. First dataSource is setup by @EnableAutoConfiguration which can be assigned only for one configuration, not multiple. And that will generate 'transactionManager' by DataSourceTransactionManager, that looks default transactionManager generated by the annotation. However I have seen the transaction not beginning issue on the thread from scheduled thread pool only for the default DataSourceTransactionManager and also when there are multiple transaction managers. So I create transactionManager manually by JpaTransactionManager also for the first dataSource with assigning 'transactionManager' bean name and default entityManagerFactory. That JpaTransactionManager for first dataSource surely resolves the weird transaction issue on the thread from ScheduledThreadPool.
Update for Spring Boot 1.3.0.RELEASE
I found my previous configuration with @EnableAutoConfiguration for default dataSource has issue on finding entityManagerFactory with Spring Boot 1.3 version. Maybe default entityManagerFactory is not generated by @EnableAutoConfiguration, once after I introduce my own transactionManager. So now I create entityManagerFactory by myself. So I don't need to use @EntityScan. So it looks I'm getting more and more out of the setup by @EnableAutoConfiguration.
Second dataSource is setup without @EnableAutoConfiguration and create 'anotherTransactionManager' by manual way.
Since there are multiple transactionManager extends from PlatformTransactionManager, we should specify which transactionManager to use on each @Transactional annotation
Default Repository Config
@Configuration
@EnableTransactionManagement
@EnableAutoConfiguration
@EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactory",
transactionManagerRef = "transactionManager",
basePackages = {"com.mysource.repository"})
public class RepositoryConfig {
@Autowired
JpaVendorAdapter jpaVendorAdapter;
@Autowired
DataSource dataSource;
@Bean(name = "entityManager")
public EntityManager entityManager() {
return entityManagerFactory().createEntityManager();
}
@Primary
@Bean(name = "entityManagerFactory")
public EntityManagerFactory entityManagerFactory() {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource);
emf.setJpaVendorAdapter(jpaVendorAdapter);
emf.setPackagesToScan("com.mysource.model");
emf.setPersistenceUnitName("default"); // <- giving 'default' as name
emf.afterPropertiesSet();
return emf.getObject();
}
@Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager() {
JpaTransactionManager tm = new JpaTransactionManager();
tm.setEntityManagerFactory(entityManagerFactory());
return tm;
}
}
Another Repository Config
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "anotherEntityManagerFactory",
transactionManagerRef = "anotherTransactionManager",
basePackages = {"com.mysource.anothersource.repository"})
public class AnotherRepositoryConfig {
@Autowired
JpaVendorAdapter jpaVendorAdapter;
@Value("${another.datasource.url}")
private String databaseUrl;
@Value("${another.datasource.username}")
private String username;
@Value("${another.datasource.password}")
private String password;
@Value("${another.dataource.driverClassName}")
private String driverClassName;
@Value("${another.datasource.hibernate.dialect}")
private String dialect;
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource(databaseUrl, username, password);
dataSource.setDriverClassName(driverClassName);
return dataSource;
}
@Bean(name = "anotherEntityManager")
public EntityManager entityManager() {
return entityManagerFactory().createEntityManager();
}
@Bean(name = "anotherEntityManagerFactory")
public EntityManagerFactory entityManagerFactory() {
Properties properties = new Properties();
properties.setProperty("hibernate.dialect", dialect);
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource());
emf.setJpaVendorAdapter(jpaVendorAdapter);
emf.setPackagesToScan("com.mysource.anothersource.model"); // <- package for entities
emf.setPersistenceUnitName("anotherPersistenceUnit");
emf.setJpaProperties(properties);
emf.afterPropertiesSet();
return emf.getObject();
}
@Bean(name = "anotherTransactionManager")
public PlatformTransactionManager transactionManager() {
return new JpaTransactionManager(entityManagerFactory());
}
}
application.properties
# database configuration
spring.datasource.url=jdbc:h2:file:~/main-source;AUTO_SERVER=TRUE
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.continueOnError=true
spring.datasource.initialize=false
# another database configuration
another.datasource.url=jdbc:sqlserver://localhost:1433;DatabaseName=another;
another.datasource.username=username
another.datasource.password=
another.datasource.hibernate.dialect=org.hibernate.dialect.SQLServer2008Dialect
another.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
Choose proper transactionManager for @Transactional annotation
Service for first datasource
@Service("mainService")
@Transactional("transactionManager")
public class DefaultDataSourceServiceImpl implements DefaultDataSourceService
{
//
}
Service for another datasource
@Service("anotherService")
@Transactional("anotherTransactionManager")
public class AnotherDataSourceServiceImpl implements AnotherDataSourceService
{
//
}
Download http://download.cnet.com/Free-Desktop-Timer/3000-2350_4-75415517.html
Then add a button or something on the form and inside its event, just open this app ie:
{
Process.Start(@"C:\Program Files (x86)\Free Desktop Timer\DesktopTimer");
}
put anyfile on the directories you wanted to find, in this case, place 'root' at public_html
/home/user/public_html/root <- note that 'root' is not a folder (you can use root.txt if u want)
And use this function
function findThis($get){
$d = '';
for($i = 0; $i < 20; $i++){//this will try 20 times recursively on upper folder
if(file_exists($d.$get)){
return $d;
}else{
$d.="../";
}
}
}
and get the value by calling it
$pathToRoot = findThis('root');
And it will return, for example the the dir of php script is
/home/user/public_html/test/another-dir/test.php
so the $pathToRoot will be
$pathToRoot => "../../../"
Is this the one you want??
string[0] = "";
"warning: assignment makes integer from pointer without a cast
Ok, let's dive into the expression ...
0
an int: represents the number of chars (assuming string
is (or decayed into) a char*) to advance from the beginning of the object string
string[0]
: the char
object located at the beginning of the object string
""
: string literal: an object of type char[1]
=
: assignment operator: tries to assign a value of type char[1]
to an object of type char
. char[1]
(decayed to char*
) and char
are not assignment compatible, but the compiler trusts you (the programmer) and goes ahead with the assignment anyway by casting the type char*
(what char[1]
decayed to) to an int
--- and you get the warning as a bonus. You have a really nice compiler :-)
This is how to retrieve a Column Name from a DataColumn:
MyDataTable.Columns(1).ColumnName
To get the name of all DataColumns within your DataTable:
Dim name(DT.Columns.Count) As String
Dim i As Integer = 0
For Each column As DataColumn In DT.Columns
name(i) = column.ColumnName
i += 1
Next
References
If you want to add a custom image to checkbox then set button to null and just add background to checkbox that's solve
<CheckBox
android:layout_width="22dp"
android:layout_height="22dp"
android:layout_marginLeft="-10dp"
android:button="@null"
android:background="@drawable/memory_selector"/>
<?php
ob_start();
system('ipconfig/all');
$mycom=ob_get_contents();
ob_clean();
$findme = "Physical";
$pmac = strpos($mycom, $findme);
$mac=substr($mycom,($pmac+36),17);
echo $mac;
?>
This prints the mac address of client machine
Please run below code may it helps you :)
var str = "this,is,an,example";_x000D_
var strArr = str.split(',');_x000D_
var data = "";_x000D_
for(var i=0; i<strArr.length; i++){_x000D_
data += "Index : "+i+" value : "+strArr[i]+"<br/>";_x000D_
}_x000D_
document.getElementById('print').innerHTML = data;
_x000D_
<div id="print">_x000D_
</div>
_x000D_
https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.md5?view=netframework-4.7.2
using System;
using System.Security.Cryptography;
using System.Text;
static string GetMd5Hash(string input)
{
using (MD5 md5Hash = MD5.Create())
{
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
}
// Verify a hash against a string.
static bool VerifyMd5Hash(string input, string hash)
{
// Hash the input.
string hashOfInput = GetMd5Hash(input);
// Create a StringComparer an compare the hashes.
StringComparer comparer = StringComparer.OrdinalIgnoreCase;
return 0 == comparer.Compare(hashOfInput, hash);
}
You can use the dplyr
package to easily remove those particular rows.
library(dplyr)
df <- filter(df, C != "Foo")
Some interesting timings regarding all these methods. If you have Gigabit connections, you should not use the /z flag or it will kill your connection speed. Robocopy or dism are the only tools that go full speed and show a progress bar. wdscase is for multicasting off a WDS server and might be faster if you are imaging 5+ computers. To get the 1:17 timing, I was maxing out the Gigabit connection at 920Mbps so you won't get that on two connections at once. Also take note that exporting the small wim index out of the larger wim file too longer than just copying the whole thing.
Model Exe OS switches index size time link speed
8760w dism Win8 /export-wim index 1 6.27GB 2:21 link 1Gbps
8760w dism Win8 /export-wim index 2 7.92GB 1:29 link 1Gbps
6305 wdsmcast winpe32 /trans-file res.RWM 7.92GB 6:54 link 1Gbps
6305 dism Winpe32 /export-wim index 1 6.27GB 2:20 link 1Gbps
6305 dism Winpe32 /export-wim index 2 7.92GB 1:34 link 1Gbps
6305 copy Winpe32 /z Whole 7.92GB 25:48 link 1Gbps
6305 copy Winpe32 none Wim 7.92GB 1:17 link 1Gbps
6305 xcopy Winpe32 /z /j Wim 7.92GB 23:54 link 1Gbps
6305 xcopy Winpe32 /j Wim 7.92GB 1:38 link 1Gbps
6305 VBS.copy Winpe32 Wim 7.92 1:21 link 1Gbps
6305 robocopy Winpe32 Wim 7.92 1:17 link 1Gbps
If you don't have robocopy.exe available, why not run it from the network share you are copying your files from? In my case, I prefer to do that so I don't have to rebuild my WinPE boot.wim file every time I want to make a change and then update dozens of flash drives.