I can't recall the source, but I've heard/read about a form of audible syntax "colouring" - so that instead of a string assignment being read as
foo equals quote this is a string quote
the string part would be read with a different pitch or voice to make the separation of elements clearer.
Modules Preconditions:
The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (
precondition="managedHandler"
) only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />
If you remove the attribute
precondition="managedHandler"
, Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "
managedHandler
" precondition.To enable all managed modules to run for all requests without configuring each module entry to remove the "
managedHandler
" precondition, use therunAllManagedModulesForAllRequests
property in the<modules>
section:<modules runAllManagedModulesForAllRequests="true" />
When you use this property, the "
managedHandler
" precondition has no effect and all managed modules run for all requests.
Copied from IIS Modules Overview: Preconditions
I am using a powershell build and couldn't get npm to run without changing the current directory.
Ended up using the start command and just specifying the working directory:
start "npm" -ArgumentList "install --warn" -wo $buildFolder
Try the following:
cv::Mat image = ...do some stuff...;
image.at<cv::Vec3b>(y,x);
gives you the RGB (it might be ordered as BGR) vector of type cv::Vec3b
image.at<cv::Vec3b>(y,x)[0] = newval[0];
image.at<cv::Vec3b>(y,x)[1] = newval[1];
image.at<cv::Vec3b>(y,x)[2] = newval[2];
I think the following code will take care of only TextFields in the form:
var str = $('#formId').serialize();
To add other types of input type we can use:
$("input[type='checkbox'], input[type='radio']").on( "click", functionToSerialize );
$("select").on( "change", functionToSerialize );
It depends. If the main code is protected by an if
as in:
if __name__ == '__main__':
...main code...
then no, you can't make Python execute that because you can't influence the automatic variable __name__
.
But when all the code is in a function, then might be able to. Try
import myModule
myModule.main()
This works even when the module protects itself with a __all__
.
from myModule import *
might not make main
visible to you, so you really need to import the module itself.
While most people have answered the question directly, I wanted to elaborate more on the concept behind it. First, I was drawn to the attention of IME when I created a default Login Activity. It generated some code for me which included the following:
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/prompt_password"
android:imeActionId="@+id/login"
android:imeActionLabel="@string/action_sign_in_short"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true"/>
You should already be familiar with the inputType attribute. This just informs Android the type of text expected such as an email address, password or phone number. The full list of possible values can be found here.
It was, however, the attribute imeOptions="actionUnspecified"
that I didn't understand its purpose. Android allows you to interact with the keyboard that pops up from bottom of screen when text is selected using the InputMethodManager
. On the bottom corner of the keyboard, there is a button, typically it says "Next" or "Done", depending on the current text field. Android allows you to customize this using android:imeOptions
. You can specify a "Send" button or "Next" button. The full list can be found here.
With that, you can then listen for presses on the action button by defining a TextView.OnEditorActionListener
for the EditText
element. As in your example:
editText.setOnEditorActionListener(new EditText.OnEditorActionListener() {
@Override
public boolean onEditorAction(EditText v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
//do here your stuff f
return true;
}
return false;
}
});
Now in my example I had android:imeOptions="actionUnspecified"
attribute. This is useful when you want to try to login a user when they press the enter key. In your Activity, you can detect this tag and then attempt the login:
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
A solution in ASP.NET Core:
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
namespace WebApp
{
public static class HttpHelper
{
// In my case this is https://localhost:44366/
private static readonly string apiBasicUri = ConfigurationManager.AppSettings["apiBasicUri"];
public static async Task Post<T>(string url, T contentValue)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(apiBasicUri);
var content = new StringContent(JsonConvert.SerializeObject(contentValue), Encoding.UTF8, "application/json");
var result = await client.PostAsync(url, content);
result.EnsureSuccessStatusCode();
}
}
public static async Task Put<T>(string url, T stringValue)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(apiBasicUri);
var content = new StringContent(JsonConvert.SerializeObject(stringValue), Encoding.UTF8, "application/json");
var result = await client.PutAsync(url, content);
result.EnsureSuccessStatusCode();
}
}
public static async Task<T> Get<T>(string url)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(apiBasicUri);
var result = await client.GetAsync(url);
result.EnsureSuccessStatusCode();
string resultContentString = await result.Content.ReadAsStringAsync();
T resultContent = JsonConvert.DeserializeObject<T>(resultContentString);
return resultContent;
}
}
public static async Task Delete(string url)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(apiBasicUri);
var result = await client.DeleteAsync(url);
result.EnsureSuccessStatusCode();
}
}
}
}
To post, use something like this:
await HttpHelper.Post<Setting>($"/api/values/{id}", setting);
Example for delete:
await HttpHelper.Delete($"/api/values/{id}");
Example to get a list:
List<ClaimTerm> claimTerms = await HttpHelper.Get<List<ClaimTerm>>("/api/values/");
Example to get only one:
ClaimTerm processedClaimImage = await HttpHelper.Get<ClaimTerm>($"/api/values/{id}");
You can use multiple id
's the way you wrote:
$('#upload_link, #upload_link2, #upload_link3')
However, that doesn't mean that those ids exist within the DOM when you've executed your code. It also doesn't mean that upload
is a legitimate function. It also doesn't mean that upload
has been built in a way that allows for multiple elements in a selection.
upload
is a custom jQuery plugin, so you'll have to show what's going on with upload
for us to be able to help you.
I found this issue addressed here vagrant issues. Two ways to do it:
Run this on guest (i.e. after you ssh into vbox via vagrant ssh
)
sudo ln -s /opt/VBoxGuestAdditions-4.3.10/lib/VBoxGuestAdditions /usr/lib/VBoxGuestAdditions
Then run vagrant reload
to correctly mount the folders.
As @klang pointed out, update the VBoxGuestAdditions.iso file on your mac:
wget https://www.virtualbox.org/download/testcase/VBoxGuestAdditions_4.3.11-93070.iso??
sudo cp VBoxGuestAdditions_4.3.11-93070.iso /Applications/VirtualBox.app/Contents/MacOS/VBoxGuestAdditions.iso
Since the iso is no longer available, you can use the 4.3.12 one (http://dlc.sun.com.edgesuite.net/virtualbox/4.3.12/VBoxGuestAdditions_4.3.12.iso)
note : the binary vbox4.3.12 for os X is not available at this time
The modern way to do this is with flexbox, adding align-items: flex-end;
on the container.
With this content:
<div class="Container">
<div>one</div>
<div>two</div>
</div>
Use this style:
.Container {
display: flex;
align-items: flex-end;
}
Here's my way to find file names that contain some content that I'm interested in, just a single bash line that nicely handles spaces in filenames too:
find . -name \*.xml | while read i; do grep '<?xml' "$i" >/dev/null; [ $? == 0 ] && echo $i; done
A TVF (table-valued function) is supposed to be SELECTed FROM. Try this:
select * from FN('myFunc')
I think you are referring to the problem in C (and C++) that returning an array from a function isn't allowed (or at least won't work as expected) - this is because the array return will (if you write it in the simple form) return a pointer to the actual array on the stack, which is then promptly removed when the function returns.
But in this case, it works, because the std::vector
is a class, and classes, like structs, can (and will) be copied to the callers context. [Actually, most compilers will optimise out this particular type of copy using something called "Return Value Optimisation", specifically introduced to avoid copying large objects when they are returned from a function, but that's an optimisation, and from a programmers perspective, it will behave as if the assignment constructor was called for the object]
As long as you don't return a pointer or a reference to something that is within the function returning, you are fine.
SELECT a.salesorderid, a.orderdate, s.orderdate, s.salesorderid
FROM A a
OUTER APPLY (SELECT top(1) *
FROM B b WHERE a.salesorderid = b.salesorderid) as s
WHERE A.Date BETWEEN '2000-1-4' AND '2010-1-4'
If you:
shrinkToFit: false
(mean fixed width columns)autowidth: true
You can make grid with fluid width with following styles:
.ui-jqgrid {
max-width: 100% !important;
width: auto !important;
}
.ui-jqgrid-view,
.ui-jqgrid-hdiv,
.ui-jqgrid-bdiv {
width: auto !important;
}
If you get the error after installation: Find the .lax file with the matching exe name and update current vm path from:
lax.nl.current.vm=C:\ProgramData\Oracle\Java\javapath\java.exe
to
lax.nl.current.vm=C:\Program Files\Java\jre1.8.0_144\bin\java.exe
As additional information, mostly in macOS, the .vimrc file is located at directory:
/usr/share/vim/.vimrc
Let's look at this with the help of an example. Suppose we have a direct mapped cache and the write back policy is used. So we have a valid bit, a dirty bit, a tag and a data field in a cache line. Suppose we have an operation : write A ( where A is mapped to the first line of the cache).
What happens is that the data(A) from the processor gets written to the first line of the cache. The valid bit and tag bits are set. The dirty bit is set to 1.
Dirty bit simply indicates was the cache line ever written since it was last brought into the cache!
Now suppose another operation is performed : read E(where E is also mapped to the first cache line)
Since we have direct mapped cache, the first line can simply be replaced by the E block which will be brought from memory. But since the block last written into the line (block A) is not yet written into the memory(indicated by the dirty bit), so the cache controller will first issue a write back to the memory to transfer the block A to memory, then it will replace the line with block E by issuing a read operation to the memory. dirty bit is now set to 0.
So write back policy doesnot guarantee that the block will be the same in memory and its associated cache line. However whenever the line is about to be replaced, a write back is performed at first.
A write through policy is just the opposite. According to this, the memory will always have a up-to-date data. That is, if the cache block is written, the memory will also be written accordingly. (no use of dirty bits)
Yes, this is possible:
List<BigDecimal> bdList = new ArrayList<>();
//populate list
BigDecimal result = bdList.stream()
.reduce(BigDecimal.ZERO, BigDecimal::add);
What it does is:
List<BigDecimal>
.Stream<BigDecimal>
Call the reduce method.
3.1. We supply an identity value for addition, namely BigDecimal.ZERO
.
3.2. We specify the BinaryOperator<BigDecimal>
, which adds two BigDecimal
's, via a method reference BigDecimal::add
.
I see that you have added new data, therefore the new answer will become:
List<Invoice> invoiceList = new ArrayList<>();
//populate
Function<Invoice, BigDecimal> totalMapper = invoice -> invoice.getUnit_price().multiply(invoice.getQuantity());
BigDecimal result = invoiceList.stream()
.map(totalMapper)
.reduce(BigDecimal.ZERO, BigDecimal::add);
It is mostly the same, except that I have added a totalMapper
variable, that has a function from Invoice
to BigDecimal
and returns the total price of that invoice.
Then I obtain a Stream<Invoice>
, map it to a Stream<BigDecimal>
and then reduce it to a BigDecimal
.
Now, from an OOP design point I would advice you to also actually use the total()
method, which you have already defined, then it even becomes easier:
List<Invoice> invoiceList = new ArrayList<>();
//populate
BigDecimal result = invoiceList.stream()
.map(Invoice::total)
.reduce(BigDecimal.ZERO, BigDecimal::add);
Here we directly use the method reference in the map
method.
I faced this problem when I first tried python after installing windows10 + python3.7(64bit) + anacconda3 + jupyter notebook.
I solved this problem by refering to "https://vispud.blogspot.com/2019/05/tensorflow200a0-attributeerror-module.html"
I agree with
I believe "Session()" has been removed with TF 2.0.
I inserted two lines. One is tf.compat.v1.disable_eager_execution()
and the other is sess = tf.compat.v1.Session()
My Hello.py is as follows:
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
hello = tf.constant('Hello, TensorFlow!')
sess = tf.compat.v1.Session()
print(sess.run(hello))
It sounds like your printMousePos
function should:
Currently, it does this:
See the problem? Your variables are never getting set, because as soon as you add your function to the "mousemove" event you print them.
It seems like you probably don't need that mousemove event at all; I would try something like this:
function printMousePos(e) {
var cursorX = e.pageX;
var cursorY = e.pageY;
document.getElementById('test').innerHTML = "x: " + cursorX + ", y: " + cursorY;
}
I had this issue was trying to remove a ui element inside an event reactive:
myReactives <- eventReactive(input$execute, {
... # Some other long running function here
removeUI(selector = "#placeholder2")
})
I was getting this error, but not on the removeUI element line, it was in the next observer after for some reason. Taking the removeUI method out of the eventReactive and placing it somewhere else removed this error for me.
Use :earlier
/:later
. To redo everything you just need to do
later 9999999d
(assuming that you first edited the file at most 9999999 days ago), or, if you remember the difference between current undo state and needed one, use Nh
, Nm
or Ns
for hours, minutes and seconds respectively. + :later N<CR>
<=> Ng+
and :later Nf
for file writes.
ALTER TABLE
can do multiple table alterations in one statement, but MODIFY COLUMN
can only work on one column at a time, so you need to specify MODIFY COLUMN
for each column you want to change:
ALTER TABLE webstore.Store
MODIFY COLUMN ShortName VARCHAR(100),
MODIFY COLUMN UrlShort VARCHAR(100);
Also, note this warning from the manual:
When you use CHANGE or MODIFY,
column_definition
must include the data type and all attributes that should apply to the new column, other than index attributes such as PRIMARY KEY or UNIQUE. Attributes present in the original definition but not specified for the new definition are not carried forward.
I am adding this answer mainly because I can't comment above! I found it was the comment by @Nicki and her jsfiddle, https://jsfiddle.net/57co6c95/, that eventually got this working for me.
Among other things, it gave examples of the format for the json needed. The only change I had to make was that my initial results were returned in the same format as the other ajax call so I had to use
$option.text(data[0].text).val(data[0].id);
rather than
$option.text(data.text).val(data.id);
To check all versions of Internet Explorer you can go to codecpack.nl and install all versions of Internet Explorer, that is, IE collection.
Or you can use www.multibrowserviewer.com. It can check in 45 browsers and 3 OSes.
This data is JSON! You can deserialize it using the built-in json
module if you're on Python 2.6+, otherwise you can use the excellent third-party simplejson
module.
import json # or `import simplejson as json` if on Python < 2.6
json_string = u'{ "id":"123456789", ... }'
obj = json.loads(json_string) # obj now contains a dict of the data
Check to see if there are any triggers on the table you are trying to execute queries against. They can sometimes throw this error as they are trying to run the update/select/insert trigger that is on the table.
You can modify your query to disable then enable the trigger if the trigger DOES NOT need to be executed for whatever query you are trying to run.
ALTER TABLE your_table DISABLE TRIGGER [the_trigger_name]
UPDATE your_table
SET Gender = 'Female'
WHERE (Gender = 'Male')
ALTER TABLE your_table ENABLE TRIGGER [the_trigger_name]
There is opportunity for several improvements (if you are using DbContext
):
Set:
yourContext.Configuration.AutoDetectChangesEnabled = false;
yourContext.Configuration.ValidateOnSaveEnabled = false;
Do SaveChanges()
in packages of 100 inserts... or you can try with packages of 1000 items and see the changes in performance.
Since during all this inserts, the context is the same and it is getting bigger, you can rebuild your context object every 1000 inserts. var yourContext = new YourContext();
I think this is the big gain.
Doing this improvements in an importing data process of mine, took it from 7 minutes to 6 seconds.
The actual numbers... could not be 100 or 1000 in your case... try it and tweak it.
Jaqen H'ghar is spot-on. A third way is to:
Code that runs on application startup:
ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new ScriptResourceDefinition {
Path = "~/Scripts/jquery.validate.unobtrusive.min.js",
DebugPath = "~/Scripts/jquery.validate.unobtrusive.min.js"
});
Use this to set Marque:
final TextView tx = (TextView) findViewById(R.id.textView1);
tx.setEllipsize(TruncateAt.MARQUEE);
tx.setSelected(true);
tx.setSingleLine(true);
tx.setText("Marquee needs only three things to make it run and these three things are mentioned above.");
You do not need to use "android:marqueeRepeatLimit="marquee_forever" into xml file. Marquee will work even without this.
Beside using loop and for comprehension, you could also use map
lst = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")]
mylst = map(lambda each:each.strip("8"), lst)
print mylst
Enhancement of Ben Brandt's answer to compensate even if the string starts with space by applying LTRIM(). Tried to edit his answer but rejected, so I am now posting it here separately.
DECLARE @test NVARCHAR(255)
SET @test = 'First Second'
SELECT SUBSTRING(LTRIM(@test),1,(CHARINDEX(' ',LTRIM(@test) + ' ')-1))
Just make sure you add box-sizing:border-box;
to your #myWorkContent
.
You can get the first column as a Series by following code:
x[x.columns[0]]
In case anyone else runs into this problem, I was able to get it working like this:
var path = require('path');
// ...
resolve: {
root: [path.resolve(__dirname, 'src'), path.resolve(__dirname, 'node_modules')],
extensions: ['', '.js']
};
where my directory structure is:
.
+-- dist
+-- node_modules
+-- package.json
+-- README.md
+-- src
¦ +-- components
¦ +-- index.html
¦ +-- main.js
¦ +-- styles
+-- webpack.config.js
Then from anywhere in the src
directory I can call:
import MyComponent from 'components/MyComponent';
Here is the official explanation: https://github.com/golang/go/wiki/InterfaceSlice
var dataSlice []int = foo()
var interfaceSlice []interface{} = make([]interface{}, len(dataSlice))
for i, d := range dataSlice {
interfaceSlice[i] = d
}
For setting the Socket timeout, you need to follow these steps:
import socket
socks = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socks.settimeout(10.0) # settimeout is the attr of socks.
You're trying to use key functions with lambda functions.
Python and other languages like C# or F# use lambda functions.
Also, when it comes to key functions and according to the documentation
Both list.sort() and sorted() have a key parameter to specify a function to be called on each list element prior to making comparisons.
...
The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes. This technique is fast because the key function is called exactly once for each input record.
So, key functions have a parameter key and it can indeed receive a lambda function.
In Real Python there's a nice example of its usage. Let's say you have the following list
ids = ['id1', 'id100', 'id2', 'id22', 'id3', 'id30']
and want to sort through its "integers". Then, you'd do something like
sorted_ids = sorted(ids, key=lambda x: int(x[2:])) # Integer sort
and printing it would give
['id1', 'id2', 'id3', 'id22', 'id30', 'id100']
In your particular case, you're only missing to write key=
before lambda. So, you'd want to use the following
a = sorted(a, key=lambda x: x.modified, reverse=True)
To handle session properly, take a look at http://php.net/manual/en/session.configuration.php.
There you'll find these variables:
These control the garbage collector (GC) probability of running with each page request.
You could set those with ini_set() at the beginning of your script or .htaccess file so you get certainty to some extent they will get deleted sometime.
I found that using a fixed width with padding seems to work (in ff at least)
.Btn
{
width:75px;
padding:10px;
}
Try it at:-
I prefer the lambda form of the DropDownList helper - see MVC 3 Layout Page, Razor Template, and DropdownList
If you want to use the SelectList, then I think this bug report might assist - http://aspnet.codeplex.com/workitem/4932
Yes you can. You can even test it:
var i = 0;_x000D_
var timer = setInterval(function() {_x000D_
console.log(++i);_x000D_
if (i === 5) clearInterval(timer);_x000D_
console.log('post-interval'); //this will still run after clearing_x000D_
}, 200);
_x000D_
In this example, this timer clears when i
reaches 5.
The reason your code doesn't work is because the count function is asynchronous, it doesn't synchronously return a value.
Here's an example of usage:
userModel.count({}, function( err, count){
console.log( "Number of users:", count );
})
For sending data to a service you can use:
Intent intent = new Intent(getApplicationContext(), YourService.class);
intent.putExtra("SomeData","ItValue");
startService(intent);
And after in service in onStartCommand() get data from intent.
For sending data or event from a service to an application (for one or more activities):
private void sendBroadcastMessage(String intentFilterName, int arg1, String extraKey) {
Intent intent = new Intent(intentFilterName);
if (arg1 != -1 && extraKey != null) {
intent.putExtra(extraKey, arg1);
}
sendBroadcast(intent);
}
This method is calling from your service. You can simply send data for your Activity.
private void someTaskInYourService(){
//For example you downloading from server 1000 files
for(int i = 0; i < 1000; i++) {
Thread.sleep(5000) // 5 seconds. Catch in try-catch block
sendBroadCastMessage(Events.UPDATE_DOWNLOADING_PROGRESSBAR, i,0,"up_download_progress");
}
For receiving an event with data, create and register method registerBroadcastReceivers() in your activity:
private void registerBroadcastReceivers(){
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int arg1 = intent.getIntExtra("up_download_progress",0);
progressBar.setProgress(arg1);
}
};
IntentFilter progressfilter = new IntentFilter(Events.UPDATE_DOWNLOADING_PROGRESS);
registerReceiver(broadcastReceiver,progressfilter);
For sending more data, you can modify method sendBroadcastMessage();
. Remember: you must register broadcasts in onResume() & unregister in onStop() methods!
UPDATE
Please don't use my type of communication between Activity & Service. This is the wrong way. For a better experience please use special libs, such us:
1) EventBus from greenrobot
2) Otto from Square Inc
P.S. I'm only using EventBus from greenrobot in my projects,
The git cherry-pick <commit>
command allows you to take a single commit (from whatever branch) and, essentially, rebase it in your working branch.
Chapter 5 of the Pro Git book explains it better than I can, complete with diagrams and such. (The chapter on Rebasing is also good reading.)
Lastly, there are some good comments on the cherry-picking vs merging vs rebasing in another SO question.
You can also combine them I guess:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.factory('myService', function() {
return {
foo: function() {
alert("I'm foo!");
}
};
});
myApp.run(function($rootScope, myService) {
$rootScope.appData = myService;
});
myApp.controller('MainCtrl', ['$scope', function($scope){
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="appData.foo()">Call foo</button>
</body>
</html>
private void loadData() {
Scanner scanner = null;
try {
scanner = new Scanner(new File(getFileName()));
while (scanner.hasNextLine()) {
Scanner lijnScanner = new Scanner(scanner.nextLine());
lijnScanner.useDelimiter(";");
String stadVan = lijnScanner.next();
String stadNaar = lijnScanner.next();
double km = Double.parseDouble(lijnScanner.next());
this.voegToe(new TweeSteden(stadVan, stadNaar), km);
}
} catch (FileNotFoundException e) {
throw new DbException(e.getMessage(), e);
} finally {
if(scanner != null){
scanner.close();
}
}
}
Constructors are not normal methods and they cannot be "overridden". Saying that a constructor can be overridden would imply that a superclass constructor would be visible and could be called to create an instance of a subclass. This isn't true... a subclass doesn't have any constructors by default (except a no-arg constructor if the class it extends has one). It has to explicitly declare any other constructors, and those constructors belong to it and not to its superclass, even if they take the same parameters that the superclass constructors take.
The stuff you mention about default no arg constructors is just an aspect of how constructors work and has nothing to do with overriding.
go 1.0 includes a http server & util for serving files with a few lines of code.
package main
import (
"fmt"; "log"; "net/http"
)
func main() {
fmt.Println("Serving files in the current directory on port 8080")
http.Handle("/", http.FileServer(http.Dir(".")))
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
Run this source using go run myserver.go
or to build an executable go build myserver.go
instead of overwriting, create it as different css and call it in your element as other css(multiple css).
Something like:
.flex-control-thumbs li
{ margin: 0; }
Internal CSS:
.additional li
{width: 25%; float: left;}
<ul class="flex-control-thumbs additional"> </ul> /* assuming parent is ul */
FILE *f = fopen("file.txt", "w");
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
/* print some text */
const char *text = "Write this to the file";
fprintf(f, "Some text: %s\n", text);
/* print integers and floats */
int i = 1;
float py = 3.1415927;
fprintf(f, "Integer: %d, float: %f\n", i, py);
/* printing single chatacters */
char c = 'A';
fprintf(f, "A character: %c\n", c);
fclose(f);
In my case, I was missing a "name" attribute on my input element.
So I was having this problem, none of the other remedies worked. The error message was opaque, but checking dmesg was key:
[ 10.118255] NVRM: API mismatch: the client has the version 410.79, but
NVRM: this kernel module has the version 384.130. Please
NVRM: make sure that this kernel module and all NVIDIA driver
NVRM: components have the same version.
However I had completely removed the 384 version, and removed any remaining kernel drivers nvidia-384*
. But even after reboot, I was still getting this. Seeing this meant that the kernel was still compiled to reference 384, but was only finding 410. So I recompiled my kernel:
# uname -a # find the kernel it's using
Linux blah 4.13.0-43-generic #48~16.04.1-Ubuntu SMP Thu May 17 12:56:46 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
# update-initramfs -c -k 4.13.0-43-generic #recompile it
# reboot
And then it worked.
After removing 384, I still had 384 files in: /var/lib/dkms/nvidia-XXX/XXX.YY/4.13.0-43-generic/x86_64/module /lib/modules/4.13.0-43-generic/kernel/drivers
I recommend using the locate
command (not installed by default) rather than searching the filesystem every time.
I think a simpler and more elegant solution to insert a String in a certain position would be this one-liner:
target.replaceAll("^(.{" + position + "})", "$1" + insert);
For example, to insert a missing :
into a time String:
"-0300".replaceAll("^(.{3})", "$1:");
What it does is, matches position
characters from the beginning of the string, groups that, and replaces the group with itself ($1
) followed by the insert
string. Mind the replaceAll, even though there's always one occurrence, because the first parameter must be a regex.
Of course it does not have the same performance as the StringBuilder solution, but I believe the succinctness and elegance as a simple and easier to read one-liner (compared to a huge method) is sufficient for making it the preferred solution in most non performance-critical use-cases.
Note I'm solving the generic problem in the title for documentation reasons, of course if you are dealing with decimal numbers you should use the domain-specific solutions already proposed.
The point seems to be that sometimes, you need a property that has automatic storage and some behavior, for instance to notify other objects that the property just changed. When all you have is get
/set
, you need another field to hold the value. With willSet
and didSet
, you can take action when the value is modified without needing another field. For instance, in that example:
class Foo {
var myProperty: Int = 0 {
didSet {
print("The value of myProperty changed from \(oldValue) to \(myProperty)")
}
}
}
myProperty
prints its old and new value every time it is modified. With just getters and setters, I would need this instead:
class Foo {
var myPropertyValue: Int = 0
var myProperty: Int {
get { return myPropertyValue }
set {
print("The value of myProperty changed from \(myPropertyValue) to \(newValue)")
myPropertyValue = newValue
}
}
}
So willSet
and didSet
represent an economy of a couple of lines, and less noise in the field list.
Most answers are using iloc
which is good for selection by position.
If you need selection-by-label loc
would be more convenient.
For getting a value explicitly (equiv to deprecated df.get_value('a','A'))
# this is also equivalent to df1.at['a','A'] In [55]: df1.loc['a', 'A'] Out[55]: 0.13200317033032932
I've made an answer with some more details here : https://stackoverflow.com/a/11045462/592477
Or you can read it there ==>
When you use loadbalancing it means you have several instances of tomcat and you need to divide loads.
Can you load the GUIDs into a scratch table then do a
... WHERE var IN SELECT guid FROM #scratchtable
The best way to stay on the same page is to post to the same page:
<form method="post" action="<?=$_SERVER['PHP_SELF'];?>">
The simplest solution I found was to add this to my img-element:
style="display:block;margin:auto;"
It seems I don't need to add "0" before the "auto" as suggested by others. Maybe that is the proper way, but it works well enough for my purposes without the "0" as well. At least on latest Firefox, Chrome, and Edge.
You can simply check out a new branch, and then commit:
git checkout -b my_new_branch
git commit
Checking out the new branch will not discard your changes.
You have to set the associatedEmployee on the Vehicle before persisting the Employee.
Employee newEmployee = new Employee("matt");
vehicle1.setAssociatedEmployee(newEmployee);
vehicles.add(vehicle1);
newEmployee.setVehicles(vehicles);
Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);
firstOrNew
will create record if not exist and updating a row if already exist.
You can also use updateOrCreate
here is the full example
$flight = App\Flight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99]
);
If there's a flight from Oakland to San Diego, set the price to $99. if not exist create new row
Reference Doc here: (https://laravel.com/docs/5.5/eloquent)
If you just need a simple backup to an archive, you can try my little utility: https://github.com/loomchild/volume-backup
Example
Backup:
docker run -v some_volume:/volume -v /tmp:/backup --rm loomchild/volume-backup backup archive1
will archive volume named some_volume
to /tmp/archive1.tar.bz2
archive file
Restore:
docker run -v some_volume:/volume -v /tmp:/backup --rm loomchild/volume-backup restore archive1
will wipe and restore volume named some_volume
from /tmp/archive1.tar.bz2
archive file.
More info: https://medium.com/@loomchild/backup-restore-docker-named-volumes-350397b8e362
The simple solution, which no one have mentioned yet, is to just ignore the problem. If I try to use an int
as a template type in a function template that expects a container class such as vector or list, then I will get a compile error. Crude and simple, but it solves the problem. The compiler will try to use the type you specify, and if that fails, it generates a compile error.
The only problem with that is that the error messages you get are going to be tricky to read. It is nevertheless a very common way to do this. The standard library is full of function or class templates that expect certain behavior from the template type, and do nothing to check that the types used are valid.
If you want nicer error messages (or if you want to catch cases that wouldn't produce a compiler error, but still don't make sense) you can, depending on how complex you want to make it, use either Boost's static assert or the Boost concept_check library.
With an up-to-date compiler you have a built_in static_assert
, which could be used instead.
I ran into this problem on Windows 10 (N) with a new Anaconda installation based on Python 3.7 (OpenCV version 4.0). None of the above advice helped (such as installing OpenCV from the unofficial site nor installing VC Redistributable).
I checked DLL dependencies of ...\AppData\Local\conda\conda\envs\foo\Lib\site-packages\cv2\cv2.cp37-win_amd64.pyd
using dumpbin.exe
according to this github issue. I noticed a library MF.dll
, which I figured out belongs to Windows Media Foundation.
So I installed Media Feature Pack for N versions of Windows 10 and voilà, the issue was resolved!
Expanding on the above jQuery solution to cope with any delays in loading the frame contents.
$('iframe').each(function(){
function injectCSS(){
$iframe.contents().find('head').append(
$('<link/>', { rel: 'stylesheet', href: 'iframe.css', type: 'text/css' })
);
}
var $iframe = $(this);
$iframe.on('load', injectCSS);
injectCSS();
});
You are calling DoDownloadAsync() but you don't wait it. So your program going to the next line. But there is another problem, Async methods should return Task
or Task<T>
, if you return nothing and you want your method will be run asyncronously you should define your method like this:
private static async Task DoDownloadAsync() { WebClient w = new WebClient(); string txt = await w.DownloadStringTaskAsync("http://www.google.com/"); Debug.WriteLine(txt); }
And in Main method you can't await for DoDownloadAsync
, because you can't use await keyword in non-async function, and you can't make Main
async. So consider this:
var result = DoDownloadAsync(); Debug.WriteLine("DoDownload done"); result.Wait();
On Windows OS:
1) open following file for edit (as an admin): C:\Windows\System32\drivers\etc\hosts
(this file has no extension)
2) on the bottom, add one line: 127.0.0.1 tools.google.com
3) save the file
4) enjoy old Chrome
How about this:
$(document).ready(function() {
$('#subscribeForm').submit(function() {
var $fields = $(this).find('input[name="list"]:checked');
if (!$fields.length) {
alert('You must check at least one box!');
return false; // The form will *not* submit
}
});
});
in my case just removing background-image
from nav-bar
item solved the problem
.navbar-default .navbar-nav > .active > a:focus {
.
.
.
background-image: none;
}
Please note that you can use view.setZ(float)
starting from API level 21. Here you can find more info.
Are you sure? This forum thread suggests it might be your watch window. Try outputting the string to a MsgBox, which can display a maximum of 1024 characters:
MsgBox RunMacros
I would set up a shortcut, either to CMD or to the thing you want to run, then set the properties of the shortcut to require admin, and then run the shortcut from your batch file. I haven't tested to confirm it will respect the properties, but I think it's more elegant and doesn't require activating the Administrator account.
Also if you do it as a scheduled task (which can be set up from code) there is an option to run it elevated there.
You can set a very small initial delay-time (e.g. 100) and set it to your desired delay-time within the function:
var delay = 100;_x000D_
_x000D_
function foo() {_x000D_
console.log("Change initial delay-time to what you want.");_x000D_
delay = 12000;_x000D_
setTimeout(foo, delay);_x000D_
}
_x000D_
Two steps, for example,
package main
import (
"fmt"
"strings"
)
func main() {
s := strings.Split("127.0.0.1:5432", ":")
ip, port := s[0], s[1]
fmt.Println(ip, port)
}
Output:
127.0.0.1 5432
One step, for example,
package main
import (
"fmt"
"net"
)
func main() {
host, port, err := net.SplitHostPort("127.0.0.1:5432")
fmt.Println(host, port, err)
}
Output:
127.0.0.1 5432 <nil>
You can use Create USer to create a user
CREATE LOGIN sam
WITH PASSWORD = '340$Uuxwp7Mcxo7Khy';
USE AdventureWorks;
CREATE USER sam FOR LOGIN sam;
GO
and to Grant (Read-only access) you can use the following
GRANT SELECT TO sam
Hope that helps.
If you are using RestTemplateBuilder
may be the usual thing wouldn't work. You need to add this in your test class along with when(condition).
@Before
public void setup() {
ReflectionTestUtils.setField(service, "restTemplate", restTemplate);
}
Modulus operator; gives the remainder of the left value divided by the right value. Like:
3 % 1
would equal zero (since 3 divides evenly by 1)
3 % 2
would equal 1 (since dividing 3 by 2 results in a remainder of 1).
Another way to do:
First, install these modules: url-loader
, file-loader
Using npm: npm install --save-dev url-loader file-loader
Next, add this to your Webpack config:
module: {
loaders: [
{ test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192' }
]
}
limit
: Byte limit to inline files as Data URL
You need to install both modules: url-loader
and file-loader
Finally, you can do:
<img src={require('./my-path/images/my-image.png')}/>
You can investigate these loaders further here:
url-loader: https://www.npmjs.com/package/url-loader
file-loader: https://www.npmjs.com/package/file-loader
erlswf is an opensource project written in erlang for decompiling .swf files.
Here's the site: https://github.com/bef/erlswf
The native way is indeed setInterval()
/clearInterval()
, but if you are already using the Prototype library you can take advantage of PeriodicalExecutor:
new PeriodicalUpdator(myEvent, seconds);
This prevents overlapping calls. From http://www.prototypejs.org/api/periodicalExecuter:
"it shields you against multiple parallel executions of the callback function, should it take longer than the given interval to execute (it maintains an internal “running” flag, which is shielded against exceptions in the callback function). This is especially useful if you use one to interact with the user at given intervals (e.g. use a prompt or confirm call): this will avoid multiple message boxes all waiting to be actioned."
I know this is not an ideal question to answer but as the OP seems to be a beginner, I'd love to share some basic knowledge with him... Hope everybody understands
OP, you can convert a string to type Boolean
by using any of the methods stated below:
string sample = "True";
bool myBool = bool.Parse(sample);
///or
bool myBool = Convert.ToBoolean(sample);
bool.Parse
expects one parameter which in this case is sample
, .ToBoolean
also expects one parameter.
You can use TryParse
which is the same as Parse
but it doesn't throw any exception :)
string sample = "false";
Boolean myBool;
if (Boolean.TryParse(sample , out myBool))
{
}
Please note that you cannot convert any type of string to type Boolean
because the value of a Boolean
can only be True
or False
Hope you understand :)
You can test using eval
:
try:
eval("1 if True else 2")
except SyntaxError:
# doesn't have ternary
Also, with
is available in Python 2.5, just add from __future__ import with_statement
.
EDIT: to get control early enough, you could split it into different .py
files and check compatibility in the main file before importing (e.g. in __init__.py
in a package):
# __init__.py
# Check compatibility
try:
eval("1 if True else 2")
except SyntaxError:
raise ImportError("requires ternary support")
# import from another module
from impl import *
I think the easiest way for verifying an argument object is to use the refEq
method:
Mockito.verify(mockedObject).someMethodOnMockedObject(ArgumentMatchers.refEq(objectToCompareWith));
It can be used even if the object doesn't implement equals()
, because reflection is used. If you don't want to compare some fields, just add their names as arguments for refEq
.
To get Ant running on your Mac in 5 minutes, follow these steps.
Open up your terminal.
Perform these commands in order:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew install ant
If you don't have Java installed yet, you will get the following error: "Error: An unsatisfied requirement failed this build."
Run this command next: brew cask install java
to fix this.
The installation will resume.
Check your version of by running this command:
ant -version
And you're ready to go!
I had the same issue (even though the project was compiling/working fine in Eclipse), it was not when using the command line build. The reason was that I wasn't using the correct folder structure for mvn: "src/main/java/com" etc. It is looking at these folders by default (I was using "/scr/main/com" etc. which caused issues).
if you have bash, you can use extended globbing
shopt -s extglob
shopt -s nullglob
shopt -s nocaseglob
for file in +([0-9])_+([a-z])_+([a-z0-9]).jpg
do
IFS="_"
set -- $file
echo "This is your captured output : $2"
done
or
ls +([0-9])_+([a-z])_+([a-z0-9]).jpg | while read file
do
IFS="_"
set -- $file
echo "This is your captured output : $2"
done
If you had caught the error, you would have seen this:
jsonString, err := json.Marshal(datas)
fmt.Println(err)
// [] json: unsupported type: map[int]main.Foo
The thing is you cannot use integers as keys in JSON; it is forbidden. Instead, you can convert these values to strings beforehand, for instance using strconv.Itoa
.
See this post for more details: https://stackoverflow.com/a/24284721/2679935
for me this is working ok tested in chrome v72
function down_file(url,name){
var a = $("<a>")
.attr("href", url)
.attr("download", name)
.appendTo("body");
a[0].click();
a.remove();
}
down_file('https://www.useotools.com/uploads/nulogo[1].png','logo.png')
This answer might be stupid, but I spent quite some time to figure it out.
What happened to me was I didn't set display: flex
to the container. And of course, justify-content
won't work without a container with that property.
If you run jupyter in the background like me:
jupyter notebook &> /dev/null &
Then to exit jupyter completely, instead of Ctl-C, make an alias command:
echo 'alias quitjupyter="kill $(pgrep jupyter)"' >> ~/.bashrc
Restart your terminal. Kill all jupyter instances:
quitjupyter
Note: use double quotes inside of single quotes as shown above. The other way around will evaluate the expression before writing it to your .bashrc (you want to write the command itself not 'kill 1430' or whatever process number may be associated with a current jupyter instance). Of course you can use any alias you wish. I actually use 'qjup':
echo 'alias qjup="kill $(pgrep jupyter)"' >> ~/.bashrc
Restart your terminal. Kill all jupyter instances:
qjup
You could target all text boxes with input[type=text]
and then explicitly define the class for the textboxes who need it.
You can code like below :
input[type=text] {_x000D_
padding: 0;_x000D_
height: 30px;_x000D_
position: relative;_x000D_
left: 0;_x000D_
outline: none;_x000D_
border: 1px solid #cdcdcd;_x000D_
border-color: rgba(0, 0, 0, .15);_x000D_
background-color: white;_x000D_
font-size: 16px;_x000D_
}_x000D_
_x000D_
.advancedSearchTextbox {_x000D_
width: 526px;_x000D_
margin-right: -4px;_x000D_
}
_x000D_
<input type="text" class="advancedSearchTextBox" />
_x000D_
I hope the following sequence of code will help you:
Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight, config);
Canvas canvas = new Canvas(targetBitmap);
Matrix matrix = new Matrix();
matrix.setRotate(mRotation,source.getWidth()/2,source.getHeight()/2);
canvas.drawBitmap(source, matrix, new Paint());
If you check the following method from ~frameworks\base\graphics\java\android\graphics\Bitmap.java
public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height,
Matrix m, boolean filter)
this would explain what it does with rotation and translate.
I've only seen the parsing error when the android version on the device was lower than the version the app was compiled for. For example if the app is compiled for android OS v2.2 and your device only has android OS v2.1 you'd get a parse error when you try to install the app.
I believe the best way to do this is to use the LocalTimezone
class defined in the datetime.tzinfo
documentation (goto http://docs.python.org/library/datetime.html#tzinfo-objects and scroll down to the "Example tzinfo classes" section):
Assuming Local
is an instance of LocalTimezone
t = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=utc)
local_t = t.astimezone(Local)
then str(local_t)
gives:
'2009-07-11 04:44:59.193982+10:00'
which is what you want.
(Note: this may look weird to you because I'm in New South Wales, Australia which is 10 or 11 hours ahead of UTC)
In JavaScript 1.8.5, Object.getOwnPropertyNames
returns an array of all properties found directly upon a given object.
Object.getOwnPropertyNames ( obj )
and another method Object.keys
, which returns an array containing the names of all of the given object's own enumerable properties.
Object.keys( obj )
I used forEach
to list values and keys in obj, same as for (var key in obj) ..
Object.keys(obj).forEach(function (key) {
console.log( key , obj[key] );
});
This all are new features in ECMAScript , the mothods getOwnPropertyNames
, keys
won't supports old browser's.
Comment from answer: "make sure you use the same open connection for all the database calls inside the transaction. – Magnus"
Our users are stored in a separate db from the data I was working with in the transactions. Opening the db connection to get the user was causing this error for me. Moving the other db connection and user lookup outside of the transaction scope fixed the error.
See this similar question and answer to searching with case insensitivity - SQL server ignore case in a where expression
Try using something like:
SELECT DISTINCT COL_NAME
FROM myTable
WHERE COL_NAME COLLATE SQL_Latin1_General_CP1_CI_AS LIKE '%priceorder%'
In postgresql I can write a similar query with a date-format function (to_char) and grouping just by date:
SELECT to_char (datum, 'MM-YYYY') AS mjesec
FROM test
GROUP BY datum
ORDER BY datum;
Such thing is surely possible with SQL-Server too, isn't it?
You'll get more consistency if you use width (your second example).
if you set your context model as code first based on exist database so you have to for set migration:
Add-Migration InitialCreate –IgnoreChanges
Update-database -force
and then change your context model and set:
Add-migration RemoveIspositive
Update-database -force
Make sure ssh-agent is running by executing the following command on your terminal:
eval $(ssh-agent -s)
Source: Github documentation
If you can save the workbook then you have the option to use ADO and Jet/ACE to treat the workbook as a database, and execute SQL against the sheet.
The MSDN information on how to hit Excel using ADO can be found here.
Because your else
isn't attached to anything. The if
without braces only encompasses the single statement that immediately follows it.
if (choice==5)
{
System.out.println("End of Game\n Thank you for playing with us!");
break;
}
else
{
System.out.println("Not a valid choice!\n Please try again...\n");
}
Not using braces is generally viewed as a bad practice because it can lead to the exact problems you encountered.
In addition, using a switch
here would make more sense.
int choice;
boolean keepGoing = true;
while(keepGoing)
{
System.out.println("---> Your choice: ");
choice = input.nextInt();
switch(choice)
{
case 1:
playGame();
break;
case 2:
loadGame();
break;
// your other cases
// ...
case 5:
System.out.println("End of Game\n Thank you for playing with us!");
keepGoing = false;
break;
default:
System.out.println("Not a valid choice!\n Please try again...\n");
}
}
Note that instead of an infinite for
loop I used a while(boolean)
, making it easy to exit the loop. Another approach would be using break with labels.
Use debug_backtrace
to get a backtrace of what functions and methods had been called and what files had been included that led to the point where debug_backtrace
has been called.
You need to make some changes in the compiler. In Dev C++ Compiler: 1. Go to compiler settings/compiler Options. 2. Click on General Tab 3. Check the checkbox (Add the following commands when calling the compiler. 4. write -std=c++11 5. click Ok
If anyone looking for a drop-in, zero-config and zero-dependencies library for the above use-case, try pace.js (http://github.hubspot.com/pace/docs/welcome/).
It automatically hooks to events (ajax, readyState, history pushstate, js event loop etc) and show a customizable loader.
Worked well with our react/relay projects (handles navigation changes using react-router, relay requests) (Not affliated; had used pace.js for our projects and it worked great)
You need to set a name on the <select>
tag like so:
<select name="select_catalog" id="select_catalog">
You can get it in php with this:
$_POST['select_catalog'];
you can use command
date | awk '{print $4}'| cut -d ':' -f3
as you mentioned using only the date|awk '{print $4}'
pipeline gives you something like this
20:18:19
so as we can see if we want to extract some part of this string then we need a delimiter , for our case it is :
, so we decide to chop on the basis of :
.
Now this delimiter will chop the string into three parts i.e. 20 ,18 and 19 , as we want the second one we use -f2 in our command.
to sum up ,
cut
: chops some string based on delimeter.
-d
: delimeter (here :
)
-f2
: the chopped off token that we want.
Please don't put members into an interface; though it's correct in phrasing. Please don't "delete" an interface.
class IInterface()
{
Public:
Virtual ~IInterface(){};
…
}
Class ClassImpl : public IInterface
{
…
}
Int main()
{
IInterface* pInterface = new ClassImpl();
…
delete pInterface; // Wrong in OO Programming, correct in C++.
}
Here comes the long-winded – yet easy to understand – script, inspired by the solution of nicerobot, that only requests the response headers and avoids using IFS as suggested here. It outputs a bounce message when it encounters a response >= 400. This echo can be replaced with a bounce-script.
# set the url to probe
url='http://localhost:8080'
# use curl to request headers (return sensitive default on timeout: "timeout 500"). Parse the result into an array (avoid settings IFS, instead use read)
read -ra result <<< $(curl -Is --connect-timeout 5 "${url}" || echo "timeout 500")
# status code is second element of array "result"
status=${result[1]}
# if status code is greater than or equal to 400, then output a bounce message (replace this with any bounce script you like)
[ $status -ge 400 ] && echo "bounce at $url with status $status"
SQL Server doesn't allow you to pass parameters to a procedure that you haven't defined. I think the closest you can get to this sort of design is to use optional parameters like so:
CREATE PROCEDURE GetTaskEvents
@TaskName varchar(50),
@ID int = NULL
AS
BEGIN
-- SP Logic
END;
You would need to include every possible parameter that you might use in the definition. Then you'd be free to call the procedure either way:
EXEC GetTaskEvents @TaskName = 'TESTTASK', @ID = 2;
EXEC GetTaskEvents @TaskName = 'TESTTASK'; -- @ID gets NULL here
I was using node v12.13.1, so I've downgraded to v10.19.0 and works fine after that.
yes, simply use colspan.
This is what worked for me:
recyclerView.setAdapter(new RecyclerViewAdapter(newList));
recyclerView.invalidate();
After creating a new adapter that contains the updated list (in my case it was a database converted into an ArrayList) and setting that as adapter, I tried recyclerView.invalidate()
and it worked.
This is really just an expansion of Freddy Rios' accepted answer only using Generics.
public static bool IsNullOrDefault<T>(this Nullable<T> value) where T : struct
{
return default(T).Equals( value.GetValueOrDefault() );
}
public static bool IsValue<T>(this Nullable<T> value, T valueToCheck) where T : struct
{
return valueToCheck.Equals((value ?? valueToCheck));
}
NOTE we don't need to check default(T) for null since we are dealing with either value types or structs! This also means we can safely assume T valueToCheck will not be null; Remember here that T? is shorthand Nullable<T> so by adding the extension to Nullable<T> we get the method in int?, double?, bool? etc.
Examples:
double? x = null;
x.IsNullOrDefault(); //true
int? y = 3;
y.IsNullOrDefault(); //false
bool? z = false;
z.IsNullOrDefault(); //true
I too encountered the same scenario and found out two solutions after googling for several times. Hope this helps.
Way 01:
Before trying to open the file in Excel, find it in Windows' File Explorer. Right-click the file and select Properties. At the bottom of the General tab, click the Unblock button. Once you unblock a file, Windows should remember and Excel should not ask you again. This option is available for some file types, but not others. If you don't have an Unblock button, use Way 2.
Way 02:
This option is better if you usually store your downloaded Excel files in one folder. In Excel, click File » Options » Trust Center » Trust Center Settings » Trusted Locations. Click Add new location. Browse to the folder where you store your Excel files, select Subfolders of this location are also trusted, and click OK.
Go into task manager and see if you have any Microsoft Excel Processes running in the background. I closed my excel background processes and my code worked again.
import { FormControl, FormGroup, AbstractControl, FormBuilder, Validators } from '@angular/forms';_x000D_
_x000D_
_x000D_
this.userInfoForm = new FormGroup({_x000D_
userInfoUserName: new FormControl({ value: '' }, Validators.compose([Validators.required])),_x000D_
userInfoName: new FormControl({ value: '' }, Validators.compose([Validators.required])),_x000D_
userInfoSurName: new FormControl({ value: '' }, Validators.compose([Validators.required]))_x000D_
});
_x000D_
<form [formGroup]="userInfoForm" class="form-horizontal">_x000D_
<div class="form-group">_x000D_
<label class="control-label"><i>*</i> User Name</label>_x000D_
<input type="text" formControlName="userInfoUserName" class="form-control" [(ngModel)]="userInfo.userName">_x000D_
</div>_x000D_
<div class="form-group">_x000D_
<label class="control-label"><i>*</i> Name</label>_x000D_
<input type="text" formControlName="userInfoName" class="form-control" [(ngModel)]="userInfo.name">_x000D_
</div>_x000D_
<div class="form-group">_x000D_
<label class="control-label"><i>*</i> Surname</label>_x000D_
<input type="text" formControlName="userInfoSurName" class="form-control" [(ngModel)]="userInfo.surName">_x000D_
</div>_x000D_
</form>
_x000D_
The problem is that you are using gulp 4 and the syntax in gulfile.js is of gulp 3. So either downgrade your gulp to 3.x.x or make use of gulp 4 syntaxes.
Syntax Gulp 3:
gulp.task('default', ['sass'], function() {....} );
Syntax Gulp 4:
gulp.task('default', gulp.series(sass), function() {....} );
You can read more about gulp and gulp tasks on: https://medium.com/@sudoanushil/how-to-write-gulp-tasks-ce1b1b7a7e81
I know this is an old topic, but I think it is still relevant, and would like to share an implementation of an array comparison method which I feel strikes the right balance between performance and elegance.
static bool CollectionEquals<T>(ICollection<T> a, ICollection<T> b, IEqualityComparer<T> comparer = null)
{
return ReferenceEquals(a, b) || a != null && b != null && a.Count == b.Count && a.SequenceEqual(b, comparer);
}
The idea here is to check for all of the early out conditions first, then fall back on SequenceEqual
. It also avoids doing extra branching and instead relies on boolean short-circuit to avoid unecessary execution. I also feel it looks clean and is easy to understand.
Also, by using ICollection
for the parameters, it will work with more than just arrays.
You can just use the TimeOfDay property of date time, which is TimeSpan type:
DateTime.TimeOfDay
This property has been around since .NET 1.1
More information: http://msdn.microsoft.com/en-us/library/system.datetime.timeofday(v=vs.110).aspx
Here is what I ended up doing to work around the error.
First, I set up the database recovery model as SIMPLE. More information here.
Then, by deleting some old files I was able to make 5GB of free space which gave the log file more space to grow.
I reran the DELETE statement sucessfully without any warning.
I thought that by running the DELETE statement the database would inmediately become smaller thus freeing space in my hard drive. But that was not true. The space freed after a DELETE statement is not returned to the operating system inmediatedly unless you run the following command:
DBCC SHRINKDATABASE (MyDb, 0);
GO
More information about that command here.
UPDATE: Using Java 8 Syntax
List<DataPoint> myList = new ArrayList<>();
//Fill up myList with your Data Points
List<DataPoint> dataPointsCalledJohn =
myList
.stream()
.filter(p-> p.getName().equals(("john")))
.collect(Collectors.toList());
If you don't mind using an external libaray - you can use Predicates from the Google Guava library as follows:
class DataPoint {
String name;
String getName() { return name; }
}
Predicate<DataPoint> nameEqualsTo(final String name) {
return new Predicate<DataPoint>() {
public boolean apply(DataPoint dataPoint) {
return dataPoint.getName().equals(name);
}
};
}
public void main(String[] args) throws Exception {
List<DataPoint> myList = new ArrayList<DataPoint>();
//Fill up myList with your Data Points
Collection<DataPoint> dataPointsCalledJohn =
Collections2.filter(myList, nameEqualsTo("john"));
}
In Python >= 3.5 using subprocess.run
works for me:
import subprocess
cmd = 'echo foo; sleep 1; echo foo; sleep 2; echo foo'
subprocess.run(cmd, shell=True)
(getting the output during execution also works without shell=True
)
https://docs.python.org/3/library/subprocess.html#subprocess.run
Branch-prediction gain!
It is important to understand that branch misprediction doesn't slow down programs. The cost of a missed prediction is just as if branch prediction didn't exist and you waited for the evaluation of the expression to decide what code to run (further explanation in the next paragraph).
if (expression)
{
// Run 1
} else {
// Run 2
}
Whenever there's an if-else
\ switch
statement, the expression has to be evaluated to determine which block should be executed. In the assembly code generated by the compiler, conditional branch instructions are inserted.
A branch instruction can cause a computer to begin executing a different instruction sequence and thus deviate from its default behavior of executing instructions in order (i.e. if the expression is false, the program skips the code of the if
block) depending on some condition, which is the expression evaluation in our case.
That being said, the compiler tries to predict the outcome prior to it being actually evaluated. It will fetch instructions from the if
block, and if the expression turns out to be true, then wonderful! We gained the time it took to evaluate it and made progress in the code; if not then we are running the wrong code, the pipeline is flushed, and the correct block is run.
Let's say you need to pick route 1 or route 2. Waiting for your partner to check the map, you have stopped at ## and waited, or you could just pick route1 and if you were lucky (route 1 is the correct route), then great you didn't have to wait for your partner to check the map (you saved the time it would have taken him to check the map), otherwise you will just turn back.
While flushing pipelines is super fast, nowadays taking this gamble is worth it. Predicting sorted data or a data that changes slowly is always easier and better than predicting fast changes.
O Route 1 /-------------------------------
/|\ /
| ---------##/
/ \ \
\
Route 2 \--------------------------------
import org.apache.commons.lang.math.NumberUtils;
This will handle null
NumberUtils.createLong(String)
If you are using Laravel as your Backend, then edit your .htaccess file by just pasting this code, to solve problem CROS in your Angular or IONIC project
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
You can paste the following code to the console to scroll up/down using the a/z keyboard keys. If you want to set your own keys you can visit this page to get the keycodes
function KeyPress(e) {
var evtobj = window.event? event : e
if (evtobj.keyCode == 90) {
window.scrollBy(0, 100)
}
if (evtobj.keyCode == 65) {
window.scrollBy(0, -100)
}
}
document.onkeydown = KeyPress;
I've had similar problem in my software. We've wanted to merge several PDF files into one PDF file and submit it to an outer service. We've been using the FPDI solution as shown in Christa's solution.
However, the input PDF's we've been using could be in version higher than 1.7. We've decided to evaluate the FPDI commercial add-on. However, it turned out that some of the documents scanned by our office copier were having malformed indexes, which crashed the commercial FPDI add-on. So we've decided to use Ghostscript solution as in Chauhan's answer.
But then we got some strange metadata in the output PDF properties.
Finally we've decided to join two solutions to get PDF's merged and downgraded by Ghostscript, but the metadata is set by FPDI. We don't know yet how it would work with some advanced formatted pdfs, but for scans we use it works just fine. Here's our class excerpt:
class MergedPDF extends \FPDI
{
private $documentsPaths = array();
public function Render()
{
$outputFileName = tempnam(sys_get_temp_dir(), 'merged');
// merge files and save resulting file as PDF version 1.4 for FPDI compatibility
$cmd = "/usr/bin/gs -q -dNOPAUSE -dBATCH -dCompatibilityLevel=1.4 -sDEVICE=pdfwrite -sOutputFile=$outputFileName";
foreach ($this->getDocumentsPaths() as $pdfpath) {
$cmd .= " $pdfpath ";
}
$result = shell_exec($cmd);
$this->SetCreator('Your Software Name');
$this->setPrintHeader(false);
$numPages = $this->setSourceFile($outputFileName);
for ($i = 1; $i <= $numPages; $i++) {
$tplIdx = $this->importPage($i);
$this->AddPage();
$this->useTemplate($tplIdx);
}
unlink($outputFileName);
$content = $this->Output(null, 'S');
return $content;
}
public function getDocumentsPaths()
{
return $this->documentsPaths;
}
public function setDocumentsPaths($documentsPaths)
{
$this->documentsPaths = $documentsPaths;
}
public function addDocumentPath($documentPath)
{
$this->documentsPaths[] = $documentPath;
}
}
The usage of this class is as follows:
$pdf = new MergedPDF();
$pdf->setTitle($pdfTitle);
$pdf->addDocumentPath($absolutePath1);
$pdf->addDocumentPath($absolutePath2);
$pdf->addDocumentPath($absolutePath3);
$tempFileName = tempnam(sys_get_temp_dir(), 'merged');
$content = $pdf->Render();
file_put_contents($tempFileName, $content);
You can use the Grid CSS properties, is the most clear, clean and intuitive way structure your boxes.
#container{_x000D_
display: grid;_x000D_
grid-template-columns: 100px auto;_x000D_
color:white;_x000D_
}_x000D_
#fixed{_x000D_
background: red;_x000D_
grid-column: 1;_x000D_
}_x000D_
#remaining{_x000D_
background: green;_x000D_
grid-column: 2;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="fixed">Fixed</div>_x000D_
<div id="remaining">Remaining</div>_x000D_
</div>
_x000D_
Perhaps something like this :
LinkedHashMap<Integer, String> myMap;
public String getFirstKey() {
String out = null;
for (int key : myMap.keySet()) {
out = myMap.get(key);
break;
}
return out;
}
public String getLastKey() {
String out = null;
for (int key : myMap.keySet()) {
out = myMap.get(key);
}
return out;
}
I know this is a couple of years late, but I'm putting it out there for the next person on this journey.
GraphQL has been helpful and way easier compared to DjangoRESTFramework. It is also more flexible in terms of the responses you get. You get what you ask for and don't have to filter through the response to get what you want.
You can use Graphene Django on the server side and React+Apollo/Relay... You can look into it as that is not your question.
This is how I solved the problem. In Device Manager you will find the Arduino COM port.
Go to the Advanced properties of the port
Set the COM port number to COM1.
Then replug the USB.
The Objects
class has a nonNull
Predicate
that can be used with filter
.
For example:
tourists.stream().filter(Objects::nonNull).collect(Collectors.toList());
Use jQuery. Keep your checkbox elements hidden and create a list like this:
<ul id="list">
<li><a href="javascript:void(0)" id="link1">Happy face</a></li>
<li><a href="javascript:void(0)" id="link2">Sad face</a></li>
</ul>
<form action="file.php" method="post">
<!-- More code -->
<input type="radio" id="option1" name="radio1" value="happy" style="display:none"/>
<input type="radio" id="option2" name="radio1" value="sad" style="display:none"/>
<!-- More code -->
</form>
<script type="text/javascript">
$("#list li a").click(function() {
$('#list .active').removeClass("active");
var id = this.id;
var newselect = id.replace('link', 'option');
$('#'+newselect).attr('checked', true);
$(this).addClass("active").parent().addClass("active");
return false;
});
</script>
This code would add the checked attribute to your radio inputs in the background and assign class active to your list elements. Do not use inline styles of course, don't forget to include jQuery and everything should run out of the box after you customize it.
Cheers!
i just had the same problems - have been testing a lot of different stuff. but it just wouldn't work. then i checked the tutorial examples on jQuery.com again and found out:
your jQuery script needs to be after the elements you are referring to !
so your script needs to be after the html-code you want to access!
seems like jQuery can't access it otherwise.
You need to run the script like this:
groovy helloworld.groovy
Use one of these threee variants:
SOME_PATH="/mnt/someProject/some path"
SOME_PATH='/mnt/someProject/some path'
SOME_PATH=/mnt/someProject/some\ path
The "illegal instruction" message is simply telling you that your binaries contain instructions the version of the OS that you are attempting to run them under does not understand. I can't give you the precise meaning of 4
but I expect that is internal to Apple.
Otherwise take a look at these... they are a little old, but probably tell you what you need to know
How does 64 bit code work on OS-X 10.5?
what does macosx-version-min imply?
''.join(filter(str.isdigit, "+123-456-7890"))
As for Xcode 5.1, the problem was in arm64
architecture in VALID_ARCHS
. Building the release configuration for 5.0 device locally gives the following error:
Xcode cannot install or launch applications supporting the 64-bit architecture on devices running iOS versions prior to 6.0. This configuration is supported for distribution through the iOS App Store, but cannot be used during development with Xcode. To continue, edit the Run scheme action and select a build configuration that does not include the 64-bit architecture.
Removing arm64
from VALID_ARCHS
solves the issue. In my case I had to create a separate branch for testing on iOS 5 devices.
Edit the gradle wrapper settings in gradle/wrapper/gradle-wrapper.properties
and change gradle-1.6-bin.zip to gradle-2.4-bin.zip.
./gradle/wrapper/gradle-wrapper.properties :
#Wed Apr 10 15:27:10 PDT 2013
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=http\://services.gradle.org/distributions/gradle-1.8-bin.zip
It should compile without any error now.
Note: update version numbers with the most recent ones
You can use strcpy
but remember to end the array with '\0'
char array[20]; char string[100];
array[0]='1'; array[1]='7'; array[2]='8'; array[3]='.'; array[4]='9'; array[5]='\0';
strcpy(string, array);
printf("%s\n", string);
Using the map()
and reduce()
built-in functions
def file_to_list(file):
#stuff to parse file to a list
return list
files = [...list of files...]
L = map(file_to_list, files)
flat_L = reduce(lambda x,y:x+y, L)
Minimal "for looping" and elegant coding pattern :)
Python 2:
print >> sys.stderr, "fatal error"
Python 3:
print("fatal error", file=sys.stderr)
print >> sys.stderr
is gone in Python3.
http://docs.python.org/3.0/whatsnew/3.0.html says:
Old:
print >> sys.stderr, "fatal error"
New:print("fatal error", file=sys.stderr)
For many of us, it feels somewhat unnatural to relegate the destination to the end of the command. The alternative
sys.stderr.write("fatal error\n")
looks more object oriented, and elegantly goes from the generic to the specific. But note that write
is not a 1:1 replacement for print
.
Why dont you just create a tableView and make isScrollEnabled = false
ToString can take a format. try:
i.ToString("000");
Depending on your shell, you may be able to use the following syntax:
expr substr $string $position $length
So for your example:
TESTSTRINGONE="MOTEST"
echo `expr substr ${TESTSTRINGONE} 0 5`
Alternatively,
echo 'MOTEST' | cut -c1-5
or
echo 'MOTEST' | awk '{print substr($0,0,5)}'
Click "Tab Moves Focus" at the bottom right in the status bar.
I believe I had clicked on ctrl+M. When doing this, the "Tab Moves Focus" tab/button showed up at the bottom right. Clicking on that makes it go away and starts working again.
Note: The
classList
property is not supported in Internet Explorer 9. The following code will work in all browsers:
function addClass(id,classname) {
var element, name, arr;
element = document.getElementById(id);
arr = element.className.split(" ");
if (arr.indexOf(classname) == -1) { // check if class is already added
element.className += " " + classname;
}
}
addClass('div1','show')
Source: how to js add class
The transmission delay is the amount of time required for the router to push out the packet.
The propagation delay, is the time it takes a bit to propagate from one router to the next.
the transmission and propagation delay are completely different! if denote the length of the packet by L bits, and denote the transmission rate of the link from first router to second router by R bits/sec. then transmission delay will be L/R. and this is depended to transmission rate of link and the length of packet.
then if denote the distance between two routers d and denote the propagation speed s, the propagation delay will be d/s. it is a function of the Distance between the two routers, but has no dependence to the packet's length or the transmission rate of the link.
Indeed, there is no defined standard. To support that information, have a look at wikipedia, in the Query String chapter. There is the following comment:
While there is no definitive standard, most web frameworks allow multiple values to be associated with a single field.[3][4]
Furthermore, when you take a look at the RFC 3986, in section 3.4 Query, there is no definition for parameters with multiple values.
Most applications use the first option you have shown: http://server/action?id=a&id=b
. To support that information, take a look at this Stackoverflow link, and this MSDN link regarding ASP.NET applications, which use the same standard for parameters with multiple values.
However, since you are developing the APIs, I suggest you to do what is the easiest for you, since the caller of the API will not have much trouble creating the query string.
Oh, that's an interesting beast.
I've spent considerable time of getting that right, there are three main issues that differs from locale to locale: - currency symbol and direction - thousand separator - decimal point
I've written my own rather extensive implementation of this which is part of the kiwi python framework, check out the LGPL:ed source here:
http://svn.async.com.br/cgi-bin/viewvc.cgi/kiwi/trunk/kiwi/currency.py?view=markup
The code is slightly Linux/Glibc specific, but shouldn't be too difficult to adopt to windows or other unixes.
Once you have that installed you can do the following:
>>> from kiwi.datatypes import currency
>>> v = currency('10.5').format()
Which will then give you:
'$10.50'
or
'10,50 kr'
Depending on the currently selected locale.
The main point this post has over the other is that it will work with older versions of python. locale.currency was introduced in python 2.5.
EventHandler
receives EventArgs
as a parameter. To resolve your problem, you can build your own MyEventArgs
.
public enum MyEvents
{
Event1
}
public class MyEventArgs : EventArgs
{
public MyEvents MyEvent { get; set; }
}
public static event EventHandler<MyEventArgs> EventTriggered;
public static void Trigger(MyEvents ev)
{
if (EventTriggered != null)
{
EventTriggered(null, new MyEventArgs { MyEvent = ev });
}
}
Like this:
from c in db.Company
group c by c.Name into grp
where grp.Count() > 1
select grp.Key
Or, using the method syntax:
Company
.GroupBy(c => c.Name)
.Where(grp => grp.Count() > 1)
.Select(grp => grp.Key);
Ensure that the permissions on your home directory and on the home directory of the user on the host you're connecting to are set to 700 ( owning user rwx only to prevent others seeing the .ssh subdirectory ).
Then ensure that the ~/.ssh directory is also 700 ( user rwx ) and that the authorized_keys is 600 ( user rw ) .
Private keys in your ~/.ssh directory should be 600 or 400 ( user rw or user r )
You need to install ENU\x64\SQLEXPRWT_x64_ENU.exe which is Express with Tools (RTM release. SP1 release can be found here).
As the page states
Express with Tools (with LocalDB) Includes the database engine and SQL Server Management Studio Express) This package contains everything needed to install and configure SQL Server as a database server. Choose either LocalDB or Express depending on your needs above.
So install this and use the management studio included with it.
Here a performance test with multiples alternatives (some are case sensitive and others case insensitive):
public static void main(String[] args) {
// Why 4 * 4:
// The test contains 3 values (val1, val2 and val3). Checking 4 combinations will check the match on all values, and the non match;
// Try 4 times: lowercase, UPPERCASE, prefix + lowercase, prefix + UPPERCASE;
final int NUMBER_OF_TESTS = 4 * 4;
final int EXCUTIONS_BY_TEST = 1_000_000;
int numberOfMatches;
int numberOfExpectedCaseSensitiveMatches;
int numberOfExpectedCaseInsensitiveMatches;
// Start at -1, because the first execution is always slower, and should be ignored!
for (int i = -1; i < NUMBER_OF_TESTS; i++) {
int iInsensitive = i % 4;
List<String> testType = new ArrayList<>();
List<Long> timeSteps = new ArrayList<>();
String name = (i / 4 > 1 ? "dummyPrefix" : "") + ((i / 4) % 2 == 0 ? "val" : "VAL" )+iInsensitive ;
numberOfExpectedCaseSensitiveMatches = 1 <= i && i <= 3 ? EXCUTIONS_BY_TEST : 0;
numberOfExpectedCaseInsensitiveMatches = 1 <= iInsensitive && iInsensitive <= 3 && i / 4 <= 1 ? EXCUTIONS_BY_TEST : 0;
timeSteps.add(System.currentTimeMillis());
//-----------------------------------------
numberOfMatches = 0;
testType.add("List (Case sensitive)");
for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
if (Arrays.asList("val1", "val2", "val3").contains(name)) {
numberOfMatches++;
}
}
if (numberOfMatches != numberOfExpectedCaseSensitiveMatches) {
throw new RuntimeException();
}
timeSteps.add(System.currentTimeMillis());
//-----------------------------------------
numberOfMatches = 0;
testType.add("Set (Case sensitive)");
for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
if (new HashSet<>(Arrays.asList(new String[] {"val1", "val2", "val3"})).contains(name)) {
numberOfMatches++;
}
}
if (numberOfMatches != numberOfExpectedCaseSensitiveMatches) {
throw new RuntimeException();
}
timeSteps.add(System.currentTimeMillis());
//-----------------------------------------
numberOfMatches = 0;
testType.add("OR (Case sensitive)");
for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
if ("val1".equals(name) || "val2".equals(name) || "val3".equals(name)) {
numberOfMatches++;
}
}
if (numberOfMatches != numberOfExpectedCaseSensitiveMatches) {
throw new RuntimeException();
}
timeSteps.add(System.currentTimeMillis());
//-----------------------------------------
numberOfMatches = 0;
testType.add("OR (Case insensitive)");
for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
if ("val1".equalsIgnoreCase(name) || "val2".equalsIgnoreCase(name) || "val3".equalsIgnoreCase(name)) {
numberOfMatches++;
}
}
if (numberOfMatches != numberOfExpectedCaseInsensitiveMatches) {
throw new RuntimeException();
}
timeSteps.add(System.currentTimeMillis());
//-----------------------------------------
numberOfMatches = 0;
testType.add("ArraysBinarySearch(Case sensitive)");
for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
if (Arrays.binarySearch(new String[]{"val1", "val2", "val3"}, name) >= 0) {
numberOfMatches++;
}
}
if (numberOfMatches != numberOfExpectedCaseSensitiveMatches) {
throw new RuntimeException();
}
timeSteps.add(System.currentTimeMillis());
//-----------------------------------------
numberOfMatches = 0;
testType.add("Java8 Stream (Case sensitive)");
for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
if (Stream.of("val1", "val2", "val3").anyMatch(name::equals)) {
numberOfMatches++;
}
}
if (numberOfMatches != numberOfExpectedCaseSensitiveMatches) {
throw new RuntimeException();
}
timeSteps.add(System.currentTimeMillis());
//-----------------------------------------
numberOfMatches = 0;
testType.add("Java8 Stream (Case insensitive)");
for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
if (Stream.of("val1", "val2", "val3").anyMatch(name::equalsIgnoreCase)) {
numberOfMatches++;
}
}
if (numberOfMatches != numberOfExpectedCaseInsensitiveMatches) {
throw new RuntimeException();
}
timeSteps.add(System.currentTimeMillis());
//-----------------------------------------
numberOfMatches = 0;
testType.add("RegEx (Case sensitive)");
// WARNING: if values contains special characters, that should be escaped by Pattern.quote(String)
for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
if (name.matches("val1|val2|val3")) {
numberOfMatches++;
}
}
if (numberOfMatches != numberOfExpectedCaseSensitiveMatches) {
throw new RuntimeException();
}
timeSteps.add(System.currentTimeMillis());
//-----------------------------------------
numberOfMatches = 0;
testType.add("RegEx (Case insensitive)");
// WARNING: if values contains special characters, that should be escaped by Pattern.quote(String)
for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
if (name.matches("(?i)val1|val2|val3")) {
numberOfMatches++;
}
}
if (numberOfMatches != numberOfExpectedCaseInsensitiveMatches) {
throw new RuntimeException();
}
timeSteps.add(System.currentTimeMillis());
//-----------------------------------------
numberOfMatches = 0;
testType.add("StringIndexOf (Case sensitive)");
// WARNING: the string to be matched should not contains the SEPARATOR!
final String SEPARATOR = ",";
for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
// Don't forget the SEPARATOR at the begin and at the end!
if ((SEPARATOR+"val1"+SEPARATOR+"val2"+SEPARATOR+"val3"+SEPARATOR).indexOf(SEPARATOR + name + SEPARATOR)>=0) {
numberOfMatches++;
}
}
if (numberOfMatches != numberOfExpectedCaseSensitiveMatches) {
throw new RuntimeException();
}
timeSteps.add(System.currentTimeMillis());
//-----------------------------------------
StringBuffer sb = new StringBuffer("Test ").append(i)
.append("{ name : ").append(name)
.append(", numberOfExpectedCaseSensitiveMatches : ").append(numberOfExpectedCaseSensitiveMatches)
.append(", numberOfExpectedCaseInsensitiveMatches : ").append(numberOfExpectedCaseInsensitiveMatches)
.append(" }:\n");
for (int j = 0; j < testType.size(); j++) {
sb.append(String.format(" %4d ms with %s\n", timeSteps.get(j + 1)-timeSteps.get(j), testType.get(j)));
}
System.out.println(sb.toString());
}
}
Output (only the worse case, that is when have to check all elements without match none):
Test 4{ name : VAL0, numberOfExpectedCaseSensitiveMatches : 0, numberOfExpectedCaseInsensitiveMatches : 0 }:
43 ms with List (Case sensitive)
378 ms with Set (Case sensitive)
22 ms with OR (Case sensitive)
254 ms with OR (Case insensitive)
35 ms with ArraysBinarySearch(Case sensitive)
266 ms with Java8 Stream (Case sensitive)
531 ms with Java8 Stream (Case insensitive)
1009 ms with RegEx (Case sensitive)
1201 ms with RegEx (Case insensitive)
107 ms with StringIndexOf (Case sensitive)
This return only filename without any extension in 1 row:
$path = "/etc/sudoers.php";
print array_shift(explode(".", basename($path)));
// will print "sudoers"
$file = "file_name.php";
print array_shift(explode(".", basename($file)));
// will print "file_name"
It just happend to me. I solved the problem by tracing backward from the point ng-click is coded. Found out that an extra
</div>
was placed in the html to prematurely close the div block that contains the ng-click.
Removed the extra
</div>
then everything is working fine.
https://stackoverflow.com/a/46903870/4489222
To achieved this, there are simply two steps,
Step 1: Go to AndroidManifest.xml and in the add the parameter in tag - android:parentActivityName=".home.HomeActivity"
example :
<activity
android:name=".home.ActivityDetail"
android:parentActivityName=".home.HomeActivity"
android:screenOrientation="portrait" />
Step 2: in ActivityDetail add your action for previous page/activity
example :
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);}
}
The above answers really helped, but only delivered part of the solution. The major issue is that as soon as you remove the Default value attribute, the constraint on the column in database won't be removed. So previous default value will still stay in the database.
Here is a full solution to the problem, including removal of SQL constraints on attribute removal.
I am also re-using .NET Framework's native DefaultValue
attribute.
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
[DefaultValue("getutcdate()")]
public DateTime CreatedOn { get; set; }
For this to work you need to update IdentityModels.cs and Configuration.cs files
Add/update this method in your ApplicationDbContext
class
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
var convention = new AttributeToColumnAnnotationConvention<DefaultValueAttribute, string>("SqlDefaultValue", (p, attributes) => attributes.SingleOrDefault().Value.ToString());
modelBuilder.Conventions.Add(convention);
}
Update your Configuration
class constructor by registering custom Sql generator, like this:
internal sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
{
public Configuration()
{
// DefaultValue Sql Generator
SetSqlGenerator("System.Data.SqlClient", new DefaultValueSqlServerMigrationSqlGenerator());
}
}
Next, add custom Sql generator class (you can add it to the Configuration.cs file or a separate file)
internal class DefaultValueSqlServerMigrationSqlGenerator : SqlServerMigrationSqlGenerator
{
private int dropConstraintCount;
protected override void Generate(AddColumnOperation addColumnOperation)
{
SetAnnotatedColumn(addColumnOperation.Column, addColumnOperation.Table);
base.Generate(addColumnOperation);
}
protected override void Generate(AlterColumnOperation alterColumnOperation)
{
SetAnnotatedColumn(alterColumnOperation.Column, alterColumnOperation.Table);
base.Generate(alterColumnOperation);
}
protected override void Generate(CreateTableOperation createTableOperation)
{
SetAnnotatedColumns(createTableOperation.Columns, createTableOperation.Name);
base.Generate(createTableOperation);
}
protected override void Generate(AlterTableOperation alterTableOperation)
{
SetAnnotatedColumns(alterTableOperation.Columns, alterTableOperation.Name);
base.Generate(alterTableOperation);
}
private void SetAnnotatedColumn(ColumnModel column, string tableName)
{
if (column.Annotations.TryGetValue("SqlDefaultValue", out var values))
{
if (values.NewValue == null)
{
column.DefaultValueSql = null;
using var writer = Writer();
// Drop Constraint
writer.WriteLine(GetSqlDropConstraintQuery(tableName, column.Name));
Statement(writer);
}
else
{
column.DefaultValueSql = (string)values.NewValue;
}
}
}
private void SetAnnotatedColumns(IEnumerable<ColumnModel> columns, string tableName)
{
foreach (var column in columns)
{
SetAnnotatedColumn(column, tableName);
}
}
private string GetSqlDropConstraintQuery(string tableName, string columnName)
{
var tableNameSplitByDot = tableName.Split('.');
var tableSchema = tableNameSplitByDot[0];
var tablePureName = tableNameSplitByDot[1];
var str = $@"DECLARE @var{dropConstraintCount} nvarchar(128)
SELECT @var{dropConstraintCount} = name
FROM sys.default_constraints
WHERE parent_object_id = object_id(N'{tableSchema}.[{tablePureName}]')
AND col_name(parent_object_id, parent_column_id) = '{columnName}';
IF @var{dropConstraintCount} IS NOT NULL
EXECUTE('ALTER TABLE {tableSchema}.[{tablePureName}] DROP CONSTRAINT [' + @var{dropConstraintCount} + ']')";
dropConstraintCount++;
return str;
}
}
my understanding is: __proto__ and prototype are all served for the prototype chain technique . the difference is functions named with underscore(like __proto__) are not aim for developers invoked explicitly at all. in other words, they are just for some mechanisms like inherit etc. they are 'back-end'. but functions named without underscore are designed for invoked explicitly, they are 'front-end'.
You can't change CSS properties directly with jQuery. But you can achieve the same effect in at least two ways.
function updateStyleSheet(filename) {
newstylesheet = "style_" + filename + ".css";
if ($("#dynamic_css").length == 0) {
$("head").append("<link>")
css = $("head").children(":last");
css.attr({
id: "dynamic_css",
rel: "stylesheet",
type: "text/css",
href: newstylesheet
});
} else {
$("#dynamic_css").attr("href",newstylesheet);
}
}
The example above is copied from:
$("head").append('<style type="text/css"></style>');
var newStyleElement = $("head").children(':last');
newStyleElement.html('.red{background:green;}');
The example code is copied from this JSFiddle fiddle originally referenced by Alvaro in their comment.
OSX Mojave 10.14.5 (18F132) IntelliJ 2019-1 Community Edition. It worked setting idea.properties file. I also configured JAVA_HOME pointing to /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/
idea_rt idea.no.launcher=true
If you want to use outlook with Javamail API
then use
smtp-mail.outlook.com
as a host for more and complete working code Check out this answer.
A SqlDataAdapter is typically used to fill a DataSet or DataTable and so you will have access to the data after your connection has been closed (disconnected access).
The SqlDataReader is a fast forward-only and connected cursor which tends to be generally quicker than filling a DataSet/DataTable.
Furthermore, with a SqlDataReader, you deal with your data one record at a time, and don't hold any data in memory. Obviously with a DataTable or DataSet, you do have a memory allocation overhead.
If you don't need to keep your data in memory, so for rendering stuff only, go for the SqlDataReader. If you want to deal with your data in a disconnected fashion choose the DataAdapter to fill either a DataSet or DataTable.
If you really want to disable a button, I found that you also need to call the .unbind() method on it. Otherwise the button may still be active, and a double-click could lead to multiple form submissions. The following code works for me:
button = $(this).parent().find("button:contains('OK')");
button.unbind();
button.addClass('ui-state-disabled');
I use Eclipse Java EE edition
Create a "Dynamic Web Project"
Install a local server in the server view, for the version of Tomcat I'm using. Then debug, and run on that server for testing.
When I deploy I export the project to a war file.
The problem is on this line:
oShell.run "cmd.exe /C copy "S:Claims\Sound.wav" "C:\WINDOWS\Media\Sound.wav"
Your first quote next to "S:Claims" ends the string; you need to escape the quotes around your files with a second quote, like this:
oShell.run "cmd.exe /C copy ""S:\Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "
You also have a typo in S:Claims\Sound.wav
, should be S:\Claims\Sound.wav
.
I also assume the apostrophe before Dim oShell
and after Set oShell = Nothing
are typos as well.
Try:
$('body').on({
hover: function() {
console.log("yeahhhh!!! but this doesn't work for me :(");
},
click: function() {
console.log("yeahhhh!!! but this doesn't work for me :(");
}
},'#my-button');
When using .on() and binding to a dynamic element, you need to refer to an element that already exists on the page (like body in the example). If you can use a more specific element that would improve performance.
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next.
I've started my own project, called syncProj. Documentation / download links from here:
https://docs.google.com/document/d/1C1YrbFUVpTBXajbtrC62aXru2om6dy5rClyknBj5zHU/edit# https://sourceforge.net/projects/syncproj/
If you're planning to use Visual studio for development, and currently only C++ is supported.
Main advantage compared to other make systems is that you can actually debug your script, as it's C# based.
If you're not familiar with syncProj, you can just convert your solution / project to .cs script, and continue further development from that point on.
In cmake you will need to write everything from scratch.
IMO, it's better to use the install
command in such situations. I was trying to make systemd-journald
persistent across reboots.
install -d -g systemd-journal -m 2755 -v /var/log/journal
Regarding git fetch -p
, its behavior changed in Git 1.9, and only Git 2.9.x/2.10 reflects that.
See commit 9e70233 (13 Jun 2016) by Jeff King (peff
).
(Merged by Junio C Hamano -- gitster
-- in commit 1c22105, 06 Jul 2016)
fetch
: document that pruning happens before fetchingThis was changed in 10a6cc8 (
fetch --prune
: Run prune before fetching, 2014-01-02), but it seems that nobody in that discussion realized we were advertising the "after" explicitly.
So the documentation now states:
Before fetching, remove any remote-tracking references that no longer exist on the remote
That is because:
When we have a remote-tracking branch named "
frotz/nitfol
" from a previous fetch, and the upstream now has a branch named "frotz
", fetch would fail to remove "frotz/nitfol
" with a "git fetch --prune
" from the upstream. git would inform the user to use "git remote prune
" to fix the problem.Change the way "
fetch --prune
" works by moving the pruning operation before the fetching operation. This way, instead of warning the user of a conflict, it automatically fixes it.
You can't use variable names to bind columns or other system objects, you need dynamic sql
DECLARE @value varchar(10)
SET @value = 'intStep'
DECLARE @sqlText nvarchar(1000);
SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
To download the SDK over command line, the link has changed slightly than previously mentioned:
wget --quiet --output-document=/tmp/sdk-tools-linux.zip https://dl.google.com/android/repository/commandlinetools-linux-${ANDROID_SDK_TOOLS}.zip
Latest version listed on the downloads page.
Very easy:
you have only to place the iframe between
<center> ... </center>
with some
<br>
. That's all.
Perfect Tree:
x
/ \
/ \
x x
/ \ / \
x x x x
/ \ / \ / \ / \
x x x x x x x x
Complete Tree:
x
/ \
/ \
x x
/ \ / \
x x x x
/ \ /
x x x
Strict/Full Tree:
x
/ \
/ \
x x
/ \
x x
/ \
x x
In the terminal: For Xcode 9.x and above
$ open /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app
For Xcode-beta 9.x and above
$ open /Applications/Xcode-beta.app/Contents/Developer/Applications/Simulator.app
You can use the Firefox add-on called SQLite Manager to view the database's structure clearly.
There are three different approaches to consider, as described in the reference
Most likely the problem lies outside the code you are showing us here. You are trying to update an object that is not associated with the current session. If it is not the Invoice, then maybe it is an InvoiceItem that has already been persisted, obtained from the db, kept alive in some sort of session and then you try to persist it on a new session. This is not possible. As a general rule, never keep your persisted objects alive across sessions.
The solution will ie in obtaining the whole object graph from the same session you are trying to persist it with. In a web environment this would mean:
If you keep having issues post some of the code that is calling your service.
Are you trying to submit a form?
Listen to the submit
event instead.
This will handle click
and enter
.
If you must use enter key...
document.querySelector('#txtSearch').addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
// code for enter
}
});
Apache Tomcat is used to deploy your Java Servlets and JSPs. So in your Java project you can build your WAR (short for Web ARchive) file, and just drop it in the deploy directory in Tomcat.
So basically Apache is an HTTP Server, serving HTTP. Tomcat is a Servlet and JSP Server serving Java technologies.
Tomcat includes Catalina, which is a servlet container. A servlet, at the end, is a Java class. JSP files (which are similar to PHP, and older ASP files) are generated into Java code (HttpServlet), which is then compiled to .class files by the server and executed by the Java virtual machine.
First of all, read the warning! It says do not run composer as root! Secondly, you're probably using Xammp on your local which has the required php libraries as default.
But in your server you're missing ext-dom
. php-xml
has all the related packages you need. So, you can simply install it by running:
sudo apt-get update
sudo apt install php-xml
Most likely you are missing mbstring
too. If you get the error, install this package as well with:
sudo apt-get install php-mbstring
Then run:
composer update
composer require cviebrock/eloquent-sluggable
After reading your clarification, @Ates Goral's answer provides how to perform the same operation you're doing in C# in JavaScript.
@Gumbo's answer provides the best way to check for null; however, it's important to note the difference in ==
versus ===
in JavaScript especially when it comes to issues of checking for undefined
and/or null
.
There's a really good article about the difference in two terms here. Basically, understand that if you use ==
instead of ===
, JavaScript will try to coalesce the values you're comparing and return what the result of the comparison after this coalescence.
First dump the keystore from JKS to PKCS12
1. keytool -importkeystore -srckeystore ~/.android/debug.keystore -destkeystore intermediate.p12 -srcstoretype JKS -deststoretype PKCS12
Dump the new pkcs12 file into pem
You should have both the cert and private key in pem format. Split them up. Put the part between “BEGIN CERTIFICATE” and “END CERTIFICATE” into cert.x509.pem Put the part between “BEGIN RSA PRIVATE KEY” and “END RSA PRIVATE KEY” into private.rsa.pem Convert the private key into pk8 format as expected by signapk
3. openssl pkcs8 -topk8 -outform DER -in private.rsa.pem -inform PEM -out private.pk8 -nocrypt
I am doing similar thing to compile all the c files in a directory.
for iterating files in different directory try this.
set codedirectory=C:\Users\code
for /r %codedirectory% %%i in (*.c) do
( some GCC commands )
update_attribute
simply updates only one attribute of a model, but we can pass multiple attributes in update_attributes
method.
Example:
user = User.last
#update_attribute
user.update_attribute(:status, "active")
It pass the validation
#update_attributes
user.update_attributes(first_name: 'update name', status: "active")
it doesn't update if validation fails.
The finite repetition syntax uses {m,n}
in place of star/plus/question mark.
From java.util.regex.Pattern
:
X{n} X, exactly n times
X{n,} X, at least n times
X{n,m} X, at least n but not more than m times
All repetition metacharacter have the same precedence, so just like you may need grouping for *
, +
, and ?
, you may also for {n,m}
.
ha*
matches e.g. "haaaaaaaa"
ha{3}
matches only "haaa"
(ha)*
matches e.g. "hahahahaha"
(ha){3}
matches only "hahaha"
Also, just like *
, +
, and ?
, you can add the ?
and +
reluctant and possessive repetition modifiers respectively.
System.out.println(
"xxxxx".replaceAll("x{2,3}", "[x]")
); "[x][x]"
System.out.println(
"xxxxx".replaceAll("x{2,3}?", "[x]")
); "[x][x]x"
Essentially anywhere a *
is a repetition metacharacter for "zero-or-more", you can use {...}
repetition construct. Note that it's not true the other way around: you can use finite repetition in a lookbehind, but you can't use *
because Java doesn't officially support infinite-length lookbehind.
.*
and .*?
for regexregex{n,}?
== regex{n}
?a{1}b{0,1}
instead of ab?
false != 'false'
For good measures, put the result of validate into a variable to avoid double validation and use that in the IF statement. Like this:
var result = ValidateForm();
if(result == false) {
...
}
Using merge
is different from lookup in Excel as it has potential to duplicate (multiply) your data if primary key constraint is not enforced in lookup table or reduce the number of records if you are not using all.x = T
.
To make sure you don't get into trouble with that and lookup safely, I suggest two strategies.
First one is to make a check on a number of duplicated rows in lookup key:
safeLookup <- function(data, lookup, by, select = setdiff(colnames(lookup), by)) {
# Merges data to lookup making sure that the number of rows does not change.
stopifnot(sum(duplicated(lookup[, by])) == 0)
res <- merge(data, lookup[, c(by, select)], by = by, all.x = T)
return (res)
}
This will force you to de-dupe lookup dataset before using it:
baseSafe <- safeLookup(largetable, house.ids, by = "HouseType")
# Error: sum(duplicated(lookup[, by])) == 0 is not TRUE
baseSafe<- safeLookup(largetable, unique(house.ids), by = "HouseType")
head(baseSafe)
# HouseType HouseTypeNo
# 1 Apartment 4
# 2 Apartment 4
# ...
Second option is to reproduce Excel behaviour by taking the first matching value from the lookup dataset:
firstLookup <- function(data, lookup, by, select = setdiff(colnames(lookup), by)) {
# Merges data to lookup using first row per unique combination in by.
unique.lookup <- lookup[!duplicated(lookup[, by]), ]
res <- merge(data, unique.lookup[, c(by, select)], by = by, all.x = T)
return (res)
}
baseFirst <- firstLookup(largetable, house.ids, by = "HouseType")
These functions are slightly different from lookup
as they add multiple columns.
I use AngularJS v1.3.4
HTML:
<button ng-click="downloadPdf()" class="btn btn-primary">download PDF</button>
JS controller:
'use strict';
angular.module('xxxxxxxxApp')
.controller('MathController', function ($scope, MathServicePDF) {
$scope.downloadPdf = function () {
var fileName = "test.pdf";
var a = document.createElement("a");
document.body.appendChild(a);
MathServicePDF.downloadPdf().then(function (result) {
var file = new Blob([result.data], {type: 'application/pdf'});
var fileURL = window.URL.createObjectURL(file);
a.href = fileURL;
a.download = fileName;
a.click();
});
};
});
JS services:
angular.module('xxxxxxxxApp')
.factory('MathServicePDF', function ($http) {
return {
downloadPdf: function () {
return $http.get('api/downloadPDF', { responseType: 'arraybuffer' }).then(function (response) {
return response;
});
}
};
});
Java REST Web Services - Spring MVC:
@RequestMapping(value = "/downloadPDF", method = RequestMethod.GET, produces = "application/pdf")
public ResponseEntity<byte[]> getPDF() {
FileInputStream fileStream;
try {
fileStream = new FileInputStream(new File("C:\\xxxxx\\xxxxxx\\test.pdf"));
byte[] contents = IOUtils.toByteArray(fileStream);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
String filename = "test.pdf";
headers.setContentDispositionFormData(filename, filename);
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
return response;
} catch (FileNotFoundException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
}
return null;
}
You cannot use Set Transaction Isolation Level Read Uncommitted in a View (you can only have one script in there in fact), so you would have to use (nolock) if dirty rows should be included.
I used Darin Dimitrov's answer to create a generic extension to get member attributes for any member in a class (instead of attributes for a class). I'm posting it here because others may find it useful:
public static class AttributeExtensions
{
/// <summary>
/// Returns the value of a member attribute for any member in a class.
/// (a member is a Field, Property, Method, etc...)
/// <remarks>
/// If there is more than one member of the same name in the class, it will return the first one (this applies to overloaded methods)
/// </remarks>
/// <example>
/// Read System.ComponentModel Description Attribute from method 'MyMethodName' in class 'MyClass':
/// var Attribute = typeof(MyClass).GetAttribute("MyMethodName", (DescriptionAttribute d) => d.Description);
/// </example>
/// <param name="type">The class that contains the member as a type</param>
/// <param name="MemberName">Name of the member in the class</param>
/// <param name="valueSelector">Attribute type and property to get (will return first instance if there are multiple attributes of the same type)</param>
/// <param name="inherit">true to search this member's inheritance chain to find the attributes; otherwise, false. This parameter is ignored for properties and events</param>
/// </summary>
public static TValue GetAttribute<TAttribute, TValue>(this Type type, string MemberName, Func<TAttribute, TValue> valueSelector, bool inherit = false) where TAttribute : Attribute
{
var att = type.GetMember(MemberName).FirstOrDefault().GetCustomAttributes(typeof(TAttribute), inherit).FirstOrDefault() as TAttribute;
if (att != null)
{
return valueSelector(att);
}
return default(TValue);
}
}
Usage example:
//Read System.ComponentModel Description Attribute from method 'MyMethodName' in class 'MyClass'
var Attribute = typeof(MyClass).GetAttribute("MyMethodName", (DescriptionAttribute d) => d.Description);
What you're looking for is n choose k. Basically:
For every pair of 100 items, you'd have 4,950 combinations - provided order doesn't matter (AB and BA are considered a single combination) and you don't want to repeat (AA is not a valid pair).