I created my own function to extract the rules from the decision trees created by sklearn:
import pandas as pd
import numpy as np
from sklearn.tree import DecisionTreeClassifier
# dummy data:
df = pd.DataFrame({'col1':[0,1,2,3],'col2':[3,4,5,6],'dv':[0,1,0,1]})
# create decision tree
dt = DecisionTreeClassifier(max_depth=5, min_samples_leaf=1)
dt.fit(df.ix[:,:2], df.dv)
This function first starts with the nodes (identified by -1 in the child arrays) and then recursively finds the parents. I call this a node's 'lineage'. Along the way, I grab the values I need to create if/then/else SAS logic:
def get_lineage(tree, feature_names):
left = tree.tree_.children_left
right = tree.tree_.children_right
threshold = tree.tree_.threshold
features = [feature_names[i] for i in tree.tree_.feature]
# get ids of child nodes
idx = np.argwhere(left == -1)[:,0]
def recurse(left, right, child, lineage=None):
if lineage is None:
lineage = [child]
if child in left:
parent = np.where(left == child)[0].item()
split = 'l'
else:
parent = np.where(right == child)[0].item()
split = 'r'
lineage.append((parent, split, threshold[parent], features[parent]))
if parent == 0:
lineage.reverse()
return lineage
else:
return recurse(left, right, parent, lineage)
for child in idx:
for node in recurse(left, right, child):
print node
The sets of tuples below contain everything I need to create SAS if/then/else statements. I do not like using do
blocks in SAS which is why I create logic describing a node's entire path. The single integer after the tuples is the ID of the terminal node in a path. All of the preceding tuples combine to create that node.
In [1]: get_lineage(dt, df.columns)
(0, 'l', 0.5, 'col1')
1
(0, 'r', 0.5, 'col1')
(2, 'l', 4.5, 'col2')
3
(0, 'r', 0.5, 'col1')
(2, 'r', 4.5, 'col2')
(4, 'l', 2.5, 'col1')
5
(0, 'r', 0.5, 'col1')
(2, 'r', 4.5, 'col2')
(4, 'r', 2.5, 'col1')
6
If you run into issues with grabbing the source .dot directly you can also use Source.from_file
like this:
from graphviz import Source
from sklearn import tree
tree.export_graphviz(dtreg, out_file='tree.dot', feature_names=X.columns)
Source.from_file('tree.dot')
This solution worked for me Android Studio 3.3.2.
One way I've found to do this is to create an img tag and set the src attribute to the file you are looking for. The onload or onerror of the img element will fire based on whether the file exists. You can't load any data using this method, but you can determine if a particular file exists or not.
The value of EOF can't be confused with any real character.
If a= getchar()
, then we must declare a
big enough to hold any value that getchar()
returns. We can't use char
since a
must be big enough to hold EOF in addition to characters.
A complete solution is here
it's explained very nice with sample code. However, be careful that it does not close the application.Add the line Application.Current.Shutdown(); to gracefully close the app.
Personally I rarely write loops myself now when I can get away with it... I use the Jakarta commons libs:
Customer findCustomerByid(final int id){
return (Customer) CollectionUtils.find(customers, new Predicate() {
public boolean evaluate(Object arg0) {
return ((Customer) arg0).getId()==id;
}
});
}
Yay! I saved one line!
Use ng-value
for set value of input box after clicking on a button
:
"input type="email" class="form-control" id="email2" ng-value="myForm.email2" placeholder="Email"
and
Set Value as:
$scope.myForm.email2 = $scope.names[0].success;
<div><p>some unnecessary content</p></div>
div{
border: 1px solid red;
width: 40%;
padding: 40%;
box-sizing: border-box;
position: relative;
}
p{
position: absolute;
top: 0;
left: 0;
}
For this to work i think you need to define the padding to ex. top? like this:
<div><p>some unnecessary content</p></div>
div{
border: 1px solid red;
width: 40%;
padding-top: 40%;
box-sizing: border-box;
position: relative;
}
p{
position: absolute;
top: 0;
left: 0;
}
anyways, thats how i got it to work, since with just padding all arround it would not be a square.
If you'd like to initialize the array to values other than 0, with gcc
you can do:
int array[1024] = { [ 0 ... 1023 ] = -1 };
This is a GNU extension of C99 Designated Initializers. In older GCC, you may need to use -std=gnu99
to compile your code.
For me it worked as Kumar Jaggal but: steps 1, 2, 3, the same 4. py -m setup.py install
They're the same, aren't they? Now I'm losing confidence in myself but I really thought IPv6 was just an addressing change. TCP and UDP are still addressed as they are under IPv4.
There's a Python module that you can get from PyPI called progressbar
that implements such functionality. If you don't mind adding a dependency, it's a good solution. Otherwise, go with one of the other answers.
A simple example of how to use it:
import progressbar
from time import sleep
bar = progressbar.ProgressBar(maxval=20, \
widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()])
bar.start()
for i in xrange(20):
bar.update(i+1)
sleep(0.1)
bar.finish()
To install it, you can use easy_install progressbar
, or pip install progressbar
if you prefer pip.
A solution that works for S3 modified from Minkymorgan.
Simply pass the temporary partitioned directory path (with different name than final path) as the srcPath
and single final csv/txt as destPath
Specify also deleteSource
if you want to remove the original directory.
/**
* Merges multiple partitions of spark text file output into single file.
* @param srcPath source directory of partitioned files
* @param dstPath output path of individual path
* @param deleteSource whether or not to delete source directory after merging
* @param spark sparkSession
*/
def mergeTextFiles(srcPath: String, dstPath: String, deleteSource: Boolean): Unit = {
import org.apache.hadoop.fs.FileUtil
import java.net.URI
val config = spark.sparkContext.hadoopConfiguration
val fs: FileSystem = FileSystem.get(new URI(srcPath), config)
FileUtil.copyMerge(
fs, new Path(srcPath), fs, new Path(dstPath), deleteSource, config, null
)
}
Since C++11 you can use std::chrono
:
std::chrono::system_clock::now()
.time_since_epoch()
duration_cast<milliseconds>(d)
std::chrono::milliseconds
to integer (uint64_t
to avoid overflow)#include <chrono>
#include <cstdint>
#include <iostream>
uint64_t timeSinceEpochMillisec() {
using namespace std::chrono;
return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
}
int main() {
std::cout << timeSinceEpochMillisec() << std::endl;
return 0;
}
The year()
function just retrieves the year component of the underlying Date
object, so it returns a number.
Calling format('YYYY')
will invoke moment's string formatting functions, which will parse the format string supplied, and build a new string containing the appropriate data. Since you only are passing YYYY
, then the result will be a string containing the year.
If all you need is the year, then use the year()
function. It will be faster, as there is less work to do.
Do note that while years are the same in this regard, months are not! Calling format('M')
will return months in the range 1-12. Calling month()
will return months in the range 0-11. This is due to the same behavior of the underlying Date
object.
Java is 'Big-endian' as noted above. That means that the MSB of an int is on the left if you examine memory (on an Intel CPU at least). The sign bit is also in the MSB for all Java integer types.
Reading a 4 byte unsigned integer from a binary file stored by a 'Little-endian' system takes a bit of adaptation in Java. DataInputStream's readInt() expects Big-endian format.
Here's an example that reads a four byte unsigned value (as displayed by HexEdit as 01 00 00 00) into an integer with a value of 1:
// Declare an array of 4 shorts to hold the four unsigned bytes
short[] tempShort = new short[4];
for (int b = 0; b < 4; b++) {
tempShort[b] = (short)dIStream.readUnsignedByte();
}
int curVal = convToInt(tempShort);
// Pass an array of four shorts which convert from LSB first
public int convToInt(short[] sb)
{
int answer = sb[0];
answer += sb[1] << 8;
answer += sb[2] << 16;
answer += sb[3] << 24;
return answer;
}
In Python 3.4+: os.cpu_count().
multiprocessing.cpu_count()
is implemented in terms of this function but raises NotImplementedError
if os.cpu_count()
returns None
("can't determine number of CPUs").
Also the same error may occur when you put a new class into the source code of a designer created form's class.
This new class may be removed, and placed in a different cs file.
(At least in my case this was the problem...)
Here's a demonstration page that uses slowAES.
slowAES was easy to use. Logically designed. Reasonable OO packaging. Supports knobs and levers like IV and Encryption mode. Good compatibility with .NET/C#. The name is tongue-in-cheek; it's called "slow AES" because it's not implemented in C++. But in my tests it was not impractically slow.
It lacks an ECB mode. Also lacks a CTR mode, although you could build one pretty easily given an ECB mode, I guess.
It is solely focused on encryption. A nice complementary class that does RFC2898-compliant password-based key derivation, in Javascript, is available from Anandam. This pair of libraries works well with the analogous .NET classes. Good interop. Though, in contrast to SlowAES, the Javascript PBKDF2 is noticeably slower than the Rfc2898DeriveBytes class when generating keys.
It's not surprising that technically there is good interop, but the key point for me was the model adopted by SlowAES is familiar and easy to use. I found some of the other Javascript libraries for AES to be hard to understand and use. For example, in some of them I couldn't find the place to set the IV, or the mode (CBC, ECB, etc). Things were not where I expected them to be. SlowAES was not like that. The properties were right where I expected them to be. It was easy for me to pick up, having been familiar with the Java and .NET crypto programming models.
Anandam's PBKDF2 was not quite on that level. It supported only a single call to DeriveBytes function, so if you need to derive both a key and an IV from a password, this library won't work, unchanged. Some slight modification, and it is working just fine for that purpose.
EDIT: I put together an example of packaging SlowAES and a modified version of Anandam's PBKDF2 into Windows Script Components. Using this AES with a password-derived key shows good interop with the .NET RijndaelManaged class.
EDIT2: the demo page shows how to use this AES encryption from a web page. Using the same inputs (iv, key, mode, etc) supported in .NET gives you good interop with the .NET Rijndael class. You can do a "view source" to get the javascript for that page.
EDIT3
a late addition: Javascript Cryptography considered harmful. Worth the read.
Shallow Cloning:
Definition: "A shallow copy of an object copies the ‘main’ object, but doesn’t copy the inner objects."
When a custom object (eg. Employee) has just primitive, String type variables then you use Shallow Cloning.
Employee e = new Employee(2, "john cena");
Employee e2=e.clone();
You return super.clone();
in the overridden clone() method and your job is over.
Deep Cloning:
Definition: "Unlike the shallow copy, a deep copy is a fully independent copy of an object."
Means when an Employee object holds another custom object:
Employee e = new Employee(2, "john cena", new Address(12, "West Newbury", "Massachusetts");
Then you have to write the code to clone the 'Address' object as well in the overridden clone() method. Otherwise the Address object won't clone and it causes a bug when you change value of Address in cloned Employee object, which reflects the original one too.
You will need to know something about the URLs, like do they have a specific directory or some query string element because you have to match for something. Otherwise you will have to redirect on the 404. If this is what is required then do something like this in your .htaccess:
ErrorDocument 404 /index.php
An error page redirect must be relative to root so you cannot use www.mydomain.com.
If you have a pattern to match too then use 301 instead of 302 because 301 is permanent and 302 is temporary. A 301 will get the old URLs removed from the search engines and the 302 will not.
Mod Rewrite Reference: http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html
Google has recently launched design support library and there is one component called TextInputLayout and it supports showing an error via setErrorEnabled(boolean)
and setError(CharSequence)
.
How to use it?
Step 1: Wrap your EditText with TextInputLayout:
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/layoutUserName">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="hint"
android:id="@+id/editText1" />
</android.support.design.widget.TextInputLayout>
Step 2: Validate input
// validating input on a button click
public void btnValidateInputClick(View view) {
final TextInputLayout layoutUserName = (TextInputLayout) findViewById(R.id.layoutUserName);
String strUsername = layoutLastName.getEditText().getText().toString();
if(!TextUtils.isEmpty(strLastName)) {
Snackbar.make(view, strUsername, Snackbar.LENGTH_SHORT).show();
layoutUserName.setErrorEnabled(false);
} else {
layoutUserName.setError("Input required");
layoutUserName.setErrorEnabled(true);
}
}
I have created an example over my Github repository, checkout the example if you wish to!
ANT_HOME
is not being resolved. Change %ANT_HOME%\bin
in the Path system environment variable to c:\apache-ant\apache-ant-1.8.2\bin
.
csvde -f test.csv
This command will perform a CSV dump of every entry in your Active Directory server. You should be able to see the full DN's of users and groups.
You will have to go through that output file and get rid off the unnecessary content.
Little bit off topic but say i want to remove all 2s from a list. Here's a very elegant way to do that.
void RemoveAll<T>(T item,List<T> list)
{
while(list.Contains(item)) list.Remove(item);
}
With predicate:
void RemoveAll<T>(Func<T,bool> predicate,List<T> list)
{
while(list.Any(predicate)) list.Remove(list.First(predicate));
}
+1 only to encourage you to leave your answer here for learning purposes. You're also right about it being off-topic, but I won't ding you for that because of there is significant value in leaving your examples here, again, strictly for learning purposes. I'm posting this response as an edit because posting it as a series of comments would be unruly.
Though your examples are short & compact, neither is elegant in terms of efficiency; the first is bad at O(n2), the second, absolutely abysmal at O(n3). Algorithmic efficiency of O(n2) is bad and should be avoided whenever possible, especially in general-purpose code; efficiency of O(n3) is horrible and should be avoided in all cases except when you know n will always be very small. Some might fling out their "premature optimization is the root of all evil" battle axes, but they do so naïvely because they do not truly understand the consequences of quadratic growth since they've never coded algorithms that have to process large datasets. As a result, their small-dataset-handling algorithms just run generally slower than they could, and they have no idea that they could run faster. The difference between an efficient algorithm and an inefficient algorithm is often subtle, but the performance difference can be dramatic. The key to understanding the performance of your algorithm is to understand the performance characteristics of the primitives you choose to use.
In your first example, list.Contains()
and Remove()
are both O(n), so a while()
loop with one in the predicate & the other in the body is O(n2); well, technically O(m*n), but it approaches O(n2) as the number of elements being removed (m) approaches the length of the list (n).
Your second example is even worse: O(n3), because for every time you call Remove()
, you also call First(predicate)
, which is also O(n). Think about it: Any(predicate)
loops over the list looking for any element for which predicate()
returns true. Once it finds the first such element, it returns true. In the body of the while()
loop, you then call list.First(predicate)
which loops over the list a second time looking for the same element that had already been found by list.Any(predicate)
. Once First()
has found it, it returns that element which is passed to list.Remove()
, which loops over the list a third time to yet once again find that same element that was previously found by Any()
and First()
, in order to finally remove it. Once removed, the whole process starts over at the beginning with a slightly shorter list, doing all the looping over and over and over again starting at the beginning every time until finally no more elements matching the predicate remain. So the performance of your second example is O(m*m*n), or O(n3) as m approaches n.
Your best bet for removing all items from a list that match some predicate is to use the generic list's own List<T>.RemoveAll(predicate)
method, which is O(n) as long as your predicate is O(1). A for()
loop technique that passes over the list only once, calling list.RemoveAt()
for each element to be removed, may seem to be O(n) since it appears to pass over the loop only once. Such a solution is more efficient than your first example, but only by a constant factor, which in terms of algorithmic efficiency is negligible. Even a for()
loop implementation is O(m*n) since each call to Remove()
is O(n). Since the for()
loop itself is O(n), and it calls Remove()
m times, the for()
loop's growth is O(n2) as m approaches n.
I had a similar problem due to a zombie vim.exe process.
Killing it in Task Manager, followed by a git rebase --abort
fixed it.
You'll need to use os.stat
to get the file creation time and a combination of time.strftime
and time.timezone
for formatting:
>>> import time
>>> import os
>>> t = os.stat('C:/Path/To/File.txt').st_ctime
>>> t = time.localtime(t)
>>> formatted = time.strftime('%Y-%m-%d %H:%M:%S', t)
>>> tz = str.format('{0:+06.2f}', float(time.timezone) / 3600)
>>> final = formatted + tz
>>>
>>> final
'2008-11-24 14:46:08-02.00'
You should use maven surefire plugin to run unit tests and maven failsafe plugin to run integration tests.
Please follow below if you wish to toggle the execution of these tests using flags.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>${skipUnitTests}</skipTests>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<configuration>
<includes>
<include>**/*IT.java</include>
</includes>
<skipTests>${skipIntegrationTests}</skipTests>
</configuration>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<properties>
<skipTests>false</skipTests>
<skipUnitTests>${skipTests}</skipUnitTests>
<skipIntegrationTests>${skipTests}</skipIntegrationTests>
</properties>
So, tests will be skipped or switched according to below flag rules:
Tests can be skipped by below flags:
-DskipTests
skips both unit and integration tests-DskipUnitTests
skips unit tests but executes integration tests-DskipIntegrationTests
skips integration tests but executes unit testsRun below to execute only Unit Tests
mvn clean test
You can execute below command to run the tests (both unit and integration)
mvn clean verify
In order to run only Integration Tests, follow
mvn failsafe:integration-test
Or skip unit tests
mvn clean install -DskipUnitTests
Also, in order to skip integration tests during mvn install
, follow
mvn clean install -DskipIntegrationTests
You can skip all tests using
mvn clean install -DskipTests
Note if you are on certain shared hosting sites like Dreamhost you can't disable PHP output buffering at all without going through different routes:
Changing the output buffer cache If you are using PHP FastCGI, the PHP functions flush(), ob_flush(), and ob_implicit_flush() will not function as expected. By default, output is buffered at a higher level than PHP (specifically, by the Apache module mod_deflate which is similar in form/function to mod_gzip).
If you need unbuffered output, you must either use CGI (instead of FastCGI) or contact support to request that mod_deflate is disabled for your site.
https://help.dreamhost.com/hc/en-us/articles/214202188-PHP-overview
You probably forgot to give #
before id for id selector, you need to give #
before id
ie is ulId
You problably need to bind scroll event on div that contains the ul and scrolls. You need to bind the event with div instead of ul
$(document).on( 'scroll', '#idOfDivThatContainsULandScroll', function(){
console.log('Event Fired');
});
Edit
The above would not work because the scroll event does not bubble up in DOM which is used for event delegation, see this question why doesn't delegate work for scroll?
But with modern browsers > IE 8 you can do it by other way. Instead of delegating by using jquery you can do it using event capturing with java script document.addEventListener
, with the third argument as true
; see how bubbling and capturing work in this tuturial.
document.addEventListener('scroll', function (event) {
if (event.target.id === 'idOfUl') { // or any other filtering condition
console.log('scrolling', event.target);
}
}, true /*Capture event*/);
If you do not need event delegation then you can bind scroll event directly to the ul instead of delegating it through document
.
$("#idOfUl").on( 'scroll', function(){
console.log('Event Fired');
});
Ideally, every custom watch should be removed when you leave the scope.
It helps in better memory management and better app performance.
// call to $watch will return a de-register function
var listener = $scope.$watch(someVariableToWatch, function(....));
$scope.$on('$destroy', function() {
listener(); // call the de-register function on scope destroy
});
If your count(distinct(x))
is significantly slower than count(x)
then you can speed up this query by maintaining x value counts in different table, for example table_name_x_counts (x integer not null, x_count int not null)
, using triggers. But your write performance will suffer and if you update multiple x
values in single transaction then you'd need to do this in some explicit order to avoid possible deadlock.
Well I know this might be a big change or even not suitable for your project, but did you consider not performing the push until you already have the data? That way you only need to draw the view once and the user experience will also be better - the push will move in already loaded.
The way you do this is in the UITableView
didSelectRowAtIndexPath
you asynchronously ask for the data. Once you receive the response, you manually perform the segue and pass the data to your viewController in prepareForSegue
.
Meanwhile you may want to show some activity indicator, for simple loading indicator check https://github.com/jdg/MBProgressHUD
Just for fun, here's a non-regex (more readable/maintainable for simpletons like me) solution:
string myString = "AB12";
if( Char.IsLetter(myString, 0) &&
Char.IsLetter(myString, 1) &&
Char.IsNumber(myString, 2) &&
Char.IsNumber(myString, 3)) {
// First two are letters, second two are numbers
}
else {
// Validation failed
}
EDIT
It seems that I've misunderstood the requirements. The code below will ensure that the first two characters and last two characters of a string validate (so long as the length of the string is > 3)
string myString = "AB12";
if(myString.Length > 3) {
if( Char.IsLetter(myString, 0) &&
Char.IsLetter(myString, 1) &&
Char.IsNumber(myString, (myString.Length - 2)) &&
Char.IsNumber(myString, (myString.Length - 1))) {
// First two are letters, second two are numbers
}
else {
// Validation failed
}
}
else {
// Validation failed
}
To push your existing repo into different, you need to:
Clone the original repo first.
git clone https://git.fedorahosted.org/cgit/rhq/rhq.git
Push the cloned sources to your new repository:
cd rhq
git push https://github.com/user/example master:master
You may change master:master
into source:destination
branch.
If you want to push specific commit (branch), then do:
On the original repo, create and checkout a new branch:
git checkout -b new_branch
Choose and reset to the point which you want to start with:
git log # Find the interesting hash
git reset 4b62bdc9087bf33cc01d0462bf16bbf396369c81 --hard
Alternatively select the commit by git cherry-pick
to append into existing HEAD.
Then push to your new repo:
git push https://github.com/user/example new_branch:master
If you're rebasing, use -f
for force push (not recommended). Run git reflog
to see history of changes.
if you are use using notepad: then
public String toString(){
return ""; ---now here you can use variables which you have created for your class
}
if you are using eclipse IDE then press
-alt +shift +s
-click on override toString method here you will get options to select what type of variables you want to select.
Similar to answer by @Jeff_Alieffson, but not relying on default Locale
:
Use DecimalFormatSymbols
for explicit locale:
DecimalFormatSymbols decimalFormatSymbols = DecimalFormatSymbols.getInstance(new Locale("ru", "RU"));
Or explicit separator symbols:
DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
decimalFormatSymbols.setDecimalSeparator('.');
decimalFormatSymbols.setGroupingSeparator(' ');
Then:
new DecimalFormat("#,##0.00", decimalFormatSymbols).format(new BigDecimal("12345"));
Result:
12 345.00
You could try this notattion:
SELECT * from table1,table2
More complicated one :
SELECT table1.field1,table1.field2, table2.field3,table2.field8 from table1,table2 where table1.field2 = something and table2.field3 = somethingelse
You are sending a POST AJAX request so use $albumname = $_POST['album'];
on your server to fetch the value. Also I would recommend you writing the request like this in order to ensure proper encoding:
$.ajax({
type: 'POST',
url: 'test.php',
data: { album: this.title },
success: function(response) {
content.html(response);
}
});
or in its shorter form:
$.post('test.php', { album: this.title }, function() {
content.html(response);
});
and if you wanted to use a GET request:
$.ajax({
type: 'GET',
url: 'test.php',
data: { album: this.title },
success: function(response) {
content.html(response);
}
});
or in its shorter form:
$.get('test.php', { album: this.title }, function() {
content.html(response);
});
and now on your server you wil be able to use $albumname = $_GET['album'];
. Be careful though with AJAX GET requests as they might be cached by some browsers. To avoid caching them you could set the cache: false
setting.
With JDK8 it does have some support for them.
We may yet see full support of unsigned types in Java despite Gosling's concerns.
Just need to set the value property in a convenient place (such as InitializeComponent()
):
dateTimePicker1.Value = DateTime.Today.AddDays(-1);
Public Function getWholeNumber(number As Decimal) As Integer
Dim round = Math.Round(number, 0)
If round > number Then
Return round - 1
Else
Return round
End If
End Function
I'll try and explain it as simple as possible. So there is no guarantee of the accuracy of the actual terms.
Session is where to initiate the connectivity to AWS services. E.g. following is default session that uses the default credential profile(e.g. ~/.aws/credentials, or assume your EC2 using IAM instance profile )
sqs = boto3.client('sqs')
s3 = boto3.resource('s3')
Because default session is limit to the profile or instance profile used, sometimes you need to use the custom session to override the default session configuration (e.g. region_name, endpoint_url, etc. ) e.g.
# custom resource session must use boto3.Session to do the override
my_west_session = boto3.Session(region_name = 'us-west-2')
my_east_session = boto3.Session(region_name = 'us-east-1')
backup_s3 = my_west_session.resource('s3')
video_s3 = my_east_session.resource('s3')
# you have two choices of create custom client session.
backup_s3c = my_west_session.client('s3')
video_s3c = boto3.client("s3", region_name = 'us-east-1')
Resource : This is the high-level service class recommended to be used. This allows you to tied particular AWS resources and passes it along, so you just use this abstraction than worry which target services are pointed to. As you notice from the session part, if you have a custom session, you just pass this abstract object than worrying about all custom regions,etc to pass along. Following is a complicated example E.g.
import boto3
my_west_session = boto3.Session(region_name = 'us-west-2')
my_east_session = boto3.Session(region_name = 'us-east-1')
backup_s3 = my_west_session.resource("s3")
video_s3 = my_east_session.resource("s3")
backup_bucket = backup_s3.Bucket('backupbucket')
video_bucket = video_s3.Bucket('videobucket')
# just pass the instantiated bucket object
def list_bucket_contents(bucket):
for object in bucket.objects.all():
print(object.key)
list_bucket_contents(backup_bucket)
list_bucket_contents(video_bucket)
Client is a low level class object. For each client call, you need to explicitly specify the targeting resources, the designated service target name must be pass long. You will lose the abstraction ability.
For example, if you only deal with the default session, this looks similar to boto3.resource.
import boto3
s3 = boto3.client('s3')
def list_bucket_contents(bucket_name):
for object in s3.list_objects_v2(Bucket=bucket_name) :
print(object.key)
list_bucket_contents('Mybucket')
However, if you want to list objects from a bucket in different regions, you need to specify the explicit bucket parameter required for the client.
import boto3
backup_s3 = my_west_session.client('s3',region_name = 'us-west-2')
video_s3 = my_east_session.client('s3',region_name = 'us-east-1')
# you must pass boto3.Session.client and the bucket name
def list_bucket_contents(s3session, bucket_name):
response = s3session.list_objects_v2(Bucket=bucket_name)
if 'Contents' in response:
for obj in response['Contents']:
print(obj['key'])
list_bucket_contents(backup_s3, 'backupbucket')
list_bucket_contents(video_s3 , 'videobucket')
I'd suggest to use http://docopt.org/. There's a scala-port but the Java implementation https://github.com/docopt/docopt.java works just fine and seems to be better maintained. Here's an example:
import org.docopt.Docopt
import scala.collection.JavaConversions._
import scala.collection.JavaConverters._
val doc =
"""
Usage: my_program [options] <input>
Options:
--sorted fancy sorting
""".stripMargin.trim
//def args = "--sorted test.dat".split(" ").toList
var results = new Docopt(doc).
parse(args()).
map {case(key, value)=>key ->value.toString}
val inputFile = new File(results("<input>"))
val sorted = results("--sorted").toBoolean
jQuery is not the same as an array. If you want to append something at the end of a jQuery object, use:
$('#fruit').append(veggies);
or to append it to the end of a form value like in your example:
$('#fruit').val($('#fruit').val()+veggies);
In your case, fruitvegbasket
is a string that contains the current value of #fruit
, not an array.
jQuery (jquery.com) allows for DOM manipulation, and the specific function you called val()
returns the value
attribute of an input
element as a string. You can't push something onto a string.
You can run another migration, just for the index:
class AddIndexToTable < ActiveRecord::Migration
def change
add_index :table, :user_id
end
end
After Xcode 7, the bitcode option will be enabled by default. If your library was compiled without bitcode, but the bitcode option is enabled in your project settings, you can:
And the Library Build Settings to remove the warnings.
For more information, go to documentation of bitcode in developer library.
And WWDC 2015 Session 102: "Platforms State of the Union"
It's not a programmatic solution but you can run
java -verbose:class ....
and the JVM will dump out what it's loading, and from where.
[Opened /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
[Opened /usr/java/j2sdk1.4.1/jre/lib/sunrsasign.jar]
[Opened /usr/java/j2sdk1.4.1/jre/lib/jsse.jar]
[Opened /usr/java/j2sdk1.4.1/jre/lib/jce.jar]
[Opened /usr/java/j2sdk1.4.1/jre/lib/charsets.jar]
[Loaded java.lang.Object from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
[Loaded java.io.Serializable from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
[Loaded java.lang.Comparable from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
[Loaded java.lang.CharSequence from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
[Loaded java.lang.String from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
See here for more details.
jsonb
in Postgres 9.4+You can use the same query as below, just with jsonb_array_elements()
.
But rather use the jsonb
"contains" operator @>
in combination with a matching GIN index on the expression data->'objects'
:
CREATE INDEX reports_data_gin_idx ON reports
USING gin ((data->'objects') jsonb_path_ops);
SELECT * FROM reports WHERE data->'objects' @> '[{"src":"foo.png"}]';
Since the key objects
holds a JSON array, we need to match the structure in the search term and wrap the array element into square brackets, too. Drop the array brackets when searching a plain record.
More explanation and options:
json
in Postgres 9.3+Unnest the JSON array with the function json_array_elements()
in a lateral join in the FROM
clause and test for its elements:
SELECT data::text, obj
FROM reports r, json_array_elements(r.data#>'{objects}') obj
WHERE obj->>'src' = 'foo.png';
The CTE (WITH
query) just substitutes for a table reports
.
Or, equivalent for just a single level of nesting:
SELECT *
FROM reports r, json_array_elements(r.data->'objects') obj
WHERE obj->>'src' = 'foo.png';
->>
, ->
and #>
operators are explained in the manual.
Both queries use an implicit JOIN LATERAL
.
Closely related:
I had a similar situation recently where I needed to run multiple programs at the same time, redirect their outputs to separated log files and wait for them to finish and I ended up with something like that:
#!/bin/bash
# Add the full path processes to run to the array
PROCESSES_TO_RUN=("/home/joao/Code/test/prog_1/prog1" \
"/home/joao/Code/test/prog_2/prog2")
# You can keep adding processes to the array...
for i in ${PROCESSES_TO_RUN[@]}; do
${i%/*}/./${i##*/} > ${i}.log 2>&1 &
# ${i%/*} -> Get folder name until the /
# ${i##*/} -> Get the filename after the /
done
# Wait for the processes to finish
wait
Source: http://joaoperibeiro.com/execute-multiple-programs-and-redirect-their-outputs-linux/
You can override onViewCreated() which is called right after all views had been inflated. It's the right place to fill in your Fragment's member View
variables. Here's an example:
class GalleryFragment extends Fragment {
private Gallery gallery;
(...)
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
gallery = (Gallery) view.findViewById(R.id.gallery);
gallery.setAdapter(adapter);
super.onViewCreated(view, savedInstanceState);
}
}
Yes this is possible. kizzie is correct with the session_start();
having to go first.
another observation I made is that you need to filter your form data using:
strip_tags($value);
and/or
stripslashes($value);
It depends on the context.
final
class or method, the C# equivalent is sealed
.final
field, the C# equivalent is readonly
.final
local variable or method parameter, there's no direct C# equivalent.The error you gave is due to the fact that in python, dictionary keys must be immutable types (if key can change, there will be problems), and list is a mutable type.
Your error says that you try to use a list as dictionary key, you'll have to change your list into tuples if you want to put them as keys in your dictionary.
According to the python doc :
The only types of values not acceptable as keys are values containing lists or dictionaries or other mutable types that are compared by value rather than by object identity, the reason being that the efficient implementation of dictionaries requires a key’s hash value to remain constant
I just clean the arraylist , try values.clear();
values = new ArrayList<String>();
values.clear();
ArrayAdapter <String> adapter;
adapter = new ArrayAdapter<String>(this, R.layout.list,android.R.id.text1, values);
lista.setAdapter(adapter);
The rvest
along with xml2
is another popular package for parsing html web pages.
library(rvest)
theurl <- "http://en.wikipedia.org/wiki/Brazil_national_football_team"
file<-read_html(theurl)
tables<-html_nodes(file, "table")
table1 <- html_table(tables[4], fill = TRUE)
The syntax is easier to use than the xml
package and for most web pages the package provides all of the options ones needs.
There's no easy way to do this, but something like this will work:
SELECT ET.TrainingID,
ET.CompletedDate,
ET.Notes
FROM
HR_EmployeeTrainings ET
inner join
(
select TrainingID, Max(CompletedDate) as CompletedDate
FROM HR_EmployeeTrainings
WHERE (ET.AvantiRecID IS NULL OR ET.AvantiRecID = @avantiRecID)
GROUP BY AvantiRecID, TrainingID
) ET2
on ET.TrainingID = ET2.TrainingID
and ET.CompletedDate = ET2.CompletedDate
Using numpy (highly recommended), you would do:
from numpy import (array, dot, arccos, clip)
from numpy.linalg import norm
u = array([1.,2,3,4])
v = ...
c = dot(u,v)/norm(u)/norm(v) # -> cosine of the angle
angle = arccos(clip(c, -1, 1)) # if you really want the angle
Don't you try it with that program? It'll goto finally block and executing the finally block, but, the exception won't be handled. But, that exception can be overruled in the finally block!
.c_str()
returns a const char*
. If you need a mutable version, you will need to produce a copy yourself.
You can use a text field to store dates within SQLite
.
Storing dates in UTC format, the default if you use datetime('now')
(yyyy-MM-dd HH:mm:ss)
will then allow sorting by the date column.
Retrieving dates as strings from SQLite
you can then format/convert them as required into local regionalised formats using the Calendar or the android.text.format.DateUtils.formatDateTime
method.
Here's a regionalised formatter method I use;
public static String formatDateTime(Context context, String timeToFormat) {
String finalDateTime = "";
SimpleDateFormat iso8601Format = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
Date date = null;
if (timeToFormat != null) {
try {
date = iso8601Format.parse(timeToFormat);
} catch (ParseException e) {
date = null;
}
if (date != null) {
long when = date.getTime();
int flags = 0;
flags |= android.text.format.DateUtils.FORMAT_SHOW_TIME;
flags |= android.text.format.DateUtils.FORMAT_SHOW_DATE;
flags |= android.text.format.DateUtils.FORMAT_ABBREV_MONTH;
flags |= android.text.format.DateUtils.FORMAT_SHOW_YEAR;
finalDateTime = android.text.format.DateUtils.formatDateTime(context,
when + TimeZone.getDefault().getOffset(when), flags);
}
}
return finalDateTime;
}
When you get a NULL value from a database, the value returned is DBNull.Value on which case, you can simply call .ToString()
and it will return ""
Example:
reader["Column"].ToString()
Gets you ""
if the value returned is DBNull.Value
If the scenario is not always a database, then I'd go for an Extension method:
public static class Extensions
{
public static string EmptyIfNull(this object value)
{
if (value == null)
return "";
return value.ToString();
}
}
Usage:
string someVar = null;
someVar.EmptyIfNull();
Here you can use my method for generating Random String
protected String getSaltString() {
String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder salt = new StringBuilder();
Random rnd = new Random();
while (salt.length() < 18) { // length of the random string.
int index = (int) (rnd.nextFloat() * SALTCHARS.length());
salt.append(SALTCHARS.charAt(index));
}
String saltStr = salt.toString();
return saltStr;
}
The above method from my bag using to generate a salt string for login purpose.
Real Time Output Issue resolved:
I encountered a similar issue in Python, while capturing the real time output from C program. I added fflush(stdout);
in my C code. It worked for me. Here is the code.
C program:
#include <stdio.h>
void main()
{
int count = 1;
while (1)
{
printf(" Count %d\n", count++);
fflush(stdout);
sleep(1);
}
}
Python program:
#!/usr/bin/python
import os, sys
import subprocess
procExe = subprocess.Popen(".//count", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
while procExe.poll() is None:
line = procExe.stdout.readline()
print("Print:" + line)
Output:
Print: Count 1
Print: Count 2
Print: Count 3
Have you tried using Timestamp.valueOf(String)
? It looks like it should do almost exactly what you want - you just need to change the separator between your date and time to a space, and the ones between hours and minutes, and minutes and hours, to colons:
import java.sql.*;
public class Test {
public static void main(String[] args) {
String text = "2011-10-02 18:48:05.123456";
Timestamp ts = Timestamp.valueOf(text);
System.out.println(ts.getNanos());
}
}
Assuming you've already validated the string length, this will convert to the right format:
static String convertSeparators(String input) {
char[] chars = input.toCharArray();
chars[10] = ' ';
chars[13] = ':';
chars[16] = ':';
return new String(chars);
}
Alternatively, parse down to milliseconds by taking a substring and using Joda Time or SimpleDateFormat
(I vastly prefer Joda Time, but your mileage may vary). Then take the remainder of the string as another string and parse it with Integer.parseInt
. You can then combine the values pretty easily:
Date date = parseDateFromFirstPart();
int micros = parseJustLastThreeDigits();
Timestamp ts = new Timestamp(date.getTime());
ts.setNanos(ts.getNanos() + micros * 1000);
It appears that you can throw only RuntimeException from the method orElseThrow
. Otherwise you will get an error message like MyException cannot be converted to java.lang.RuntimeException
Update:- This was an issue with an older version of JDK. I don't see this issue with the latest versions.
The problem still not resolved after remove the '.', then it start points the error to my folder. As i added this folder first time then i restarted the PyCharm and it automatically resolved the issue
To answer your additional question how disable views caching:
You can do this by automatically delete the files in the folder for each request with the command php artisan view:clear
mentioned by DilipGurung. Here is an example Middleware class from https://stackoverflow.com/a/38598434/2311074
<?php
namespace App\Http\Middleware;
use Artisan;
use Closure;
class ClearViewCache
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (env('APP_DEBUG') || env('APP_ENV') === 'local')
Artisan::call('view:clear');
return $next($request);
}
}
However you may note that Larevel will recompile the files in the /app/storage/views folder whenever the time on the views files is earlier than the time on the PHP blade files for the layout. THus, I cannot really think of a scenario where this would be necessary to do.
This is just a suggestion, it might not work and I'm prepared to be called on this.
This will generate false positives, but hopefully not false negatives.
Resize both of the images so that they are the same size (I assume that the ratios of widths to lengths are the same in both images).
Compress a bitmap of both images with a lossless compression algorithm (e.g. gzip).
Find pairs of files that have similar file sizes. For instance, you could just sort every pair of files you have by how similar the file sizes are and retrieve the top X.
As I said, this will definitely generate false positives, but hopefully not false negatives. You can implement this in five minutes, whereas the Porikil et. al. would probably require extensive work.
Your description is a little confusing.
Generally speaking, though some C++ implementations have mechanisms for it, you're not supposed to ask about the type. Instead, you are supposed to do a dynamic_cast on the pointer to A. What this will do is that at runtime, the actual contents of the pointer to A will be checked. If you have a B, you'll get your pointer to B. Otherwise, you'll get an exception or null.
The number of arguments is $#
Search for it on this page to learn more: http://tldp.org/LDP/abs/html/internalvariables.html#ARGLIST
On Windows 7 for example, the following set of commands/operations could be used.
Create an personal environment variable, double backslashes are mandatory:
%NPM_HOME%
C:\\SomeFolder\\SubFolder\\
Now, set the config values to the new folders (examplary file names):
npm config set prefix "%NPM_HOME%\\npm"
npm config set cache "%NPM_HOME%\\npm-cache"
npm config set tmp "%NPM_HOME%\\temp"
Optionally, you can purge the contents of the original folders before the config is changed.
Delete the npm-cache npm cache clear
List the npm modules npm -g ls
Delete the npm modules
npm -g rm name_of_package1 name_of_package2
In the event the method you're calling is private, or called from one location, try
return new Object[]{value1, value2};
The caller looks like:
Object[] temp=myMethod(parameters);
Type1 value1=(Type1)temp[0]; //For code clarity: temp[0] is not descriptive
Type2 value2=(Type2)temp[1];
The Pair example by David Hanak has no syntactic benefit, and is limited to two values.
return new Pair<Type1,Type2>(value1, value2);
And the caller looks like:
Pair<Type1, Type2> temp=myMethod(parameters);
Type1 value1=temp.a; //For code clarity: temp.a is not descriptive
Type2 value2=temp.b;
<div *ngIf="currentStatus !== ('status1' || 'status2' || 'status3' || 'status4')">
Depending on the format of your new row, you might use tibble::add_row
if your new row is simple and can specified in "value-pairs". Or you could use dplyr::bind_rows
, "an efficient implementation of the common pattern of do.call(rbind, dfs)".
The two methods are 100% equivalent.
I’m not sure why Microsoft felt the need to include this extra Clear
method but since it’s there, I recommend using it, as it clearly expresses its purpose.
When you install Python, it will not overwrite other installs of other major versions. So installing Python 2.5.x will not overwrite Python 2.6.x, although installing 2.6.6 will overwrite 2.6.5.
So you can just install it. Then you call the Python version you want. For example:
C:\Python2.5\Python.exe
for Python 2.5 on windows and
C:\Python2.6\Python.exe
for Python 2.6 on windows, or
/usr/local/bin/python-2.5
or
/usr/local/bin/python-2.6
on Windows Unix (including Linux and OS X).
When you install on Unix (including Linux and OS X) you will get a generic python
command installed, which will be the last one you installed. This is mostly not a problem as most scripts will explicitly call /usr/local/bin/python2.5 or something just to protect against that. But if you don't want to do that, and you probably don't you can install it like this:
./configure
make
sudo make altinstall
Note the "altinstall" that means it will install it, but it will not replace the python
command.
On Windows you don't get a global python
command as far as I know so that's not an issue.
In iOS7 I found that if I had a View inside a UIScrollView on a FreeForm-sized ViewController it would not scroll in the app, no matter what I did. I played around and found the following seemed to work, which uses no FreeForms:
Insert a UIScrollView inside the main View of a ViewController
Set the Autolayout constraints on the ScrollView as appropriate. For me I used 0 to Top Layout guide and 0 to Bottom layout Guide
Inside the ScrollView, place a Container View. Set its height to whatever you want (e.g. 1000)
Add a Height constraint (1000) to the Container so it doesn't resize. The bottom will be past the end of the form.
Add the line [self.scrollView setContentSize:CGSizeMake(320, 1000)]; to the ViewController that contains the scrollView (which you've hooked up as a IBOutlet)
The ViewController (automatically added) that is associated with the Container will have the desired height (1000) in Interface Builder and will also scroll properly in the original view controller. You can now use the container's ViewController to layout your controls.
Your problem is simple:
names = {'John', 'Joe', 'Steve'}
for names = 1, 3 do
print (names)
end
This code first declares a global variable called names
. Then, you start a for loop. The for loop declares a local variable that just happens to be called names
too; the fact that a variable had previously been defined with names
is entirely irrelevant. Any use of names
inside the for loop will refer to the local one, not the global one.
The for loop says that the inner part of the loop will be called with names = 1
, then names = 2
, and finally names = 3
. The for loop declares a counter that counts from the first number to the last, and it will call the inner code once for each value it counts.
What you actually wanted was something like this:
names = {'John', 'Joe', 'Steve'}
for nameCount = 1, 3 do
print (names[nameCount])
end
The [] syntax is how you access the members of a Lua table. Lua tables map "keys" to "values". Your array automatically creates keys of integer type, which increase. So the key associated with "Joe" in the table is 2 (Lua indices always start at 1).
Therefore, you need a for loop that counts from 1 to 3, which you get. You use the count variable to access the element from the table.
However, this has a flaw. What happens if you remove one of the elements from the list?
names = {'John', 'Joe'}
for nameCount = 1, 3 do
print (names[nameCount])
end
Now, we get John Joe nil
, because attempting to access values from a table that don't exist results in nil
. To prevent this, we need to count from 1 to the length of the table:
names = {'John', 'Joe'}
for nameCount = 1, #names do
print (names[nameCount])
end
The #
is the length operator. It works on tables and strings, returning the length of either. Now, no matter how large or small names
gets, this will always work.
However, there is a more convenient way to iterate through an array of items:
names = {'John', 'Joe', 'Steve'}
for i, name in ipairs(names) do
print (name)
end
ipairs
is a Lua standard function that iterates over a list. This style of for
loop, the iterator for loop, uses this kind of iterator function. The i
value is the index of the entry in the array. The name
value is the value at that index. So it basically does a lot of grunt work for you.
$("#your-modal-id").modal('hide');
Running this call via class ($(".my-modal"))
won't work.
may be problem in data binding in export excel . check that data properly bin to a gridview or not.
Use this code for export grid view in excel sheet and note that you must add iTextSharp dll in you project.
protected void btnExportExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
// Re-Bind data to GridView
using (CompMSEntities1 CompObj = new CompMSEntities1())
{
Start = Convert.ToDateTime(txtStart.Text);
End = Convert.ToDateTime(txtEnd.Text);
GridViewSummaryReportCategory.DataSource = CompObj.SP_Category_Summary(Start, End);
SP_Category_Summary_Result obj1 = new SP_Category_Summary_Result();
GridView1.DataBind();
GridView1.Visible = true;
ExportTable.Visible = true;
}
//Change the Header Row back to white color
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
GridView1.Style.Add(" font-size", "10px");
//Apply style to Individual Cells
GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
GGridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[3].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[4].Style.Add("background-color", "green");
for (int i = 1; i < GridView1.Rows.Count; i++)
{
GridViewRow row = GridView1.Rows[i];
//Change Color back to white
row.BackColor = System.Drawing.Color.White;
//Apply text style to each Row
// row.Attributes.Add("class", "textmode");
//Apply style to Individual Cells of Alternating Row
if (i % 2 != 0)
{
row.Cells[0].Style.Add("background-color", "#C2D69B");
row.Cells[1].Style.Add("background-color", "#C2D69B");
row.Cells[2].Style.Add("background-color", "#C2D69B");
row.Cells[3].Style.Add("background-color", "#C2D69B");
row.Cells[4].Style.Add("background-color", "#C2D69B");
}
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = @"<style> .textmode { mso-number-format:\@; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
You should have the file at the same location as that of the Python files you are trying to import. Also 'from file import function' is enough.
In VB code, when trying to submit an INSERT
query, you must submit a double query in the same 'executenonquery' like this:
sqlQuery = "SET IDENTITY_INSERT dbo.TheTable ON; INSERT INTO dbo.TheTable (Col1, COl2) VALUES (Val1, Val2); SET IDENTITY_INSERT dbo.TheTable OFF;"
I used a ;
separator instead of a GO.
Works for me. Late but efficient!
Very very easy: [1,2,3]
A list is like a column.
1
2
3
If you want a list like a row, double corchete:
[[1, 2, 3]] ---> 1, 2, 3
and
[[1, 2, 3], [4, 5, 6]] ---> 1, 2, 3
4, 5, 6
Finally:
np.savetxt("file", [['r1c1', 'r1c2'], ['r2c1', 'r2c2']], delimiter=';', fmt='%s')
Note, the comma between square brackets, inner list are elements of the outer list
You can do this easier.
Source: http://www.tutorialspoint.com/android/android_loading_spinner.htm
It helped me.
Layout:
<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" />
After defining it in xml, you have to get its reference in java file through ProgressBar class. Its syntax is given below:
private ProgressBar spinner;
spinner = (ProgressBar)findViewById(R.id.progressBar1);
After that you can make its disappear , and bring it back when needed through setVisibility Method. Its syntax is given below:
spinner.setVisibility(View.GONE);
spinner.setVisibility(View.VISIBLE);
<input type = "checkbox" name = "checkbox1" /> <label> Check to say hi.</label>
From the Controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(FormCollection fc)
{
var s = fc["checkbox1"];
if (s == "on")
{
string x = "Hi";
}
}
Use Thread.sleep(2000); //2000 for 2 seconds
I usually overload my method with IEnumerable and IList in this situation.
public static IEnumerable<T> Method<T>( this IList<T> source ){... }
public static IEnumerable<T> Method<T>( this IEnumerable<T> source )
{
/*input checks on source parameter here*/
return Method( source.ToList() );
}
I take care to explain in the summary comments of the methods that calling IEnumerable will perform a .ToList().
The programmer can choose to .ToList() at a higher level if multiple operations are being concatenated and then call the IList overload or let my IEnumerable overload take care of that.
If you are using JQuery with Form plugin, you can use:
$('#myForm').ajaxSubmit({
headers: {
"foo": "bar"
}
});
I think this comes closest to what you wish:
(From IntelliJ IDEA Q&A for Eclipse Users):
The above can be combined with a recently introduced option in Compiler settings to get a view very similar to that of Eclipse.
Things to do:
Switch to 'Problems' view in the Project pane:
Enable the setting to compile the project automatically :
Finally, look at the Problems view:
Here is a comparison of what the same project (with a compilation error) looks like in Intellij IDEA 13.xx and Eclipse Kepler:
Relevant Links:
The maven project shown above : https://github.com/ajorpheus/CompileTimeErrors
FAQ For 'Eclipse Mode' / 'Automatically Compile' a project : http://devnet.jetbrains.com/docs/DOC-1122
I've seen at lot of companies are using MongoDB for realtime analytics from application logs. Its schema-freeness really fits for application logs, where record schema tends to change time-to-time. Also, its Capped Collection feature is useful because it automatically purges old data to keep the data fit into the memory.
That is one area I really think MongoDB fits for, but MySQL/PostgreSQL is more recommended in general. There're a lot of documentations and developer resources on the web, as well as their functionality and robustness.
That's an easy one:
[aView convertPoint:localPosition toView:nil];
... converts a point in local coordinate space to window coordinates. You can use this method to calculate a view's origin in window space like this:
[aView.superview convertPoint:aView.frame.origin toView:nil];
2014 Edit: Looking at the popularity of Matt__C's comment it seems reasonable to point out that the coordinates...
Are you looking at something like this, below is tested in SQL Server 2005
SELECT * FROM sys.check_constraints WHERE
object_id = OBJECT_ID(N'[dbo].[CK_accounts]') AND
parent_object_id = OBJECT_ID(N'[dbo]. [accounts]')
import os
os.path.exists(path) # Returns whether the path (directory or file) exists or not
os.path.isfile(path) # Returns whether the file exists or not
You can use a <div>
to cover the scrollbar if you really want it to disappear.
Although it won't work on IE6, modern browsers do let you put a <div>
on top of it.
Here's something I found:
:pingtheserver
ping %input% | find "Reply" > nul
if not errorlevel 1 (
echo server is online, up and running.
) else (
echo host has been taken down wait 3 seconds to refresh
ping 1.1.1.1 -n 1 -w 3000 >NUL
goto :pingtheserver
)
Note that ping 1.1.1.1 -n -w 1000 >NUL
will wait 1 second but only works when connected to a network
If you are interested in ImageButton you can try this simple thing :
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:drawable/ic_button"
android:background="?attr/selectableItemBackgroundBorderless"
/>
XML file saved at res/values/colors.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="opaque_red">#f00</color>
<color name="translucent_red">#80ff0000</color>
</resources>
This application code retrieves the color resource:
Resources res = getResources();
int color = res.getColor(R.color.opaque_red);
This layout XML applies the color to an attribute:
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="@color/translucent_red"
android:text="Hello"/>
If your using Office 2016 or later, or Office 365, there is a new function that acts similarly to a CASE function called IFS. Here's the description of the function from Microsoft's documentation:
The IFS function checks whether one or more conditions are met, and returns a value that corresponds to the first TRUE condition. IFS can take the place of multiple nested IF statements, and is much easier to read with multiple conditions.
An example of usage follows:
=IFS(A2>89,"A",A2>79,"B",A2>69,"C",A2>59,"D",TRUE,"F")
You can even specify a default result:
To specify a default result, enter TRUE for your final logical_test argument. If none of the other conditions are met, the corresponding value will be returned.
The default result feature is included in the example shown above.
You can read more about it on Microsoft's Support Documentation
If you need to return a JSON object using a String, then the following should work:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.ResponseEntity;
...
@RestController
@RequestMapping("/student")
public class StudentController {
@GetMapping
@RequestMapping("/")
public ResponseEntity<JsonNode> get() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
JsonNode json = mapper.readTree("{\"id\": \"132\", \"name\": \"Alice\"}");
return ResponseEntity.ok(json);
}
...
}
If you're just starting out learning javascript & don't want to spend time creating an entire webpage just for embedding test scripts, just open Dev Tools in a new tab in Chrome Browser, and click on Console
.
Then type out some test scripts: eg.
console.log('Aha!')
Then press Enter after every line (to submit for execution by Chrome)
or load your own "external script file":
document.createElement('script').src = 'http://example.com/file.js';
Then call your functions:
console.log(file.function('?????'))
Tested in Google Chrome 85.0.4183.121
I had been having issues where I was using
overflow: none;
But I knew CSS didn't really like it and it didn’t work 100% for how I wanted it to.
However, this is a perfect solution as none of my content is supposed to be larger than intended and this has fixed the issue I had.
overflow: auto;
So the problem must be with your JCE Unlimited Strength installation.
Be sure you overwrite the local_policy.jar
and US_export_policy.jar
in both your JDK's jdk1.6.0_25\jre\lib\security\
and in your JRE's lib\security\
folder.
In my case I would place the new .jars in:
C:\Program Files\Java\jdk1.6.0_25\jre\lib\security
and
C:\Program Files\Java\jre6\lib\security
If you are running Java 8 and you encounter this issue. Below steps should help!
Go to your JRE installation (e.g - jre1.8.0_181\lib\security\policy\unlimited) copy local_policy.jar and replace it with 'local_policy.jar' in your JDK installation directory (e.g - jdk1.8.0_141\jre\lib\security).
<td align="center" valign="center">textgoeshere</td>
Is the only correct answer imho, since your working with tables which is old functionality most common used for e-mail formatting. So your best bet is to not use just style but inline style and known table tags.
Yes you can use CASE
UPDATE table
SET columnB = CASE fieldA
WHEN columnA=1 THEN 'x'
WHEN columnA=2 THEN 'y'
ELSE 'z'
END
WHERE columnC = 1
calloc()
gives you a zero-initialized buffer, while malloc()
leaves the memory uninitialized.
For large allocations, most calloc
implementations under mainstream OSes will get known-zeroed pages from the OS (e.g. via POSIX mmap(MAP_ANONYMOUS)
or Windows VirtualAlloc
) so it doesn't need to write them in user-space. This is how normal malloc
gets more pages from the OS as well; calloc
just takes advantage of the OS's guarantee.
This means calloc
memory can still be "clean" and lazily-allocated, and copy-on-write mapped to a system-wide shared physical page of zeros. (Assuming a system with virtual memory.)
Some compilers even can optimize malloc + memset(0) into calloc for you, but you should use calloc explicitly if you want the memory to read as 0
.
If you aren't going to ever read memory before writing it, use malloc
so it can (potentially) give you dirty memory from its internal free list instead of getting new pages from the OS. (Or instead of zeroing a block of memory on the free list for a small allocation).
Embedded implementations of calloc
may leave it up to calloc
itself to zero memory if there's no OS, or it's not a fancy multi-user OS that zeros pages to stop information leaks between processes.
On embedded Linux, malloc could mmap(MAP_UNINITIALIZED|MAP_ANONYMOUS)
, which is only enabled for some embedded kernels because it's insecure on a multi-user system.
For a non ASP.NET control, i.e. HTML controls like div, table, td, tr
, etc. you need to first make them a server control, assign an ID, and then assign a property from server code:
<head>
<style type="text/css">
.top_rounded
{
height: 75px;
width: 75px;
border: 2px solid;
border-radius: 5px;
-moz-border-radius: 5px; /* Firefox 3.6 and earlier */
border-color: #9c1c1f;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div runat="server" id="myDiv">This is my div</div>
</form>
</body>
myDiv.Attributes.Add("class", "top_rounded");
This is the simplest wat to get the File object to which a certain URL object is pointing at:
File file=new File(url.toURI());
Now, for your concrete questions:
- finding all resources in the META-INF "directory":
You can indeed get the File object pointing to this URL
Enumeration<URL> en=getClass().getClassLoader().getResources("META-INF");
if (en.hasMoreElements()) {
URL metaInf=en.nextElement();
File fileMetaInf=new File(metaInf.toURI());
File[] files=fileMetaInf.listFiles();
//or
String[] filenames=fileMetaInf.list();
}
- all resources named bla.xml (recursivly)
In this case, you'll have to do some custom code. Here is a dummy example:
final List<File> foundFiles=new ArrayList<File>();
FileFilter customFilter=new FileFilter() {
@Override
public boolean accept(File pathname) {
if(pathname.isDirectory()) {
pathname.listFiles(this);
}
if(pathname.getName().endsWith("bla.xml")) {
foundFiles.add(pathname);
return true;
}
return false;
}
};
//rootFolder here represents a File Object pointing the root forlder of your search
rootFolder.listFiles(customFilter);
When the code is run, you'll get all the found ocurrences at the foundFiles
List.
An Anonymous Inner Class is used to create an object that will never be referenced again. It has no name and is declared and created in the same statement.
This is used where you would normally use an object's variable. You replace the variable with the new
keyword, a call to a constructor and the class definition inside {
and }
.
When writing a Threaded Program in Java, it would usually look like this
ThreadClass task = new ThreadClass();
Thread runner = new Thread(task);
runner.start();
The ThreadClass
used here would be user defined. This class will implement the Runnable
interface which is required for creating threads. In the ThreadClass
the run()
method (only method in Runnable
) needs to be implemented as well.
It is clear that getting rid of ThreadClass
would be more efficient and that's exactly why Anonymous Inner Classes exist.
Look at the following code
Thread runner = new Thread(new Runnable() {
public void run() {
//Thread does it's work here
}
});
runner.start();
This code replaces the reference made to task
in the top most example. Rather than having a separate class, the Anonymous Inner Class inside the Thread()
constructor returns an unnamed object that implements the Runnable
interface and overrides the run()
method. The method run()
would include statements inside that do the work required by the thread.
Answering the question on whether Anonymous Inner Classes is one of the advantages of Java, I would have to say that I'm not quite sure as I am not familiar with many programming languages at the moment. But what I can say is it is definitely a quicker and easier method of coding.
References: Sams Teach Yourself Java in 21 Days Seventh Edition
This is working for me, Writing(creating as well) and/or appending content in the same mode.
$fp = fopen("MyFile.txt", "a+")
On Windows 10
insert at beggining this:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
Strange, but it works for me! (Together with input()
at the end, of course)
redsquare's solution is the right answer.
But as an IN-THEORY solution you can write a function which is selecting the elements classed by .visibilityCheck
(not all visible elements) and check their visibility
property value; if true
then do something.
Afterward, the function should be performed periodically using the setInterval()
function. You can stop the timer using the clearInterval()
upon successful call-out.
Here's an example:
function foo() {
$('.visibilityCheck').each(function() {
if ($(this).is(':visible')){
// do something
}
});
}
window.setInterval(foo, 100);
You can also perform some performance improvements on it, however, the solution is basically absurd to be used in action. So...
Probably @droidev approach is the correct one, but I just want to publish something a little bit different, which does basically the same job and doesn't require extension of the LayoutManager.
A NOTE here - this is gonna work well if your item (the one that you want to scroll on the top of the list) is visible on the screen and you just want to scroll it to the top automatically. It is useful when the last item in your list has some action, which adds new items in the same list and you want to focus the user on the new added items:
int recyclerViewTop = recyclerView.getTop();
int positionTop = recyclerView.findViewHolderForAdapterPosition(positionToScroll) != null ? recyclerView.findViewHolderForAdapterPosition(positionToScroll).itemView.getTop() : 200;
final int calcOffset = positionTop - recyclerViewTop;
//then the actual scroll is gonna happen with (x offset = 0) and (y offset = calcOffset)
recyclerView.scrollBy(0, offset);
The idea is simple: 1. We need to get the top coordinate of the recyclerview element; 2. We need to get the top coordinate of the view item that we want to scroll to the top; 3. At the end with the calculated offset we need to do
recyclerView.scrollBy(0, offset);
200 is just example hard coded integer value that you can use if the viewholder item doesn't exist, because that is possible as well.
function my_get_tags_sitemap(){
if ( !function_exists('wp_tag_cloud') || get_option('cb2_noposttags')) return;
$unlinkTags = get_option('cb2_unlinkTags');
echo '<div class="tags"><h2>Tags</h2>';
$ret = []; // here you need to add array which you call inside implode function
if($unlinkTags)
{
$tags = get_tags();
foreach ($tags as $tag){
$ret[]= $tag->name;
}
//ERROR OCCURS HERE
echo implode(', ', $ret);
}
else
{
wp_tag_cloud('separator=, &smallest=11&largest=11');
}
echo '</div>';
}
Your list:
List<MyCustomObject> myCustomObjectList;
Your JSONArray:
// Don't need to loop through it. JSONArray constructor do it for you.
new JSONArray(myCustomObjectList)
Your response:
return new JSONObject().put("yourCustomKey", new JSONArray(myCustomObjectList));
Your post/put http body request would be like this:
{
"yourCustomKey: [
{
"myCustomObjectProperty": 1
},
{
"myCustomObjectProperty": 2
}
]
}
import os
import glob
path = 'c:\\'
extension = 'csv'
os.chdir(path)
result = glob.glob('*.{}'.format(extension))
print(result)
This is a function we are using in our application and it is working fine.
delete cookie: No argument method
function clearListCookies()
{
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
{
var spcook = cookies[i].split("=");
deleteCookie(spcook[0]);
}
function deleteCookie(cookiename)
{
var d = new Date();
d.setDate(d.getDate() - 1);
var expires = ";expires="+d;
var name=cookiename;
//alert(name);
var value="";
document.cookie = name + "=" + value + expires + "; path=/acc/html";
}
window.location = ""; // TO REFRESH THE PAGE
}
Edit: This will delete the cookie by setting it to yesterday's date.
It appears that the issue has to do (at least in mine and a few others) with invalid (corrupt?) innodb log files. Generally speaking, they simply need to be recreated.
Here are solutions, most of which require a restart of mysql.
Just translate Jojodmo code to Swift:
class InAppPurchaseManager: NSObject , SKProductsRequestDelegate, SKPaymentTransactionObserver{
//If you have more than one in-app purchase, you can define both of
//of them here. So, for example, you could define both kRemoveAdsProductIdentifier
//and kBuyCurrencyProductIdentifier with their respective product ids
//
//for this example, we will only use one product
let kRemoveAdsProductIdentifier = "put your product id (the one that we just made in iTunesConnect) in here"
@IBAction func tapsRemoveAds() {
NSLog("User requests to remove ads")
if SKPaymentQueue.canMakePayments() {
NSLog("User can make payments")
//If you have more than one in-app purchase, and would like
//to have the user purchase a different product, simply define
//another function and replace kRemoveAdsProductIdentifier with
//the identifier for the other product
let set : Set<String> = [kRemoveAdsProductIdentifier]
let productsRequest = SKProductsRequest(productIdentifiers: set)
productsRequest.delegate = self
productsRequest.start()
}
else {
NSLog("User cannot make payments due to parental controls")
//this is called the user cannot make payments, most likely due to parental controls
}
}
func purchase(product : SKProduct) {
let payment = SKPayment(product: product)
SKPaymentQueue.defaultQueue().addTransactionObserver(self)
SKPaymentQueue.defaultQueue().addPayment(payment)
}
func restore() {
//this is called when the user restores purchases, you should hook this up to a button
SKPaymentQueue.defaultQueue().addTransactionObserver(self)
SKPaymentQueue.defaultQueue().restoreCompletedTransactions()
}
func doRemoveAds() {
//TODO: implement
}
/////////////////////////////////////////////////
//////////////// store delegate /////////////////
/////////////////////////////////////////////////
// MARK: - store delegate -
func productsRequest(request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) {
if let validProduct = response.products.first {
NSLog("Products Available!")
self.purchase(validProduct)
}
else {
NSLog("No products available")
//this is called if your product id is not valid, this shouldn't be called unless that happens.
}
}
func paymentQueueRestoreCompletedTransactionsFinished(queue: SKPaymentQueue) {
NSLog("received restored transactions: \(queue.transactions.count)")
for transaction in queue.transactions {
if transaction.transactionState == .Restored {
//called when the user successfully restores a purchase
NSLog("Transaction state -> Restored")
//if you have more than one in-app purchase product,
//you restore the correct product for the identifier.
//For example, you could use
//if(productID == kRemoveAdsProductIdentifier)
//to get the product identifier for the
//restored purchases, you can use
//
//NSString *productID = transaction.payment.productIdentifier;
self.doRemoveAds()
SKPaymentQueue.defaultQueue().finishTransaction(transaction)
break;
}
}
}
func paymentQueue(queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
for transaction in transactions {
switch transaction.transactionState {
case .Purchasing: NSLog("Transaction state -> Purchasing")
//called when the user is in the process of purchasing, do not add any of your own code here.
case .Purchased:
//this is called when the user has successfully purchased the package (Cha-Ching!)
self.doRemoveAds() //you can add your code for what you want to happen when the user buys the purchase here, for this tutorial we use removing ads
SKPaymentQueue.defaultQueue().finishTransaction(transaction)
NSLog("Transaction state -> Purchased")
case .Restored:
NSLog("Transaction state -> Restored")
//add the same code as you did from SKPaymentTransactionStatePurchased here
SKPaymentQueue.defaultQueue().finishTransaction(transaction)
case .Failed:
//called when the transaction does not finish
if transaction.error?.code == SKErrorPaymentCancelled {
NSLog("Transaction state -> Cancelled")
//the user cancelled the payment ;(
}
SKPaymentQueue.defaultQueue().finishTransaction(transaction)
case .Deferred:
// The transaction is in the queue, but its final status is pending external action.
NSLog("Transaction state -> Deferred")
}
}
}
}
Oh, your traceback gave it away: you have a version conflict. You have installed some old version of sqlite in your local dist-packages directory when you already have sqlite3 included in your python2.6 distribution and don't need and probably can't use the old sqlite version. First try:
$ python -c "import sqlite3"
and if that doesn't give you an error, uninstall your dist-package:
easy_install -mxN sqlite
and then import sqlite3
in your code instead and have fun.
Quote from Jeff Handley's Blog Post on Validation Objects and Properties with Validator:
When validating an object, the following process is applied in Validator.ValidateObject:
- Validate property-level attributes
- If any validators are invalid, abort validation returning the failure(s)
- Validate the object-level attributes
- If any validators are invalid, abort validation returning the failure(s)
- If on the desktop framework and the object implements IValidatableObject, then call its Validate method and return any failure(s)
This indicates that what you are attempting to do won't work out-of-the-box because the validation will abort at step #2. You could try to create attributes that inherit from the built-in ones and specifically check for the presence of an enabled property (via an interface) before performing their normal validation. Alternatively, you could put all of the logic for validating the entity in the Validate
method.
You also could take a look a the exact implemenation of Validator
class here
The log file will be where the configuration file (usually /etc/redis/redis.conf
) says it is :)
By default, logfile stdout
which probably isn't what you are looking for. If redis is running daemonized, then that log configuration means logs will be sent to /dev/null
, i.e. discarded.
Summary: set logfile /path/to/my/log/file.log
in your config and redis logs will be written to that file.
You can even set the prof. pic size to its high resolution that is '1080x1080'
replace "150x150" with 1080x1080 and remove /vp/ from the link.
I use
android:screenOrientation="nosensor"
It is helpful if you do not want to support up side down portrait mode.
$('#example').DataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "../admin/ajax/loadtransajax.php",
"fnServerParams": function (aoData) {
// Initialize your variables here
// I have assign the textbox value for "text_min_val"
var min_val = $("#min").val(); //push to the aoData
aoData.push({name: "text_min_val", value:min_val});
},
"fnCreatedRow": function (nRow, aData, iDataIndex) {
$(nRow).attr('id', 'tr_' + aData[0]);
$(nRow).attr('name', 'tr_' + aData[0]);
$(nRow).attr('min', 'tr_' + aData[0]);
$(nRow).attr('max', 'tr_' + aData[0]);
}
});
In loadtransajax.php
you may receive the get value:
if ($_GET['text_min_val']){
$sWhere = "WHERE (";
$sWhere .= " t_group_no LIKE '%" . mysql_real_escape_string($_GET['text_min_val']) . "%' ";
$sWhere .= ')';
}
<?php
$fh = fopen('filename.txt','r');
while ($line = fgets($fh)) {
// <... Do your work with the line ...>
// echo($line);
}
fclose($fh);
?>
This will give you a line by line read.. read the notes at php.net/fgets regarding the end of line issues with Macs.
Changing com.android.tools.build:gradle:2.2.0-beta1
to com.android.tools.build:gradle:2.1.2
fixed it for me.
My Android Studio version is 2.1.2, perhaps that's why
If it helps...
I use the PHP function number_format()
and the Narrow No-break Space ( 
). It is often used as an unambiguous thousands separator.
echo number_format(200000, 0, "", " ");
Because IE8 has some problems to render the Narrow No-break Space, I changed it for a SPAN
echo "<span class='number'>".number_format(200000, 0, "", "<span></span>")."</span>";
.number SPAN{
padding: 0 1px;
}
I stugeled to find out the boost version number in bash.
Ended up doing following, which stores the version code in a variable, supressing the errors. This uses the example from maxschlepzig in the comments of the accepted answer. (Can not comment, don't have 50 Rep)
I know this has been answered long time ago. But I couldn't find how to do it in bash anywhere. So I thought this might help someone with the same problem. Also this should work no matter where boost is installed, as long as the comiler can find it. And it will give you the version number that is acutally used by the comiler, when you have multiple versions installed.
{
VERS=$(echo -e '#include <boost/version.hpp>\nBOOST_VERSION' | gcc -s -x c++ -E - | grep "^[^#;]")
} &> /dev/null
While you can use the condition && if-true-part || if-false-part
-syntax in older versions of angular, the usual ternary operator condition ? true-part : false-part
is available in Angular 1.1.5 and later.
If this is your own source code and you already have a Netbeans project folder with your source files you should just start with:
File | Open Project...
not
File | New Project ...
because the project is not new.
For SQL Server 2000:
SELECT su.name,so.name,so.crdate,*
FROM sysobjects so JOIN sysusers su
ON so.uid = su.uid
WHERE xtype='U'
ORDER BY so.name
Assuming the following method to test:
public boolean doSomething(SomeClass arg);
Mockito documentation says that you should not use captor in this way:
when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);
assertThat(argumentCaptor.getValue(), equalTo(expected));
Because you can just use matcher during stubbing:
when(someObject.doSomething(eq(expected))).thenReturn(true);
But verification is a different story. If your test needs to ensure that this method was called with a specific argument, use ArgumentCaptor
and this is the case for which it is designed:
ArgumentCaptor<SomeClass> argumentCaptor = ArgumentCaptor.forClass(SomeClass.class);
verify(someObject).doSomething(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), equalTo(expected));
In the example you gave, the method will never throw an IOException, therefore the declaration is wrong (but valid). My guess is that the original method threw the IOException, but it was then updated to handle the exception within but the declaration was not changed.
For others who ran into this issue in a project that is not using a sonar-runners.property file, you may find (as I did) that you need to tweak your pom.xml file, adding a sonar.host.url property.
For example, I needed to add the following line under the 'properties' element:
<sonar.host.url>https://sonar.my-internal-company-domain.net</sonar.host.url>
Where the url points to our internal sonar deployment.
You need to run Application.run()
because this method starts whole Spring Framework. Code below integrates your main()
with Spring Boot.
Application.java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
ReconTool.java
@Component
public class ReconTool implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
main(args);
}
public static void main(String[] args) {
// Recon Logic
}
}
SpringApplication.run(ReconTool.class, args)
Because this way spring is not fully configured (no component scan etc.). Only bean defined in run() is created (ReconTool).
Example project: https://github.com/mariuszs/spring-run-magic
I have encounter the same problem. my syntax has no problem. What I found is that I copied and pasted git commit -m "comments" from my note. I retype it, the command execute without issue. It turns out the - and " " are the problem when I copy paste to terminal.
Since I don't know how to control only the list marker size with CSS and no one's offered this yet, you can use :before
content to generate the bullets:
li {
list-style: none;
font-size: 20px;
}
li:before {
content:"·";
font-size:120px;
vertical-align:middle;
line-height:20px;
}
Demo: http://jsfiddle.net/4wDL5/
The markers are limited to appearing "inside" with this particular CSS, although you could change it. It's definitely not the best option (browser must support generated content, so no IE6 or 7), but it might be the easiest - plus you can choose any character you want for the marker.
If you go the image route, see list-style-image
.
Scripts are not allowed to close a window that a user opened. This is considered a security risk. Though it isn't in any standard, all browser vendors follow this (Mozilla docs). If this happens in some browsers, it's a security bug that (ideally) gets patched very quickly.
None of the hacks in the answers on this question work any longer, and if someone would come up with another dirty hack, eventually it will stop working as well.
I suggest you don't waste energy fighting this and embrace the method that the browser so helpfully gives you — ask the user before you seemingly crash their page.
I think I use the simplest method to get the full profile picture. You can get full profile picture or you can set the profile picture dimension yourself:
$facebook->api(me?fields=picture.width(800).height(800))
You can set width
and height
as per your need. Though Facebook doesn't return the exact size asked for, It returns the closest dimension picture available with them.
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "C# Corner Open File Dialog" ;
fdlg.InitialDirectory = @"c:\" ;
fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*" ;
fdlg.FilterIndex = 2 ;
fdlg.RestoreDirectory = true ;
if(fdlg.ShowDialog() == DialogResult.OK)
{
textBox1.Text = fdlg.FileName ;
}
In this code you can put your address in a text box.
Also experienced issues with Java the last 2 weeks no longer working in IE 11 under Windows 7 x64 (reverted to Chrome where it DID work)
I had to go through (ALL) the following steps in order to restore Java operation:
Try and install latest Java => Error was produced 'The installer cannot proceed with the current Internet Connection setting'
Hit 'Retry', and the installer started working
Java 8 update 40 was installed successfully, however Java still doesn't work in IE (after closing IE / reboot)
Removed older/outdated versions (either using the Oracle-Java tool or through Install/Uninstall programs). In my case, I was able to remove old version 7 update 71.
After another attempt to close IE completely and restarting Windows did not resolve the issue (as before, testing Java operation using the Oracle-Java online tool failed to work and even failed to produce the 'grey box' that is always shown (in spite of the fact that the Java-plugins are loaded and activated)
Finally restored IE settings through: Internet options -> Advanced -> Reset (Note: I tried that before 1 week earlier, but then this DID NOT yield a solution either)
Eureka, it works again !
Result is now as follows using the Oracle-Java online test tool, and any Java-applets now work again in IE11: "Gefeliciteerd! U beschikt over de juiste Java-versie. (Version 8 Update 40)."
To fix the especific error SSL certificate problem: unable to get local issuer certificate in git
I had the same issue with Let's Encrypt certificates .
An web site with https we just to need :
SSLEngine On
SSLCertificateFile /etc/letsencrypt/live/example.com/cert.pem
SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
but git pull says :
fatal: unable to access 'https://example.com/git/demo.git/': SSL certificate problem: unable to get local issuer certificate
To fix it, we need also add:
SSLCertificateChainFile /etc/letsencrypt/live/example.com/chain.pem
Using dict.pop
:
d = {'some': 'data'}
entries_to_remove = ('any', 'iterable')
for k in entries_to_remove:
d.pop(k, None)
git log --pretty=format:"%H %an %ad"
use --date=
to set a date format
git log --pretty=format:"%H %an %ad" --date=short
try this : here select is your select element
let select = document.getElementsByClassName('lstSelected')[0],
options = select.options,
len = options.length,
data='',
i=0;
while (i<len){
if (options[i].selected)
data+= "&" + select.name + '=' + options[i].value;
i++;
}
return data;
Data is in the form of query string i.e.name=value&name=anotherValue
SQL Server Management Studio provides an Import/Export wizard tool which have an option to automatically create tables.
You can access it by right clicking on the Database in Object Explorer and selecting Tasks->Import Data...
From there wizard should be self-explanatory and easy to navigate. You choose your CSV as source, desired destination, configure columns and run the package.
If you need detailed guidance, there are plenty of guides online, here is a nice one: http://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/
There is another way to draw a circle - draw it in fragment shader. Create a quad:
float right = 0.5;
float bottom = -0.5;
float left = -0.5;
float top = 0.5;
float quad[20] = {
//x, y, z, lx, ly
right, bottom, 0, 1.0, -1.0,
right, top, 0, 1.0, 1.0,
left, top, 0, -1.0, 1.0,
left, bottom, 0, -1.0, -1.0,
};
Bind VBO:
unsigned int glBuffer;
glGenBuffers(1, &glBuffer);
glBindBuffer(GL_ARRAY_BUFFER, glBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(float)*20, quad, GL_STATIC_DRAW);
and draw:
#define BUFFER_OFFSET(i) ((char *)NULL + (i))
glEnableVertexAttribArray(ATTRIB_VERTEX);
glEnableVertexAttribArray(ATTRIB_VALUE);
glVertexAttribPointer(ATTRIB_VERTEX , 3, GL_FLOAT, GL_FALSE, 20, 0);
glVertexAttribPointer(ATTRIB_VALUE , 2, GL_FLOAT, GL_FALSE, 20, BUFFER_OFFSET(12));
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
Vertex shader
attribute vec2 value;
uniform mat4 viewMatrix;
uniform mat4 projectionMatrix;
varying vec2 val;
void main() {
val = value;
gl_Position = projectionMatrix*viewMatrix*vertex;
}
Fragment shader
varying vec2 val;
void main() {
float R = 1.0;
float R2 = 0.5;
float dist = sqrt(dot(val,val));
if (dist >= R || dist <= R2) {
discard;
}
float sm = smoothstep(R,R-0.01,dist);
float sm2 = smoothstep(R2,R2+0.01,dist);
float alpha = sm*sm2;
gl_FragColor = vec4(0.0, 0.0, 1.0, alpha);
}
Don't forget to enable alpha blending:
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
UPDATE: Read more
If your project already depends on Apache Commons you can use StringUtils.ordinalIndexOf
, otherwise, here's an implementation:
public static int ordinalIndexOf(String str, String substr, int n) {
int pos = str.indexOf(substr);
while (--n > 0 && pos != -1)
pos = str.indexOf(substr, pos + 1);
return pos;
}
This post has been rewritten as an article here.
I wanted to keep the formulas in place, which the above code did not do.
Here's what I've been doing, note that this leaves one empty row in the table.
Sub DeleteTableRows(ByRef Table As ListObject, KeepFormulas as boolean)
On Error Resume Next
if not KeepFormulas then
Table.DataBodyRange.clearcontents
end if
Table.DataBodyRange.Rows.Delete
On Error GoTo 0
End Sub
(PS don't ask me why!)
For more general boolean functions that you would like to use as a filter and that depend on more than one column, you can use:
df = df[df[['col_1','col_2']].apply(lambda x: f(*x), axis=1)]
where f is a function that is applied to every pair of elements (x1, x2) from col_1 and col_2 and returns True or False depending on any condition you want on (x1, x2).
Somewhere in that mess, the non-breaking spaces from the HTML template (the s) are encoding as ISO-8859-1 so that they show up incorrectly as an "Â" character
That'd be encoding to UTF-8 then, not ISO-8859-1. The non-breaking space character is byte 0xA0 in ISO-8859-1; when encoded to UTF-8 it'd be 0xC2,0xA0, which, if you (incorrectly) view it as ISO-8859-1 comes out as "Â "
. That includes a trailing nbsp which you might not be noticing; if that byte isn't there, then something else has mauled your document and we need to see further up to find out what.
What's the regexp, how does the templating work? There would seem to be a proper HTML parser involved somewhere if your
strings are (correctly) being turned into U+00A0 NON-BREAKING SPACE characters. If so, you could just process your template natively in the DOM, and ask it to serialise using the ASCII encoding to keep non-ASCII characters as character references. That would also stop you having to do regex post-processing on the HTML itself, which is always a highly dodgy business.
Well anyway, for now you can add one of the following to your document's <head>
and see if that makes it look right in the browser:
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta charset="utf-8">
If you've done that, then any remaining problem is ActivePDF's fault.
We have an app in Google Play and the App Store that will scan barcodes into a web site. The app is called Scan to Web. http://berrywing.com/scantoweb.html
You can even embed a link or button to start the scanner yourself within your web page.
<a href="bwstw://startscanner">Link to start scanner</a>
The developer documentation website for the app covers how to use the app and use JavaScript for processing the barcode scan. http://berrywing.com/scantoweb/#htmlscanbutton
NullPointerException
is a run-time exception which is not recommended to catch it, but instead avoid it:
if(someVariable != null) someVariable.doSomething();
else
{
// do something else
}
Use @Kristian Antonsen's answer, or you can use:
$('button').click(function() {
preventDefault();
captureForm();
});
If you want the remainder of your division problem, just use the actual remainder rules, just like in mathematics. Granted this won't give you a decimal output.
valone = 8
valtwo = 3
x = valone / valtwo
r = valone - (valtwo * x)
print "Answer: %s with a remainder of %s" % (x, r)
If you want to make this in a calculator format, just substitute valone = 8
with valone = int(input("Value One"))
. Do the same with valtwo = 3
, but different vairables obviously.
To answer the original posters question.... to 'decrypt' the password, you have to do what a password cracker would do.
In other words, you'd run a program to read from a large list of potential passwords (a password dictionary) and you'd hash each one using bcrypt
and the salt and complexity from the password you're trying to decipher. If you're lucky you'll find a match, but if the password is a strong one then you likely won't find a match.
Bcrypt
has the added security characteristic of being a slow hash. If your password had been hashed with md5 (terrible choice) then you'd be able to check billions of passwords per second, but since it's hashed using bcrypt
you will be able to check far fewer per second.
The fact that bcrypt
is slow to hash and salted is what makes it a good choice for password storage even today. That being said I believe NIST
recommends the PBKDF2 for password hashing.
You want a dict.
For (unsorted) lists in Python, the "in" operation requires O(n) time---not good when you have a large amount of data. A dict, on the other hand, is a hash table, so you can expect O(1) lookup time.
As others have noted, you might choose a set (a special type of dict) instead, if you only have keys rather than key/value pairs.
Related:
I ended up making 2 display:table;
#container-tv { /* Tiled background */
display:table;
width:100%;
background-image: url(images/back.jpg);
background-repeat: repeat;
}
#container-body-background { /* center column but not 100% width */
display:table;
margin:0 auto;
background-image:url(images/middle-back.png);
background-repeat: repeat-y;
}
This made it have a tiled background image with a background image in the middle as a column. It stretches to 100% height of page not just 100% of browser window size
This could be caused by the pid file created for postgres which has not been deleted due to unexpected shutdown. To fix this, remove this pid file.
Find the postgres data directory. On a MAC using homebrew it is /usr/local/var/postgres/
, other systems it might be /usr/var/postgres/
Remove pid file by running:
rm postmaster.pid
Restart postgress. On Mac, run:
brew services restart postgresql
Here's an approach. If you pipe through less, the xterm width is set to 80, which ain't so hot. But if you proceed the command with, e.g. COLS=210, you can utilize your expanded xterm.
gitdiff()
{
local width=${COLS:-$(tput cols)}
GIT_EXTERNAL_DIFF="diff -yW$width \$2 \$5; echo >/dev/null" git diff "$@"
}
$('#drop').change(
function() {
var val1 = $('#pick option:selected').val();
var val2 = $('#drop option:selected').val();
// Do something with val1 and val2 ...
}
);
ANSWER: Read the instructions #dua
Ok the magic was in this line that I apparently missed when installing was:
$ sudo apt-get install mongodb-10gen=2.4.6
And the full process as described here http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/ is
$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
$ echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
$ sudo apt-get update
$ sudo apt-get install mongodb-10gen
$ sudo apt-get install mongodb-10gen=2.2.3
$ echo "mongodb-10gen hold" | sudo dpkg --set-selections
$ sudo service mongodb start
$ mongod --version
db version v2.4.6
Wed Oct 16 12:21:39.938 git version: b9925db5eac369d77a3a5f5d98a145eaaacd9673
IMPORTANT: Make sure you change 2.4.6 to the latest version (or whatever you want to install). Find the latest version number here http://www.mongodb.org/downloads
This is for those who want to a portable way to count cpu cores on *bsd, *nix or solaris (haven't tested on aix and hp-ux but should work). It has always worked for me.
dmesg | \
egrep 'cpu[. ]?[0-9]+' | \
sed 's/^.*\(cpu[. ]*[0-9]*\).*$/\1/g' | \
sort -u | \
wc -l | \
tr -d ' '
solaris grep
& egrep
don't have -o
option so sed
is used instead.
Xamarin.iOS version for accepted answer on how to resize and then crop UIImage (Aspect Fill) is below
public static UIImage ScaleAndCropImage(UIImage sourceImage, SizeF targetSize)
{
var imageSize = sourceImage.Size;
UIImage newImage = null;
var width = imageSize.Width;
var height = imageSize.Height;
var targetWidth = targetSize.Width;
var targetHeight = targetSize.Height;
var scaleFactor = 0.0f;
var scaledWidth = targetWidth;
var scaledHeight = targetHeight;
var thumbnailPoint = PointF.Empty;
if (imageSize != targetSize)
{
var widthFactor = targetWidth / width;
var heightFactor = targetHeight / height;
if (widthFactor > heightFactor)
{
scaleFactor = widthFactor;// scale to fit height
}
else
{
scaleFactor = heightFactor;// scale to fit width
}
scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;
// center the image
if (widthFactor > heightFactor)
{
thumbnailPoint.Y = (targetHeight - scaledHeight) * 0.5f;
}
else
{
if (widthFactor < heightFactor)
{
thumbnailPoint.X = (targetWidth - scaledWidth) * 0.5f;
}
}
}
UIGraphics.BeginImageContextWithOptions(targetSize, false, 0.0f);
var thumbnailRect = new RectangleF(thumbnailPoint, new SizeF(scaledWidth, scaledHeight));
sourceImage.Draw(thumbnailRect);
newImage = UIGraphics.GetImageFromCurrentImageContext();
if (newImage == null)
{
Console.WriteLine("could not scale image");
}
//pop the context to get back to the default
UIGraphics.EndImageContext();
return newImage;
}
In my case, I had a repo with:
.json
.lock
In the meantime, A,B,C had newer versions with respect when the lock was generated.
For some reason, I deleted the "vendors" and wanted to do a composer install
and failed with the message:
Warning: The lock file is not up to date with the latest changes in composer.json.
You may be getting outdated dependencies. Run update to update them.
Your requirements could not be resolved to an installable set of packages.
I tried to run the solution from Seldaek issuing a composer update vendorD/libraryD
but composer insisted to update more things, so .lock
had too changes seen my my git tool.
The solution I used was:
vendors
dir.VendorD/LibraryD
from the .json
.composer install
..json
and checkout it again from the repo (equivalent to re-adding the file, but avoiding potential whitespace changes).composer update vendorD/libraryD
It did install the library, but in addition, git
diff showed me that in the .lock
only the new things were added without editing the other ones.
(Thnx Seldaek for the pointer ;) )
Beans.xml or file.XML is not placed under proper path. You should add the XML file under the resource folder, if you have a Maven project. src -> main -> java -> resources
SELECT * FROM tablename WHERE visible=1 ORDER BY CASE WHEN `position` = 0 THEN 'a' END , position ASC
If you don't know its key it means it doesn't matter.
You could place the value as the key, it means it will instantly find the value. Better than using searching in all elements over and over again.
$messages=array();
$messages[312] = 312;
$messages[401] = 401;
$messages[1599] = 1599;
$messages[3] = 3;
unset($messages[3]); // no search needed
A POJO is just a plain, old Java Bean with the restrictions removed. Java Beans must meet the following requirements:
POJO does not mandate any of these. It's just what the name says: an object that compiles under JDK can be considered a Plain Old Java Object. No app server, no base classes, no interfaces required to use.
The acronym POJO was a reaction against EJB 2.0, which required several interfaces, extended base classes, and lots of methods just to do simple things. Some people, Rod Johnson and Martin Fowler among them, rebelled against the complexity and sought a way to implement enterprise scale solutions without having to write EJBs.
Martin Fowler coined a new acronym.
Rod Johnson wrote "J2EE Without EJBs", wrote Spring, influenced EJB enough so version 3.1 looks a great deal like Spring and Hibernate, and got a sweet IPO from VMWare out of it.
Here's an example that you can wrap your head around:
public class MyFirstPojo
{
private String name;
public static void main(String [] args)
{
for (String arg : args)
{
MyFirstPojo pojo = new MyFirstPojo(arg); // Here's how you create a POJO
System.out.println(pojo);
}
}
public MyFirstPojo(String name)
{
this.name = name;
}
public String getName() { return this.name; }
public String toString() { return this.name; }
}
As a native and efficient approach, you don't need to use ord
or any loop over the characters. Just encode with ascii
and ignore the errors.
The following will just remove the non-ascii characters:
new_string = old_string.encode('ascii',errors='ignore')
Now if you want to replace the deleted characters just do the following:
final_string = new_string + b' ' * (len(old_string) - len(new_string))
This is a very old post, but I thought I should post my solution of a similar problem I faced recently.
Answer : I solved this issue by displaying the tr element as a block element i.e. specifying a CSS of display:block for the tr element. You can see this in code sample below.
<style>_x000D_
tr {_x000D_
display: block;_x000D_
padding-bottom: 20px;_x000D_
}_x000D_
table {_x000D_
border: 1px solid red;_x000D_
}_x000D_
</style>_x000D_
<table>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>_x000D_
<h2>Lorem Ipsum</h2>_x000D_
<p>Fusce sodales lorem nec magna iaculis a fermentum lacus facilisis. Curabitur sodales risus sit amet neque fringilla feugiat. Ut tellus nulla, bibendum at faucibus ut, convallis eget neque. In hac habitasse platea dictumst. Nullam elit enim, gravida_x000D_
eu blandit ut, pellentesque nec turpis. Proin faucibus, sem sed tempor auctor, ipsum velit pellentesque lorem, ut semper lorem eros ac eros. Vivamus mi urna, tempus vitae mattis eget, pretium sit amet sapien. Curabitur viverra lacus non tortor_x000D_
luctus vitae euismod purus hendrerit. Praesent ut venenatis eros. Nulla a ligula erat. Mauris lobortis tempus nulla non scelerisque._x000D_
</p>_x000D_
</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
<br>_x000D_
<br>This TEXT IS BELOW and OUTSIDE the TABLE element. NOTICE how the red table border is pushed down below the end of paragraph due to bottom padding being specified for the tr element. The key point here is that the tr element must be displayed as a block_x000D_
in order for padding to apply at the tr level.
_x000D_
just a variation
alist=["a", "b", "c", "d", "e", 0, "g"]
alist[3:6] = [''.join(map(str,alist[3:6]))]
print alist
If you want to run a cron every n
minutes, there are a few possible options depending on the value of n
.
n
divides 60 (1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30)
Here, the solution is straightforward by making use of the /
notation:
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7)
# | | | | |
# * * * * * command to be executed
m-59/n * * * * command
In the above, n
represents the value n
and m
represents a value smaller than n
or *
. This will execute the command at the minutes m,m+n,m+2n,...
n
does NOT divide 60
If n
does not divide 60, you cannot do this cleanly with cron but it is possible. To do this you need to put a test in the cron where the test checks the time. This is best done when looking at the UNIX timestamp, the total seconds since 1970-01-01 00:00:00 UTC
. Let's say we want to start to run the command the first time when Marty McFly arrived in Riverdale and then repeat it every n
minutes later.
% date -d '2015-10-21 07:28:00' +%s
1445412480
For a cronjob to run every 42
nd minute after `2015-10-21 07:28:00', the crontab would look like this:
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7)
# | | | | |
# * * * * * command to be executed
* * * * * minutetestcmd "2015-10-21 07:28:00" 42 && command
with minutetestcmd
defined as
#!/usr/bin/env bash
starttime=$(date -d "$1" "+%s")
# return UTC time
now=$(date "+%s")
# get the amount of minutes (using integer division to avoid lag)
minutes=$(( (now - starttime) / 60 ))
# set the modulo
modulo=$2
# do the test
(( now >= starttime )) && (( minutes % modulo == 0 ))
Remark: UNIX time is not influenced by leap seconds
Remark: cron
has no sub-second accuracy
An alternate solution is to use Apache Commons' NumberUtils:
int num = NumberUtils.toInt("1234");
The Apache utility is nice because if the string is an invalid number format then 0 is always returned. Hence saving you the try catch block.
Here's a compilation of CSS styling order in a diagram, on which CSS rules has higher priority and take precedence over the rest:
Disclaimer: My team and I worked this piece out together with a blog post (https://vecta.io/blog/definitive-guide-to-css-styling-order) which I think will come in handy to all front-end developers.
You could do something like this if you wanted
package main
import "fmt"
type Pair struct {
a, b interface{}
}
func main() {
p1 := Pair{"finished", 42}
p2 := Pair{6.1, "hello"}
fmt.Println("p1=", p1, "p2=", p2)
fmt.Println("p1.b", p1.b)
// But to use the values you'll need a type assertion
s := p1.a.(string) + " now"
fmt.Println("p1.a", s)
}
However I think what you have already is perfectly idiomatic and the struct describes your data perfectly which is a big advantage over using plain tuples.
Add .idea
and *.iml
to .gitignore
, you don't need those files to successfully import and compile the project.
Avoid direct references to '@@ERROR'. It's a flighty little thing that can be lost.
Declare @ErrorCode int;
... perform stuff ...
Set @ErrorCode = @@ERROR;
... other stuff ...
if @ErrorCode ......
Simplifying what @Scotti said. You need to create Multiples apps with different package name for a particular Project depending on the product flavor.
Suppose your Project is ABC having different product flavors X,Y where X has a package name com.x and Y has a package name com.y then in the firebase console you need to create a project ABC in which you need to create 2 apps with the package names com.x and com.y. Then you need to download the google-services.json file in which there will be 2 client-info objects which will contain those pacakges and you will be good to go.
Snippet of the json would be something like this
{
"client": [
{
"client_info": {
"android_client_info": {
"package_name": "com.x"
}
{
"client_info": {
"android_client_info": {
"package_name": "com.y"
}
]
}
You can't modify the members of a CSS class on the fly. However, you could introduce a new <style>
tag on the page with your new css class implementation, and then switch out the class. Example:
Sample.css
.someClass { border: 1px solid black; font-size: 20px; }
You want to change that class entirely, so you create a new style element:
<style>
.someClassReplacement { border: 1px solid white; font-size: 14px; }
</style>
You then do a simple replacement via jQuery:
$('.someClass').removeClass('someClass').addClass('someClassReplacement');
.rainbow {_x000D_
background-image: -webkit-gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2),color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) );_x000D_
background-image: gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2),color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) );_x000D_
color:transparent;_x000D_
-webkit-background-clip: text;_x000D_
background-clip: text;_x000D_
}
_x000D_
<h2><span class="rainbow">Rainbows are colorful and scalable and lovely</span></h2>
_x000D_
You can maintain a Map
(for fast lookup) and List
(for order) but a LinkedHashMap
may be the simplest. You can also try a SortedMap
e.g. TreeMap
, which an have any order you specify.
<html>
<head>
<title>Login page</title>
</head>
<body>
<h1>Simple Login Page</h1>
<form name="login">
Username<input type="text" name="userid"/>
Password<input type="password" name="pswrd"/>
<input type="button" onclick="check(this.form)" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
<script language="javascript">
function check(form) { /*function to check userid & password*/
/*the following code checkes whether the entered userid and password are matching*/
if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd") {
window.open('target.html')/*opens the target page while Id & password matches*/
}
else {
alert("Error Password or Username")/*displays error message*/
}
}
</script>
</body>
</html>
My Code to insert data is not working. It showing no error but data is not showing in my database.
public partial class Form1 : Form { OleDbConnection connection = new OleDbConnection(check.Properties.Settings.Default.KitchenConnectionString); public Form1() { InitializeComponent(); }
private void Form1_Load(object sender, EventArgs e)
{
}
private void btn_add_Click(object sender, EventArgs e)
{
OleDbDataAdapter items = new OleDbDataAdapter();
connection.Open();
OleDbCommand command = new OleDbCommand("insert into Sets(SetId, SetName, SetPassword) values('"+txt_id.Text+ "','" + txt_setname.Text + "','" + txt_password.Text + "');", connection);
command.CommandType = CommandType.Text;
command.ExecuteReader();
connection.Close();
MessageBox.Show("Insertd!");
}
}
Yes, you have to get all records, update them and then call SaveChanges
.
You simply cannot. DataFrames
, same as other distributed data structures, are not iterable and can be accessed using only dedicated higher order function and / or SQL methods.
You can of course collect
for row in df.rdd.collect():
do_something(row)
or convert toLocalIterator
for row in df.rdd.toLocalIterator():
do_something(row)
and iterate locally as shown above, but it beats all purpose of using Spark.
Use forward slashes. See explanation here
I don't know that function; anyway if your value is unsigned, just one operation means (val < 11)... If it is signed, I think there is no atomic way to do it because 10 is not a power of 2...
Just use:
org.springframework.beans.factory.BeanFactory#getBean(java.lang.Class)
Example:
@Component
public class Example {
@Autowired
private ApplicationContext context;
public MyService getMyServiceBean() {
return context.getBean(MyService.class);
}
// your code uses getMyServiceBean()
}
I use Ext, so I ended up doing this:
var theForm = Ext.get("theform");
var inputButtons = Ext.DomQuery.jsSelect('input[type="submit"]', theForm.dom);
var inputButtonPressed = null;
for (var i = 0; i < inputButtons.length; i++) {
Ext.fly(inputButtons[i]).on('click', function() {
inputButtonPressed = this;
}, inputButtons[i]);
}
and then when it was time submit I did
if (inputButtonPressed !== null) inputButtonPressed.click();
else theForm.dom.submit();
Wait, you say. This will loop if you're not careful. So, onSubmit must sometimes return true
// Notice I'm not using Ext here, because they can't stop the submit
theForm.dom.onsubmit = function () {
if (gottaDoSomething) {
// Do something asynchronous, call the two lines above when done.
gottaDoSomething = false;
return false;
}
return true;
}
The reason your original dataframe does not update is because chained indexing may cause you to modify a copy rather than a view of your dataframe. The docs give this advice:
When setting values in a pandas object, care must be taken to avoid what is called chained indexing.
You have a few alternatives:-
loc
+ Boolean indexingloc
may be used for setting values and supports Boolean masks:
df.loc[df['my_channel'] > 20000, 'my_channel'] = 0
mask
+ Boolean indexingYou can assign to your series:
df['my_channel'] = df['my_channel'].mask(df['my_channel'] > 20000, 0)
Or you can update your series in place:
df['my_channel'].mask(df['my_channel'] > 20000, 0, inplace=True)
np.where
+ Boolean indexingYou can use NumPy by assigning your original series when your condition is not satisfied; however, the first two solutions are cleaner since they explicitly change only specified values.
df['my_channel'] = np.where(df['my_channel'] > 20000, 0, df['my_channel'])
When you create a StreamWriter
it always create a file from scratch, you will have to create a third file and copy from target and replace what you need, and then replace the old one.
But as I can see what you need is XML manipulation, you might want to use XmlDocument
and modify your file using Xpath.
your understanding is right. For detailed info on {} see bash ref - parameter expansion
'for' and 'while' have different syntax and offer different styles of programmer control for an iteration. Most non-asm languages offer a similar syntax.
With while, you would probably write i=0; while [ $i -lt 10 ]; do echo $i; i=$(( i + 1 )); done
in essence manage everything about the iteration yourself
Behind the curtain, enums are POJOs with a private constructor and a bunch of public static final values of the enum's type (see here for an example). In fact, up until Java5, it was considered best-practice to build your own enumeration this way, and Java5 introduced the enum
keyword as a shorthand. See the source for Enum<T> to learn more.
So it should be no problem to write your own 'TypeSafeEnum' with a public static final array of constants, that are read by the constructor or passed to it.
Also, do yourself a favor and override equals
, hashCode
and toString
, and if possible create a values
method
The question is how to use such a dynamic enumeration... you can't read the value "PI=3.14" from a file to create enum MathConstants
and then go ahead and use MathConstants.PI
wherever you want...
public Bitmap scaleBitmap(Bitmap mBitmap) {
int ScaleSize = 250;//max Height or width to Scale
int width = mBitmap.getWidth();
int height = mBitmap.getHeight();
float excessSizeRatio = width > height ? width / ScaleSize : height / ScaleSize;
Bitmap bitmap = Bitmap.createBitmap(
mBitmap, 0, 0,(int) (width/excessSizeRatio),(int) (height/excessSizeRatio));
//mBitmap.recycle(); if you are not using mBitmap Obj
return bitmap;
}
Change string[] lines = File.ReadLines("c:\\file.txt");
to IEnumerable<string> lines = File.ReadLines("c:\\file.txt");
The rest of your code should work fine.
clean
is its own build lifecycle phase (which can be thought of as an action or task) in Maven. mvn clean install
tells Maven to do the clean
phase in each module before running the install
phase for each module.
What this does is clear any compiled files you have, making sure that you're really compiling each module from scratch.