I tried with and it works
use mysql; # use mysql table
update user set authentication_string="" where User='root';
flush privileges;
quit;
Vavr (formerly called Javaslang) (http://www.vavr.io) provides tuples (til size of 8) as well. Here is the javadoc: https://static.javadoc.io/io.vavr/vavr/0.9.0/io/vavr/Tuple.html.
This is a simple example:
Tuple2<Integer, String> entry = Tuple.of(1, "A");
Integer key = entry._1;
String value = entry._2;
Why JDK itself did not come with a simple kind of tuples til now is a mystery to me. Writing wrapper classes seems to be an every day business.
As a workaround, you could consider setting environment variables in the outer layer, like this.
main.py:
import os
os.environ['MYVAL'] = str(myintvariable)
mymodule.py:
import os
myval = None
if 'MYVAL' in os.environ:
myval = os.environ['MYVAL']
As an extra precaution, handle the case when MYVAL is not defined inside the module.
This version is using recursion
import pprint
from collections import deque
pp = pprint.PrettyPrinter(indent=4)
inp = raw_input("Enter a sentence to show as trie\n")
words = inp.split(" ")
trie = {}
def trie_recursion(trie_ds, word):
try:
letter = word.popleft()
out = trie_recursion(trie_ds.get(letter, {}), word)
except IndexError:
# End of the word
return {}
# Dont update if letter already present
if not trie_ds.has_key(letter):
trie_ds[letter] = out
return trie_ds
for word in words:
# Go through each word
trie = trie_recursion(trie, deque(word))
pprint.pprint(trie)
Output:
Coool <algos> python trie.py
Enter a sentence to show as trie
foo bar baz fun
{
'b': {
'a': {
'r': {},
'z': {}
}
},
'f': {
'o': {
'o': {}
},
'u': {
'n': {}
}
}
}
InverseProperty
in EF Core makes the solution easy and clean.
So the desired solution would be:
public class Team
{
[Key]
public int TeamId { get; set;}
public string Name { get; set; }
[InverseProperty(nameof(Match.HomeTeam))]
public ICollection<Match> HomeMatches{ get; set; }
[InverseProperty(nameof(Match.GuestTeam))]
public ICollection<Match> AwayMatches{ get; set; }
}
public class Match
{
[Key]
public int MatchId { get; set; }
[ForeignKey(nameof(HomeTeam)), Column(Order = 0)]
public int HomeTeamId { get; set; }
[ForeignKey(nameof(GuestTeam)), Column(Order = 1)]
public int GuestTeamId { get; set; }
public float HomePoints { get; set; }
public float GuestPoints { get; set; }
public DateTime Date { get; set; }
public Team HomeTeam { get; set; }
public Team GuestTeam { get; set; }
}
Another option would be to enclose the update statement in an IF statement and call TRIGGER_NESTLEVEL() to restrict the update being run a second time.
CREATE TRIGGER Table_A_Update ON Table_A AFTER UPDATE
AS
IF ((SELECT TRIGGER_NESTLEVEL()) < 2)
BEGIN
UPDATE a
SET Date_Column = GETDATE()
FROM Table_A a
JOIN inserted i ON a.ID = i.ID
END
When the trigger initially runs the TRIGGER_NESTLEVEL is set to 1 so the update statement will be executed. That update statement will in turn fire that same trigger except this time the TRIGGER_NESTLEVEL is set to 2 and the update statement will not be executed.
You could also check the TRIGGER_NESTLEVEL first and if its greater than 1 then call RETURN to exit out of the trigger.
IF ((SELECT TRIGGER_NESTLEVEL()) > 1) RETURN;
Rotation Object programmatically.
// clockwise rotation :
public void rotate_Clockwise(View view) {
ObjectAnimator rotate = ObjectAnimator.ofFloat(view, "rotation", 180f, 0f);
// rotate.setRepeatCount(10);
rotate.setDuration(500);
rotate.start();
}
// AntiClockwise rotation :
public void rotate_AntiClockwise(View view) {
ObjectAnimator rotate = ObjectAnimator.ofFloat(view, "rotation", 0f, 180f);
// rotate.setRepeatCount(10);
rotate.setDuration(500);
rotate.start();
}
view is object of your ImageView or other widgets.
rotate.setRepeatCount(10); use to repeat your rotation.
500 is your animation time duration.
Mark circular dependencies as "Warning" in Eclipse tool to avoid "A CYCLE WAS DETECTED IN THE BUILD PATH" error.
In Eclipse go to:
Windows -> Preferences -> Java-> Compiler -> Building -> Circular Dependencies
Oh boy! This looks bad! The only option that I can think of is that the working copy is corrupt.
Try deleting the working copy, performing a fresh checkout and performing the merge again.
If that doesn't work, then log a bug.
Suppose you are running a test python file named request.py
In request.py, you write
import request
so this also most likely a circular import.
Solution:
Just change your test file to another name such as aaa.py
, other than request.py
.
Do not use names that are already used by other libs.
I had implemented this problem in sml ( imperative programming) . Here is the outline . Find all the nodes that either have an indegree or outdegree of 0 . Such nodes cannot be part of a cycle ( so remove them ) . Next remove all the incoming or outgoing edges from such nodes. Recursively apply this process to the resulting graph. If at the end you are not left with any node or edge , the graph does not have any cycles , else it has.
In the version 3.2.4 of the XAMPP Control Panel, there is button that can open a command line prompt (red rectangle in the next figure)
After pressing the button, you will see the command prompt window.
From this window you can navigate through the different folders and start the different services available.
You can also declare class variables as None which will prevent propagation. This is useful when you need a well defined class and want to prevent AttributeErrors. For example:
>>> class TestClass(object):
... t = None
...
>>> test = TestClass()
>>> test.t
>>> test2 = TestClass()
>>> test.t = 'test'
>>> test.t
'test'
>>> test2.t
>>>
Also if you need defaults:
>>> class TestClassDefaults(object):
... t = None
... def __init__(self, t=None):
... self.t = t
...
>>> test = TestClassDefaults()
>>> test.t
>>> test2 = TestClassDefaults([])
>>> test2.t
[]
>>> test.t
>>>
Of course still follow the info in the other answers about using mutable vs immutable types as the default in __init__
.
Your session status are set once you start a session, and by default, take the current GLOBAL value.
If you disconnected after you did SET @@GLOBAL.wait_timeout=300
, then subsequently reconnected, you'd see
SHOW SESSION VARIABLES LIKE "%wait%";
Result: 300
Similarly, at any time, if you did
mysql> SET session wait_timeout=300;
You'd get
mysql> SHOW SESSION VARIABLES LIKE 'wait_timeout';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| wait_timeout | 300 |
+---------------+-------+
The SweetAlert repo seems to be unmaintained. There's a bunch of Pull Requests without any replies, the last merged pull request was on Nov 9, 2014.
I created SweetAlert2 with HTML support in modal and some other options for customization modal window - width, padding, Esc button behavior, etc.
Swal.fire({
title: "<i>Title</i>",
html: "Testno sporocilo za objekt: <b>test</b>",
confirmButtonText: "V <u>redu</u>",
});
_x000D_
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>
_x000D_
Does m
really need to be a data.frame()
or will a matrix()
suffice?
m <- matrix(0, ncol = 30, nrow = 2)
You can wrap a data.frame()
around that if you need to:
m <- data.frame(m)
or all in one line: m <- data.frame(matrix(0, ncol = 30, nrow = 2))
input.name()
needs to be inside a function; classes contain declarations, not random code.
You need to alter your table. Increase the column width using a DDL statement.
please see here
http://dba-oracle.com/t_alter_table_modify_column_syntax_example.htm
You can try this simple way for combining columns:
select some_other_column,first_name || ' ' || last_name AS First_name from customer;
You need to put an actual tab character after the -t\ and to do that in a shell you hit ctrl-v and then the tab character. Most shells I've used support this mode of literal tab entry.
Beware, though, because copying and pasting from another place generally does not preserve tabs.
Easyest way to do that is simply
IEnumerable<T> items = new T[]{new T("msg")};
List<string> itemsList = new List<string>();
itemsList.AddRange(items.Select(y => y.ToString()));
itemsList.Add("msg2");
Then you can return list as IEnumerable also because it implements IEnumerable interface
Think of the null as "unknown" in that case (or "does not exist"). In either of those cases, you can't say that they are equal, because you don't know the value of either of them. So, null=null evaluates to not true (false or null, depending on your system), because you don't know the values to say that they ARE equal. This behavior is defined in the ANSI SQL-92 standard.
EDIT: This depends on your ansi_nulls setting. if you have ANSI_NULLS off, this WILL evaluate to true. Run the following code for an example...
set ansi_nulls off
if null = null
print 'true'
else
print 'false'
set ansi_nulls ON
if null = null
print 'true'
else
print 'false'
If you're working within a single method (or even in a single class or assembly in some cases) and no one outside is going to see what you're doing, use the fullness of a List. But if you're interacting with outside code, like when you're returning a list from a method, then you only want to declare the interface without necessarily tying yourself to a specific implementation, especially if you have no control over who compiles against your code afterward. If you started with a concrete type and you decided to change to another one, even if it uses the same interface, you're going to break someone else's code unless you started off with an interface or abstract base type.
With v25.3.x of the Android Emulator & x86 Google API Emulator system images API Level 19 (Android 4.4 - Kitkat) and higher, you can simply copy and paste from your desktop with your mouse or keyboard.
This feature was announced with Android Studio 2.3
http://encosia.com/using-cors-to-access-asp-net-services-across-domains/
refer the above link for more details on Cross domain resource sharing.
you can try using JSONP . If the API is not supporting jsonp, you have to create a service which acts as a middleman between the API and your client. In my case, i have created a asmx service.
sample below:
ajax call:
$(document).ready(function () {
$.ajax({
crossDomain: true,
type:"GET",
contentType: "application/json; charset=utf-8",
async:false,
url: "<your middle man service url here>/GetQuote?callback=?",
data: { symbol: 'ctsh' },
dataType: "jsonp",
jsonpCallback: 'fnsuccesscallback'
});
});
service (asmx) which will return jsonp:
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void GetQuote(String symbol,string callback)
{
WebProxy myProxy = new WebProxy("<proxy url here>", true);
myProxy.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
StockQuoteProxy.StockQuote SQ = new StockQuoteProxy.StockQuote();
SQ.Proxy = myProxy;
String result = SQ.GetQuote(symbol);
StringBuilder sb = new StringBuilder();
JavaScriptSerializer js = new JavaScriptSerializer();
sb.Append(callback + "(");
sb.Append(js.Serialize(result));
sb.Append(");");
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.Write(sb.ToString());
Context.Response.End();
}
You can delete the service:
sc delete ServiceName
Then recreate the service.
Alt+# comments out the current line. It will be available in history if needed.
To supplement Thomas's answer, the Application
class also has the DispatcherUnhandledException
event that you can handle.
item = objects.Find(obj => obj.property==myValue);
Refer to the below link,
https://angular.io/api/common/DatePipe
**Code Sample**
@Component({
selector: 'date-pipe',
template: `<div>
<p>Today is {{today | date}}</p>
<p>Or if you prefer, {{today | date:'fullDate'}}</p>
<p>The time is {{today | date:'h:mm a z'}}</p>
</div>`
})
// Get the current date and time as a date-time value.
export class DatePipeComponent {
today: number = Date.now();
}
{{today | date:'MM/dd/yyyy'}} output: 17/09/2019
or
{{today | date:'shortDate'}} output: 17/9/19
The Abstact data type Wikipedia article has a lot to say.
In computer science, an abstract data type (ADT) is a mathematical model for a certain class of data structures that have similar behavior; or for certain data types of one or more programming languages that have similar semantics. An abstract data type is defined indirectly, only by the operations that may be performed on it and by mathematical constraints on the effects (and possibly cost) of those operations.
In slightly more concrete terms, you can take Java's List
interface as an example. The interface doesn't explicitly define any behavior at all because there is no concrete List
class. The interface only defines a set of methods that other classes (e.g. ArrayList
and LinkedList
) must implement in order to be considered a List
.
A collection is another abstract data type. In the case of Java's Collection
interface, it's even more abstract than List
, since
The
List
interface places additional stipulations, beyond those specified in theCollection
interface, on the contracts of theiterator
,add
,remove
,equals
, andhashCode
methods.
A bag is also known as a multiset.
In mathematics, the notion of multiset (or bag) is a generalization of the notion of set in which members are allowed to appear more than once. For example, there is a unique set that contains the elements a and b and no others, but there are many multisets with this property, such as the multiset that contains two copies of a and one of b or the multiset that contains three copies of both a and b.
In Java, a Bag would be a collection that implements a very simple interface. You only need to be able to add items to a bag, check its size, and iterate over the items it contains. See Bag.java for an example implementation (from Sedgewick & Wayne's Algorithms 4th edition).
With quotes around the date:
mysql> CALL insertEvent('2012.01.01 12:12:12');
A simple increment should do the trick.
UPDATE mytable
SET logins = logins + 1
WHERE id = 12
If you would like to update a previously existing row, or insert it if it doesn't already exist, you can use the REPLACE
syntax or the INSERT...ON DUPLICATE KEY UPDATE
option (As Rob Van Dam demonstrated in his answer).
Or perhaps you're looking for something like INSERT...MAX(logins)+1
? Essentially you'd run a query much like the following - perhaps a bit more complex depending on your specific needs:
INSERT into mytable (logins)
SELECT max(logins) + 1
FROM mytable
Use a lambda function.
Let's say you have an array:
nums = [0,1,5]
Check whether 5 is in nums
in Python 3.X:
(len(list(filter (lambda x : x == 5, nums))) > 0)
Check whether 5 is in nums
in Python 2.7:
(len(filter (lambda x : x == 5, nums)) > 0)
This solution is more robust. You can now check whether any number satisfying a certain condition is in your array nums
.
For example, check whether any number that is greater than or equal to 5 exists in nums
:
(len(filter (lambda x : x >= 5, nums)) > 0)
What worked for me on Windows was (I had cloned code from a repo 1st):
eval $(ssh-agent)
ssh-add
git pull
at which time it asked me one last time for my passphrase
Credits: the solution was taken from https://unix.stackexchange.com/questions/12195/how-to-avoid-being-asked-passphrase-each-time-i-push-to-bitbucket
I think this is important to consider for cross-platform execution, i.e. as a CYA. :)
On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.
This is directly quoted from Python Software Foundation 2.7.x.
There are two ways to do this. The System.Diagnostics.StackTrace()
will give you a stack trace for the current thread. If you have a reference to a Thread
instance, you can get the stack trace for that via the overloaded version of StackTrace()
.
You may also want to check out Stack Overflow question How to get non-current thread's stacktrace?.
Following link Provides JSON document describing metadata about the Keycloak
/auth/realms/{realm-name}/.well-known/openid-configuration
Following information reported with Keycloak 6.0.1 for master
realm
{
"issuer":"http://localhost:8080/auth/realms/master",
"authorization_endpoint":"http://localhost:8080/auth/realms/master/protocol/openid-connect/auth",
"token_endpoint":"http://localhost:8080/auth/realms/master/protocol/openid-connect/token",
"token_introspection_endpoint":"http://localhost:8080/auth/realms/master/protocol/openid-connect/token/introspect",
"userinfo_endpoint":"http://localhost:8080/auth/realms/master/protocol/openid-connect/userinfo",
"end_session_endpoint":"http://localhost:8080/auth/realms/master/protocol/openid-connect/logout",
"jwks_uri":"http://localhost:8080/auth/realms/master/protocol/openid-connect/certs",
"check_session_iframe":"http://localhost:8080/auth/realms/master/protocol/openid-connect/login-status-iframe.html",
"grant_types_supported":[
"authorization_code",
"implicit",
"refresh_token",
"password",
"client_credentials"
],
"response_types_supported":[
"code",
"none",
"id_token",
"token",
"id_token token",
"code id_token",
"code token",
"code id_token token"
],
"subject_types_supported":[
"public",
"pairwise"
],
"id_token_signing_alg_values_supported":[
"PS384",
"ES384",
"RS384",
"HS256",
"HS512",
"ES256",
"RS256",
"HS384",
"ES512",
"PS256",
"PS512",
"RS512"
],
"userinfo_signing_alg_values_supported":[
"PS384",
"ES384",
"RS384",
"HS256",
"HS512",
"ES256",
"RS256",
"HS384",
"ES512",
"PS256",
"PS512",
"RS512",
"none"
],
"request_object_signing_alg_values_supported":[
"PS384",
"ES384",
"RS384",
"ES256",
"RS256",
"ES512",
"PS256",
"PS512",
"RS512",
"none"
],
"response_modes_supported":[
"query",
"fragment",
"form_post"
],
"registration_endpoint":"http://localhost:8080/auth/realms/master/clients-registrations/openid-connect",
"token_endpoint_auth_methods_supported":[
"private_key_jwt",
"client_secret_basic",
"client_secret_post",
"client_secret_jwt"
],
"token_endpoint_auth_signing_alg_values_supported":[
"RS256"
],
"claims_supported":[
"aud",
"sub",
"iss",
"auth_time",
"name",
"given_name",
"family_name",
"preferred_username",
"email"
],
"claim_types_supported":[
"normal"
],
"claims_parameter_supported":false,
"scopes_supported":[
"openid",
"address",
"email",
"microprofile-jwt",
"offline_access",
"phone",
"profile",
"roles",
"web-origins"
],
"request_parameter_supported":true,
"request_uri_parameter_supported":true,
"code_challenge_methods_supported":[
"plain",
"S256"
],
"tls_client_certificate_bound_access_tokens":true,
"introspection_endpoint":"http://localhost:8080/auth/realms/master/protocol/openid-connect/token/introspect"
}
I just wrote this short script; seems to work.
/**
* Find all the elements with a tagName that matches.
* @param {RegExp} regEx regular expression to match against tagName
* @returns {Array} elements in the DOM that match
*/
function getAllTagMatches(regEx) {
return Array.prototype.slice.call(document.querySelectorAll('*')).filter(function (el) {
return el.tagName.match(regEx);
});
}
getAllTagMatches(/^di/i); // Returns an array of all elements that begin with "di", eg "div"
Ensure position
is on your element and set the z-index
to a value higher than the elements you want to cover.
element {
position: fixed;
z-index: 999;
}
div {
position: relative;
z-index: 99;
}
It will probably require some more work than that but it's a start since you didn't post any code.
As you can probably see from the multitude of different (and often mutually exclusive) answers, it depends on who you ask. In some arenas, the terms are synonymous. Or they might each refer to two similar concepts:
In either case, the intention is to allow the program to not be blocked waiting for a slow process to complete - how the program is expected to respond is the only real difference. Which term refers to which also changes from programmer to programmer, language to language, or platform to platform. Or the terms may refer to completely different concepts (such as the use of synchronous/asynchronous in relation to thread programming).
Sorry, but I don't believe there is a single right answer that is globally true.
Another possibility would be the use of REGEXP_SUBSTR.
Instead of modding the auto-generated code or wrapping every call in duplicate code, you can inject your custom HTTP headers by adding a custom message inspector, it's easier than it sounds:
public class CustomMessageInspector : IClientMessageInspector
{
readonly string _authToken;
public CustomMessageInspector(string authToken)
{
_authToken = authToken;
}
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
var reqMsgProperty = new HttpRequestMessageProperty();
reqMsgProperty.Headers.Add("Auth-Token", _authToken);
request.Properties[HttpRequestMessageProperty.Name] = reqMsgProperty;
return null;
}
public void AfterReceiveReply(ref Message reply, object correlationState)
{ }
}
public class CustomAuthenticationBehaviour : IEndpointBehavior
{
readonly string _authToken;
public CustomAuthenticationBehaviour (string authToken)
{
_authToken = authToken;
}
public void Validate(ServiceEndpoint endpoint)
{ }
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{ }
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{ }
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.ClientMessageInspectors.Add(new CustomMessageInspector(_authToken));
}
}
And when instantiating your client class you can simply add it as a behavior:
this.Endpoint.EndpointBehaviors.Add(new CustomAuthenticationBehaviour("Auth Token"));
This will make every outgoing service call to have your custom HTTP header.
Versioning of assemblies in .NET can be a confusing prospect given that there are currently at least three ways to specify a version for your assembly.
Here are the three main version-related assembly attributes:
// Assembly mscorlib, Version 2.0.0.0
[assembly: AssemblyFileVersion("2.0.50727.3521")]
[assembly: AssemblyInformationalVersion("2.0.50727.3521")]
[assembly: AssemblyVersion("2.0.0.0")]
By convention, the four parts of the version are referred to as the Major Version, Minor Version, Build, and Revision.
AssemblyFileVersion
is intended to uniquely identify a build of the individual assemblyTypically you’ll manually set the Major and Minor AssemblyFileVersion to reflect the version of the assembly, then increment the Build and/or Revision every time your build system compiles the assembly. The AssemblyFileVersion should allow you to uniquely identify a build of the assembly, so that you can use it as a starting point for debugging any problems.
On my current project we have the build server encode the changelist number from our source control repository into the Build and Revision parts of the AssemblyFileVersion. This allows us to map directly from an assembly to its source code, for any assembly generated by the build server (without having to use labels or branches in source control, or manually keeping any records of released versions).
This version number is stored in the Win32 version resource and can be seen when viewing the Windows Explorer property pages for the assembly.
The CLR does not care about nor examine the AssemblyFileVersion.
AssemblyInformationalVersion
is intended to represent the version of your entire productThe AssemblyInformationalVersion is intended to allow coherent versioning of the entire product, which may consist of many assemblies that are independently versioned, perhaps with differing versioning policies, and potentially developed by disparate teams.
“For example, version 2.0 of a product might contain several assemblies; one of these assemblies is marked as version 1.0 since it’s a new assembly that didn’t ship in version 1.0 of the same product. Typically, you set the major and minor parts of this version number to represent the public version of your product. Then you increment the build and revision parts each time you package a complete product with all its assemblies.” — Jeffrey Richter, [CLR via C# (Second Edition)] p. 57
The CLR does not care about nor examine the AssemblyInformationalVersion.
AssemblyVersion
is the only version the CLR cares about (but it cares about the entire AssemblyVersion
)The AssemblyVersion is used by the CLR to bind to strongly named assemblies. It is stored in the AssemblyDef manifest metadata table of the built assembly, and in the AssemblyRef table of any assembly that references it.
This is very important, because it means that when you reference a strongly named assembly, you are tightly bound to a specific AssemblyVersion of that assembly. The entire AssemblyVersion must be an exact match for the binding to succeed. For example, if you reference version 1.0.0.0 of a strongly named assembly at build-time, but only version 1.0.0.1 of that assembly is available at runtime, binding will fail! (You will then have to work around this using Assembly Binding Redirection.)
AssemblyVersion
has to match. (Yes, it does.)There is a little confusion around whether the entire AssemblyVersion has to be an exact match in order for an assembly to be loaded. Some people are under the false belief that only the Major and Minor parts of the AssemblyVersion have to match in order for binding to succeed. This is a sensible assumption, however it is ultimately incorrect (as of .NET 3.5), and it’s trivial to verify this for your version of the CLR. Just execute this sample code.
On my machine the second assembly load fails, and the last two lines of the fusion log make it perfectly clear why:
.NET Framework Version: 2.0.50727.3521
---
Attempting to load assembly: Rhino.Mocks, Version=3.5.0.1337, Culture=neutral, PublicKeyToken=0b3305902db7183f
Successfully loaded assembly: Rhino.Mocks, Version=3.5.0.1337, Culture=neutral, PublicKeyToken=0b3305902db7183f
---
Attempting to load assembly: Rhino.Mocks, Version=3.5.0.1336, Culture=neutral, PublicKeyToken=0b3305902db7183f
Assembly binding for failed:
System.IO.FileLoadException: Could not load file or assembly 'Rhino.Mocks, Version=3.5.0.1336, Culture=neutral,
PublicKeyToken=0b3305902db7183f' or one of its dependencies. The located assembly's manifest definition
does not match the assembly reference. (Exception from HRESULT: 0x80131040)
File name: 'Rhino.Mocks, Version=3.5.0.1336, Culture=neutral, PublicKeyToken=0b3305902db7183f'
=== Pre-bind state information ===
LOG: User = Phoenix\Dani
LOG: DisplayName = Rhino.Mocks, Version=3.5.0.1336, Culture=neutral, PublicKeyToken=0b3305902db7183f
(Fully-specified)
LOG: Appbase = [...]
LOG: Initial PrivatePath = NULL
Calling assembly : AssemblyBinding, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null.
===
LOG: This bind starts in default load context.
LOG: No application configuration file found.
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v2.0.50727\config\machine.config.
LOG: Post-policy reference: Rhino.Mocks, Version=3.5.0.1336, Culture=neutral, PublicKeyToken=0b3305902db7183f
LOG: Attempting download of new URL [...].
WRN: Comparing the assembly name resulted in the mismatch: Revision Number
ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated.
I think the source of this confusion is probably because Microsoft originally intended to be a little more lenient on this strict matching of the full AssemblyVersion, by matching only on the Major and Minor version parts:
“When loading an assembly, the CLR will automatically find the latest installed servicing version that matches the major/minor version of the assembly being requested.” — Jeffrey Richter, [CLR via C# (Second Edition)] p. 56
This was the behaviour in Beta 1 of the 1.0 CLR, however this feature was removed before the 1.0 release, and hasn’t managed to re-surface in .NET 2.0:
“Note: I have just described how you should think of version numbers. Unfortunately, the CLR doesn’t treat version numbers this way. [In .NET 2.0], the CLR treats a version number as an opaque value, and if an assembly depends on version 1.2.3.4 of another assembly, the CLR tries to load version 1.2.3.4 only (unless a binding redirection is in place). However, Microsoft has plans to change the CLR’s loader in a future version so that it loads the latest build/revision for a given major/minor version of an assembly. For example, on a future version of the CLR, if the loader is trying to find version 1.2.3.4 of an assembly and version 1.2.5.0 exists, the loader with automatically pick up the latest servicing version. This will be a very welcome change to the CLR’s loader — I for one can’t wait.” — Jeffrey Richter, [CLR via C# (Second Edition)] p. 164 (Emphasis mine)
As this change still hasn’t been implemented, I think it’s safe to assume that Microsoft had back-tracked on this intent, and it is perhaps too late to change this now. I tried to search around the web to find out what happened with these plans, but I couldn’t find any answers. I still wanted to get to the bottom of it.
So I emailed Jeff Richter and asked him directly — I figured if anyone knew what happened, it would be him.
He replied within 12 hours, on a Saturday morning no less, and clarified that the .NET 1.0 Beta 1 loader did implement this ‘automatic roll-forward’ mechanism of picking up the latest available Build and Revision of an assembly, but this behaviour was reverted before .NET 1.0 shipped. It was later intended to revive this but it didn’t make it in before the CLR 2.0 shipped. Then came Silverlight, which took priority for the CLR team, so this functionality got delayed further. In the meantime, most of the people who were around in the days of CLR 1.0 Beta 1 have since moved on, so it’s unlikely that this will see the light of day, despite all the hard work that had already been put into it.
The current behaviour, it seems, is here to stay.
It is also worth noting from my discussion with Jeff that AssemblyFileVersion was only added after the removal of the ‘automatic roll-forward’ mechanism — because after 1.0 Beta 1, any change to the AssemblyVersion was a breaking change for your customers, there was then nowhere to safely store your build number. AssemblyFileVersion is that safe haven, since it’s never automatically examined by the CLR. Maybe it’s clearer that way, having two separate version numbers, with separate meanings, rather than trying to make that separation between the Major/Minor (breaking) and the Build/Revision (non-breaking) parts of the AssemblyVersion.
AssemblyVersion
The moral is that if you’re shipping assemblies that other developers are going to be referencing, you need to be extremely careful about when you do (and don’t) change the AssemblyVersion of those assemblies. Any changes to the AssemblyVersion will mean that application developers will either have to re-compile against the new version (to update those AssemblyRef entries) or use assembly binding redirects to manually override the binding.
Just take another look at the version attributes on mscorlib:
// Assembly mscorlib, Version 2.0.0.0
[assembly: AssemblyFileVersion("2.0.50727.3521")]
[assembly: AssemblyInformationalVersion("2.0.50727.3521")]
[assembly: AssemblyVersion("2.0.0.0")]
Note that it’s the AssemblyFileVersion that contains all the interesting servicing information (it’s the Revision part of this version that tells you what Service Pack you’re on), meanwhile the AssemblyVersion is fixed at a boring old 2.0.0.0. Any change to the AssemblyVersion would force every .NET application referencing mscorlib.dll to re-compile against the new version!
I found one Solution :
echo iconv('UTF-8', 'ASCII//TRANSLIT', utf8_encode($string));
use utf8_encode()
Right click on eclipse project go to build path and then configure build path you will see jre and maven will be unchecked check both of them and your error will be solved
I came across a similar issue. However this issue was caused because of the way i designed the pages to bring the requests in. I placed all of my .js files as the last thing to be applied to the page, therefore they are at the end of my document. The .js files have all my functions include. The script manager seems that to be able to call this function it needs the js file already present with the function being called at the time of load. Hope this helps anyone else.
Be careful when you are using one liner using sslKey or sslCert, as in Josh Peak's answer:
git clone -c http.sslCAPath="/path/to/selfCA" \
-c http.sslCAInfo="/path/to/selfCA/self-signed-certificate.crt" \
-c http.sslVerify=1 \
-c http.sslCert="/path/to/privatekey/myprivatecert.pem" \
-c http.sslCertPasswordProtected=0 \
https://mygit.server.com/projects/myproject.git myproject
Only Git 2.14.x/2.15 (Q3 2015) would be able to interpret a path like ~username/mykey
correctly (while it still can interpret an absolute path like /path/to/privatekey
).
See commit 8d15496 (20 Jul 2017) by Junio C Hamano (gitster
).
Helped-by: Charles Bailey (hashpling
).
(Merged by Junio C Hamano -- gitster
-- in commit 17b1e1d, 11 Aug 2017)
http.c
:http.sslcert
andhttp.sslkey
are both pathnamesBack when the modern http_options() codepath was created to parse various http.* options at 29508e1 ("Isolate shared HTTP request functionality", 2005-11-18, Git 0.99.9k), and then later was corrected for interation between the multiple configuration files in 7059cd9 ("
http_init()
: Fix config file parsing", 2009-03-09, Git 1.6.3-rc0), we parsed configuration variables likehttp.sslkey
,http.sslcert
as plain vanilla strings, becausegit_config_pathname()
that understands "~[username]/
" prefix did not exist.Later, we converted some of them (namely,
http.sslCAPath
andhttp.sslCAInfo
) to use the function, and added variables likehttp.cookeyFile
http.pinnedpubkey
to use the function from the beginning. Because of that, these variables all understand "~[username]/
" prefix.Make the remaining two variables,
http.sslcert
andhttp.sslkey
, also aware of the convention, as they are both clearly pathnames to files.
There is an excellent book about the topic:
http://www.amazon.com/Texturing-Modeling-Third-Procedural-Approach/dp/1558608486
It is biased toward non-real-time visual effects and animation generation, but the theory and ideas are usable outside of these fields, I suppose.
It may also worth to mention that there is a professional software package that implements a complete procedural workflow called SideFX's Houdini. You can use it to invent and prototype procedural solutions to problems, that you can later translate to code.
While it's a rather expensive package, it has a free evaluation licence, which can be used as a very nice educational and/or engineering tool.
Try the event delegation method, this works in almost all cases.
$(document.body).on('change',"#selectID",function (e) {
//doStuff
var optVal= $("#selectID option:selected").val();
});
There is a simple way to align vertically and horizontally a div in css.
Just put a height to your div and apply this style
.hv-center {
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
}
Hope this helped.
I had the same problem. I had created a file named .env, but in reality the file ended up being .env.txt.
I created a new file, saved it in form of 'No Extension' and boom, the file was real .env and worked perfectly.
To prevent this, make sure every BEGIN TRANSACTION has COMMIT
The following will say successful but will leave uncommitted transactions:
BEGIN TRANSACTION
BEGIN TRANSACTION
<SQL_CODE?
COMMIT
Closing query windows with uncommitted transactions will prompt you to commit your transactions. This will generally resolve the Error 1222 message.
I tend to use yield-return when I calculate the next item in the list (or even the next group of items).
Using your Version 2, you must have the complete list before returning. By using yield-return, you really only need to have the next item before returning.
Among other things, this helps spread the computational cost of complex calculations over a larger time-frame. For example, if the list is hooked up to a GUI and the user never goes to the last page, you never calculate the final items in the list.
Another case where yield-return is preferable is if the IEnumerable represents an infinite set. Consider the list of Prime Numbers, or an infinite list of random numbers. You can never return the full IEnumerable at once, so you use yield-return to return the list incrementally.
In your particular example, you have the full list of products, so I'd use Version 2.
<?php
// Checks if key exists (doesn't care about it's value).
// @link http://php.net/manual/en/function.array-key-exists.php
if (array_key_exists(20120504, $search_array)) {
echo $search_array[20120504];
}
// Checks against NULL
// @link http://php.net/manual/en/function.isset.php
if (isset($search_array[20120504])) {
echo $search_array[20120504];
}
// No warning or error if key doesn't exist plus checks for emptiness.
// @link http://php.net/manual/en/function.empty.php
if (!empty($search_array[20120504])) {
echo $search_array[20120504];
}
?>
According to the w3c, cols and rows are both required attributes for textareas. Rows and Cols are the number of characters that are going to fit in the textarea rather than pixels or some other potentially arbitrary value. Go with the rows/cols.
To load data via a GET request you don't need any URLRequest
(and no semicolons)
let listUrlString = "http://bla.com?batchSize=" + String(batchSize) + "&fromIndex=" + String(fromIndex)
let myUrl = URL(string: listUrlString)!
let task = URLSession.shared.dataTask(with: myUrl) { ...
you can also pass the parameters through the command line. Command line arguments are stores in the array ARGV. so ARGV[0] is the first number and ARGV[1] the second number
#!/usr/bin/ruby
first_number = ARGV[0].to_i
second_number = ARGV[1].to_i
puts first_number + second_number
and you call it like this
% ./plus.rb 5 6
==> 11
You can do following:
private Date getMeYesterday(){
return new Date(System.currentTimeMillis()-24*60*60*1000);
}
Note: if you want further backward date multiply number of day with 24*60*60*1000 for example:
private Date getPreviousWeekDate(){
return new Date(System.currentTimeMillis()-7*24*60*60*1000);
}
Similarly, you can get future date by adding the value to System.currentTimeMillis(), for example:
private Date getMeTomorrow(){
return new Date(System.currentTimeMillis()+24*60*60*1000);
}
you can put your data directly in a url statment like
src = 'url(imageData)' ;
and to get the image data u can use the php function
$imageContent = file_get_contents("imageDir/".$imgName);
$imageData = base64_encode($imageContent);
so you can copy paste the value of imageData and paste it directly to your url and assign it to the src attribute of your image
In your header file say foo.h
class Foo{
public:
static void someFunction(params..);
// other stuff
}
In your implementation file say foo.cpp
#include "foo.h"
void Foo::someFunction(params..){
// Implementation of someFunction
}
Just make sure you don't use the static keyword in your method signature when you are implementing the static function in your implementation file.
Good Luck
Maybe you can try to save the old value with the "onfocus" event to afterwards compare it with the new value with the "onchange" event.
I know angular has hierarchical injectors like Thierry said.
But I have another option here in case you find a use-case where you don't really want to inject it at the parent.
We can achieve that by creating an instance of the service, and on provide always return that.
import { provide, Injectable } from '@angular/core';
import { Http } from '@angular/core'; //Dummy example of dependencies
@Injectable()
export class YourService {
private static instance: YourService = null;
// Return the instance of the service
public static getInstance(http: Http): YourService {
if (YourService.instance === null) {
YourService.instance = new YourService(http);
}
return YourService.instance;
}
constructor(private http: Http) {}
}
export const YOUR_SERVICE_PROVIDER = [
provide(YourService, {
deps: [Http],
useFactory: (http: Http): YourService => {
return YourService.getInstance(http);
}
})
];
And then on your component you use your custom provide method.
@Component({
providers: [YOUR_SERVICE_PROVIDER]
})
And you should have a singleton service without depending on the hierarchical injectors.
I'm not saying this is a better way, is just in case someone has a problem where hierarchical injectors aren't possible.
The syntax you have used is incorrect. The query should be something like:
SELECT column_name(s) FROM tablename WHERE id = (SELECT MAX(id) FROM tablename)
This Javascript function purports to show the difference between the Blob File API and the Data API to download a JSON file in the client browser:
/**_x000D_
* Save a text as file using HTML <a> temporary element and Blob_x000D_
* @author Loreto Parisi_x000D_
*/_x000D_
_x000D_
var saveAsFile = function(fileName, fileContents) {_x000D_
if (typeof(Blob) != 'undefined') { // Alternative 1: using Blob_x000D_
var textFileAsBlob = new Blob([fileContents], {type: 'text/plain'});_x000D_
var downloadLink = document.createElement("a");_x000D_
downloadLink.download = fileName;_x000D_
if (window.webkitURL != null) {_x000D_
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);_x000D_
} else {_x000D_
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);_x000D_
downloadLink.onclick = document.body.removeChild(event.target);_x000D_
downloadLink.style.display = "none";_x000D_
document.body.appendChild(downloadLink);_x000D_
}_x000D_
downloadLink.click();_x000D_
} else { // Alternative 2: using Data_x000D_
var pp = document.createElement('a');_x000D_
pp.setAttribute('href', 'data:text/plain;charset=utf-8,' +_x000D_
encodeURIComponent(fileContents));_x000D_
pp.setAttribute('download', fileName);_x000D_
pp.onclick = document.body.removeChild(event.target);_x000D_
pp.click();_x000D_
}_x000D_
} // saveAsFile_x000D_
_x000D_
/* Example */_x000D_
var jsonObject = {"name": "John", "age": 30, "car": null};_x000D_
saveAsFile('out.json', JSON.stringify(jsonObject, null, 2));
_x000D_
The function is called like saveAsFile('out.json', jsonString);
. It will create a ByteStream immediately recognized by the browser that will download the generated file directly using the File API URL.createObjectURL
.
In the else
, it is possible to see the same result obtained via the href
element plus the Data API, but this has several limitations that the Blob API has not.
The example Java data structure in the original question does not match the description of the JSON structure in the comment.
The JSON is described as
"an array of {object with an array of {object}}".
In terms of the types described in the question, the JSON translated into a Java data structure that would match the JSON structure for easy deserialization with Gson is
"an array of {TypeDTO object with an array of {ItemDTO object}}".
But the Java data structure provided in the question is not this. Instead it's
"an array of {TypeDTO object with an array of an array of {ItemDTO object}}".
A two-dimensional array != a single-dimensional array.
This first example demonstrates using Gson to simply deserialize and serialize a JSON structure that is "an array of {object with an array of {object}}".
input.json Contents:
[
{
"id":1,
"name":"name1",
"items":
[
{"id":2,"name":"name2","valid":true},
{"id":3,"name":"name3","valid":false},
{"id":4,"name":"name4","valid":true}
]
},
{
"id":5,
"name":"name5",
"items":
[
{"id":6,"name":"name6","valid":true},
{"id":7,"name":"name7","valid":false}
]
},
{
"id":8,
"name":"name8",
"items":
[
{"id":9,"name":"name9","valid":true},
{"id":10,"name":"name10","valid":false},
{"id":11,"name":"name11","valid":false},
{"id":12,"name":"name12","valid":true}
]
}
]
Foo.java:
import java.io.FileReader;
import java.util.ArrayList;
import com.google.gson.Gson;
public class Foo
{
public static void main(String[] args) throws Exception
{
Gson gson = new Gson();
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
System.out.println(gson.toJson(myTypes));
}
}
class TypeDTO
{
int id;
String name;
ArrayList<ItemDTO> items;
}
class ItemDTO
{
int id;
String name;
Boolean valid;
}
This second example uses instead a JSON structure that is actually "an array of {TypeDTO object with an array of an array of {ItemDTO object}}" to match the originally provided Java data structure.
input.json Contents:
[
{
"id":1,
"name":"name1",
"items":
[
[
{"id":2,"name":"name2","valid":true},
{"id":3,"name":"name3","valid":false}
],
[
{"id":4,"name":"name4","valid":true}
]
]
},
{
"id":5,
"name":"name5",
"items":
[
[
{"id":6,"name":"name6","valid":true}
],
[
{"id":7,"name":"name7","valid":false}
]
]
},
{
"id":8,
"name":"name8",
"items":
[
[
{"id":9,"name":"name9","valid":true},
{"id":10,"name":"name10","valid":false}
],
[
{"id":11,"name":"name11","valid":false},
{"id":12,"name":"name12","valid":true}
]
]
}
]
Foo.java:
import java.io.FileReader;
import java.util.ArrayList;
import com.google.gson.Gson;
public class Foo
{
public static void main(String[] args) throws Exception
{
Gson gson = new Gson();
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
System.out.println(gson.toJson(myTypes));
}
}
class TypeDTO
{
int id;
String name;
ArrayList<ItemDTO> items[];
}
class ItemDTO
{
int id;
String name;
Boolean valid;
}
Regarding the remaining two questions:
is Gson extremely fast?
Not compared to other deserialization/serialization APIs. Gson has traditionally been amongst the slowest. The current and next releases of Gson reportedly include significant performance improvements, though I haven't looked for the latest performance test data to support those claims.
That said, if Gson is fast enough for your needs, then since it makes JSON deserialization so easy, it probably makes sense to use it. If better performance is required, then Jackson might be a better choice to use. It offers much (maybe even all) of the conveniences of Gson.
Or am I better to stick with what I've got working already?
I wouldn't. I would most always rather have one simple line of code like
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
...to easily deserialize into a complex data structure, than the thirty lines of code that would otherwise be needed to map the pieces together one component at a time.
You can use the include?
method:
my_string = "abcdefg"
if my_string.include? "cde"
puts "String includes 'cde'"
end
I've seen that problem when I'm writing to a filesystem which doesn't (properly) handle times -- I think SMB shares or FAT or something.
What is your target filesystem?
Try decoding it first, then encoding:
apple.decode('iso-8859-1').encode('utf8')
One of The Shortest method i found for single value while i was searching for myself, is just passing single string and setting string as model in view like this.
In your Partial calling side
@Html.Partial("ParitalAction", "String data to pass to partial")
And then binding the model with Partial View like this
@model string
and the using its value in Partial View like this
@Model
You can also play with other datatypes like array, int or more complex data types like IDictionary or something else.
Hope it helps,
You can also do this:
var x = new object[] {
new { firstName = "john", lastName = "walter" },
new { brand = "BMW" }
};
And if they are the same anonymous type (firstName and lastName), you won't need to cast as object
.
var y = new [] {
new { firstName = "john", lastName = "walter" },
new { firstName = "jill", lastName = "white" }
};
Below code snippet might help.
import UIKit
extension UIImage {
func cropImage(toRect rect: CGRect) -> UIImage? {
if let imageRef = self.cgImage?.cropping(to: rect) {
return UIImage(cgImage: imageRef)
}
return nil
}
}
const generateUniqueId = () => 'id_' + Date.now() + String(Math.random()).substr(2);
// if u want to check for collision
const arr = [];
const checkForCollision = () => {
for (let i = 0; i < 10000; i++) {
const el = generateUniqueId();
if (arr.indexOf(el) > -1) {
alert('COLLISION FOUND');
}
arr.push(el);
}
};
I took klaus se's and aganders3's answer, and made a documented module that is more readable and holds in one file. You can just add it to your project. It even has an optional progress bar !
"""
The ``processes`` module provides some convenience functions
for using parallel processes in python.
Adapted from http://stackoverflow.com/a/16071616/287297
Example usage:
print prll_map(lambda i: i * 2, [1, 2, 3, 4, 6, 7, 8], 32, verbose=True)
Comments:
"It spawns a predefined amount of workers and only iterates through the input list
if there exists an idle worker. I also enabled the "daemon" mode for the workers so
that KeyboardInterupt works as expected."
Pitfalls: all the stdouts are sent back to the parent stdout, intertwined.
Alternatively, use this fork of multiprocessing:
https://github.com/uqfoundation/multiprocess
"""
# Modules #
import multiprocessing
from tqdm import tqdm
################################################################################
def apply_function(func_to_apply, queue_in, queue_out):
while not queue_in.empty():
num, obj = queue_in.get()
queue_out.put((num, func_to_apply(obj)))
################################################################################
def prll_map(func_to_apply, items, cpus=None, verbose=False):
# Number of processes to use #
if cpus is None: cpus = min(multiprocessing.cpu_count(), 32)
# Create queues #
q_in = multiprocessing.Queue()
q_out = multiprocessing.Queue()
# Process list #
new_proc = lambda t,a: multiprocessing.Process(target=t, args=a)
processes = [new_proc(apply_function, (func_to_apply, q_in, q_out)) for x in range(cpus)]
# Put all the items (objects) in the queue #
sent = [q_in.put((i, x)) for i, x in enumerate(items)]
# Start them all #
for proc in processes:
proc.daemon = True
proc.start()
# Display progress bar or not #
if verbose:
results = [q_out.get() for x in tqdm(range(len(sent)))]
else:
results = [q_out.get() for x in range(len(sent))]
# Wait for them to finish #
for proc in processes: proc.join()
# Return results #
return [x for i, x in sorted(results)]
################################################################################
def test():
def slow_square(x):
import time
time.sleep(2)
return x**2
objs = range(20)
squares = prll_map(slow_square, objs, 4, verbose=True)
print "Result: %s" % squares
EDIT: Added @alexander-mcfarlane suggestion and a test function
PHP 7.0: Using the explode function and create a list of all the results.
list($subdomain,$host) = explode('.', $_SERVER["SERVER_NAME"]);
Example: sub.domain.com
echo $subdomain;
Result: sub
echo $host;
Result: domain
for i=1,#target do
game.Players.target[i].Character:BreakJoints()
end
Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:
game.Players.target.1.Character:BreakJoints()
Which is completely incorrect.
c = game.Players:GetChildren()
Never use "Players:GetChildren()", it is not guaranteed to return only players.
Instead use:
c = Game.Players:GetPlayers()
if msg:lower()=="me" then
table.insert(people, source)
return people
Here you add the player's name in the list "people", where you in the other places adds the player object.
Fixed code:
local Admins = {"FakeNameHereSoNoStalkers"}
function Kill(Players)
for i,Player in ipairs(Players) do
if Player.Character then
Player.Character:BreakJoints()
end
end
end
function IsAdmin(Player)
for i,AdminName in ipairs(Admins) do
if Player.Name:lower() == AdminName:lower() then return true end
end
return false
end
function GetPlayers(Player,Msg)
local Targets = {}
local Players = Game.Players:GetPlayers()
if Msg:lower() == "me" then
Targets = { Player }
elseif Msg:lower() == "all" then
Targets = Players
elseif Msg:lower() == "others" then
for i,Plr in ipairs(Players) do
if Plr ~= Player then
table.insert(Targets,Plr)
end
end
else
for i,Plr in ipairs(Players) do
if Plr.Name:lower():sub(1,Msg:len()) == Msg then
table.insert(Targets,Plr)
end
end
end
return Targets
end
Game.Players.PlayerAdded:connect(function(Player)
if IsAdmin(Player) then
Player.Chatted:connect(function(Msg)
if Msg:lower():sub(1,6) == ":kill " then
Kill(GetPlayers(Player,Msg:sub(7)))
end
end)
end
end)
CASE WHEN B.[STAT] IS NULL THEN (C.[EVENT DATE]+10) -- Type DATETIME
ELSE '-' -- Type VARCHAR
END AS [DATE]
You need to select one type or the other for the field, the field type can't vary by row.
The simplest is to remove the ELSE '-'
and let it implicitly get the value NULL
instead for the second case.
Check this link , and last comment , You have to use WebChromeClient
for your purpose.
Happened to me today.
My issue was that I had too many tabs open (I didn't know they were open) with source code on them.
If you close all the tabs, maybe you will unconfuse IntelliJ into indexing the dependencies correctly
This is what you can do:
class Profile < ActiveRecord::Base
before_save :set_default_val
def set_default_val
self.send_updates = 'val' unless self.send_updates
end
end
EDIT: ...but apparently this is a Rookie mistake!
Suppose you have this scenario where you stash your changes in order to pull from origin. Possibly because your local changes are just debug: true
in some settings file. Now you pull and someone has introduced a new setting there, creating a conflict.
git status
says:
# On branch master
# Unmerged paths:
# (use "git reset HEAD <file>..." to unstage)
# (use "git add/rm <file>..." as appropriate to mark resolution)
#
# both modified: src/js/globals.tpl.js
no changes added to commit (use "git add" and/or "git commit -a")
Okay. I decided to go with what Git suggested: I resolved the conflict and committed:
vim src/js/globals.tpl.js
# type type type …
git commit -a -m WIP # (short for "work in progress")
Now my working copy is in the state I want, but I have created a commit that I don't want to have. How do I get rid of that commit without modifying my working copy? Wait, there's a popular command for that!
git reset HEAD^
My working copy has not been changed, but the WIP commit is gone. That's exactly what I wanted! (Note that I'm not using --soft
here, because if there are auto-merged files in your stash, they are auto-staged and thus you'd end up with these files being staged again after reset
.)
But there's one more thing left: The man page for git stash pop
reminds us that "Applying the state can fail with conflicts; in this case, it is not removed from the stash list. You need to resolve the conflicts by hand and call git stash drop
manually afterwards." So that's exactly what we do now:
git stash drop
And done.
The canvas
DOM element has .height
and .width
properties that correspond to the height="…"
and width="…"
attributes. Set them to numeric values in JavaScript code to resize your canvas. For example:
var canvas = document.getElementsByTagName('canvas')[0];
canvas.width = 800;
canvas.height = 600;
Note that this clears the canvas, though you should follow with ctx.clearRect( 0, 0, ctx.canvas.width, ctx.canvas.height);
to handle those browsers that don't fully clear the canvas. You'll need to redraw of any content you wanted displayed after the size change.
Note further that the height and width are the logical canvas dimensions used for drawing and are different from the style.height
and style.width
CSS attributes. If you don't set the CSS attributes, the intrinsic size of the canvas will be used as its display size; if you do set the CSS attributes, and they differ from the canvas dimensions, your content will be scaled in the browser. For example:
// Make a canvas that has a blurry pixelated zoom-in
// with each canvas pixel drawn showing as roughly 2x2 on screen
canvas.width = 400;
canvas.height = 300;
canvas.style.width = '800px';
canvas.style.height = '600px';
See this live example of a canvas that is zoomed in by 4x.
var c = document.getElementsByTagName('canvas')[0];_x000D_
var ctx = c.getContext('2d');_x000D_
ctx.lineWidth = 1;_x000D_
ctx.strokeStyle = '#f00';_x000D_
ctx.fillStyle = '#eff';_x000D_
_x000D_
ctx.fillRect( 10.5, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 10.5, 10.5, 20, 20 );_x000D_
ctx.fillRect( 40, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 40, 10.5, 20, 20 );_x000D_
ctx.fillRect( 70, 10, 20, 20 );_x000D_
ctx.strokeRect( 70, 10, 20, 20 );_x000D_
_x000D_
ctx.strokeStyle = '#fff';_x000D_
ctx.strokeRect( 10.5, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 40, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 70, 10, 20, 20 );
_x000D_
body { background:#eee; margin:1em; text-align:center }_x000D_
canvas { background:#fff; border:1px solid #ccc; width:400px; height:160px }
_x000D_
<canvas width="100" height="40"></canvas>_x000D_
<p>Showing that re-drawing the same antialiased lines does not obliterate old antialiased lines.</p>
_x000D_
You can remove the border from top if the element is sibling of the row . Add this to css :
.row + .row {
border-top:0;
}
Here is the link to the fiddle http://jsfiddle.net/7cb3Y/3/
Your syntax is incorrect. The var
keyword in your for
loop must be followed by a variable name, in this case its propName
var propValue;
for(var propName in nyc) {
propValue = nyc[propName]
console.log(propName,propValue);
}
I suggest you have a look here for some basics:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
As of HTML5 it is OK to wrap <a>
elements around a <div>
(or any other block elements):
The a element may be wrapped around entire paragraphs, lists, tables, and so forth, even entire sections, so long as there is no interactive content within (e.g. buttons or other links).
Just have to make sure you don't put an <a>
within your <a>
( or a <button>
).
Follow this steps:
-Build
-Generate Signed Apk
-Create new
Then fill up "New Key Store" form. If you wand to change .jnk file destination then chick on destination and give a name to get Ok button. After finishing it you will get "Key store password", "Key alias", "Key password" Press next and change your the destination folder. Then press finish, thats all. :)
IMHO the accepted answer is correct but misses some 'teaching' as it does not explain how to come up with the answer. For all deprecated classes look at the JavaDoc (if you do not have it either download it or go online), it will hint at which class to use to replace the old code. Of course it will not tell you everything, but this is a start. Example:
...
*
* @deprecated (4.3) use {@link HttpClientBuilder}. <----- THE HINT IS HERE !
*/
@ThreadSafe
@Deprecated
public class DefaultHttpClient extends AbstractHttpClient {
Now you have the class to use, HttpClientBuilder
, as there is no constructor to get a builder instance you may guess that there must be a static method instead: create
. Once you have the builder you can also guess that as for most builders there is a build method, thus:
org.apache.http.impl.client.HttpClientBuilder.create().build();
AutoClosable:
As Jules hinted in the comments, the returned class implements java.io.Closable
, so if you use Java 7 or above you can now do:
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {...}
The advantage is that you do not have to deal with finally and nulls.
Other relevant info
Also make sure to read about connection pooling and set the timeouts.
An example based on Chuck's answer:
myIntToStr :: Int -> String
myIntToStr x
| x < 3 = show x ++ " is less than three"
| otherwise = "normal"
Note that without the show
the third line will not compile.
A completely valid way to select all browsers but IE8 and below is using the :root
selector. Since IE versions 8 and below do not support :root
, selectors containing it are ignored. This means you could do something like this:
p {color:red;}
:root p {color:blue;}
This is still completely valid CSS, but it does cause IE8 and lower to render different styles.
Here's a list of all completely valid CSS browser-specific selectors I could find, except for some that seem quite redundant, such as ones that select for just 1 type of ancient browser (1, 2):
/****** First the hacks that target certain specific browsers ******/
* html p {color:red;} /* IE 6- */
*+html p {color:red;} /* IE 7 only */
@media screen and (-webkit-min-device-pixel-ratio:0) {
p {color:red;}
} /* Chrome, Safari 3+ */
p, body:-moz-any-link {color:red;} /* Firefox 1+ */
:-webkit-any(html) p {color:red;} /* Chrome 12+, Safari 5.1.3+ */
:-moz-any(html) p {color:red;} /* Firefox 4+ */
/****** And then the hacks that target all but certain browsers ******/
html> body p {color:green;} /* not: IE<7 */
head~body p {color:green;} /* not: IE<7, Opera<9, Safari<3 */
html:first-child p {color:green;} /* not: IE<7, Opera<9.5, Safari&Chrome<4, FF<3 */
html>/**/body p {color:green;} /* not: IE<8 */
body:first-of-type p {color:green;} /* not: IE<9, Opera<9, Safari<3, FF<3.5 */
:not([ie8min]) p {color:green;} /* not: IE<9, Opera<9.5, Safari<3.2 */
body:not([oldbrowser]) p {color:green;} /* not: IE<9, Opera<9.5, Safari<3.2 */
I think there is something wrong with method_defined?
in Rails. It may be inconsistent or something, so if you use Rails, it's better to use something from attribute_method?(attribute)
.
"testing for method_defined? on ActiveRecord classes doesn't work until an instantiation" is a question about the inconsistency.
Think of it as the natural orthogonal operation to split.
I understand why it is applicable to anything iterable and so can't easily be implemented just on list.
For readability, I'd like to see it in the language but I don't think that is actually feasible - if iterability were an interface then it could be added to the interface but it is just a convention and so there's no central way to add it to the set of things which are iterable.
I always fall back on this solution. Not too hack-ish and gets the job done.
EDIT: I should point out that you might achieve the effect you want with the following code (forgive the inline styles; they should be in a separate sheet). It seems that the default alignment on an image (baseline) will cause the text to align to the baseline; setting that to middle gets things to render nicely, at least in FireFox 3.
<div>_x000D_
<img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.svg" style="vertical-align: middle;" width="100px"/>_x000D_
<span style="vertical-align: middle;">Here is some text.</span>_x000D_
</div>
_x000D_
http://docs.ansible.com/ansible/latest/plugins/lookup/dig.html
so in template, for e. g.:
{{ lookup('dig', ansible_host) }}
Notes:
But still it serves 99 % (figuratively speaking) of use cases.
The problem is that your <label>
is inside of an <h2>
tag, and header tags have a margin
set by the default stylesheet.
A solution that is simple to understand and works with no primary key:
1) add a new boolean column
alter table mytable add tokeep boolean;
2) add a constraint on the duplicated columns AND the new column
alter table mytable add constraint preventdupe unique (mycol1, mycol2, tokeep);
3) set the boolean column to true. This will succeed only on one of the duplicated rows because of the new constraint
update ignore mytable set tokeep = true;
4) delete rows that have not been marked as tokeep
delete from mytable where tokeep is null;
5) drop the added column
alter table mytable drop tokeep;
I suggest that you keep the constraint you added, so that new duplicates are prevented in the future.
Essentially the same as Gringo Suave's answer, but with a generator:
from datetime import datetime, timedelta
def datetime_range(start=None, end=None):
span = end - start
for i in xrange(span.days + 1):
yield start + timedelta(days=i)
Then you can use it as follows:
In: list(datetime_range(start=datetime(2014, 1, 1), end=datetime(2014, 1, 5)))
Out:
[datetime.datetime(2014, 1, 1, 0, 0),
datetime.datetime(2014, 1, 2, 0, 0),
datetime.datetime(2014, 1, 3, 0, 0),
datetime.datetime(2014, 1, 4, 0, 0),
datetime.datetime(2014, 1, 5, 0, 0)]
Or like this:
In []: for date in datetime_range(start=datetime(2014, 1, 1), end=datetime(2014, 1, 5)):
...: print date
...:
2014-01-01 00:00:00
2014-01-02 00:00:00
2014-01-03 00:00:00
2014-01-04 00:00:00
2014-01-05 00:00:00
It breaks semantics, that's all. It works fine, but there may be screen readers or something down the road that won't enjoy processing your HTML if you "break semantics".
To convert the private key from PKCS#1 to PKCS#8 with openssl:
# openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in pkcs1.key -out pkcs8.key
That will work as long as you have the PKCS#1 key in PEM (text format) as described in the question.
The XML configuration of Spring is composed of Beans and Beans are basically classes. They're just POJOs that we use inside of our ApplicationContext. Defining Beans can be thought of as replacing the keyword new. So wherever you are using the keyword new in your application something like:
MyRepository myRepository =new MyRepository ();
Where you're using that keyword new that's somewhere you can look at removing that configuration and placing it into an XML file. So we will code like this:
<bean name="myRepository "
class="com.demo.repository.MyRepository " />
Now we can simply use Setter Injection/ Constructor Injection. I'm using Setter Injection.
public class MyServiceImpl implements MyService {
private MyRepository myRepository;
public void setMyRepository(MyRepository myRepository)
{
this.myRepository = myRepository ;
}
public List<Customer> findAll() {
return myRepository.findAll();
}
}
Use predefined git alias, i.e.:
$ git work
Created once by command:
$ git config --global alias.work 'log --pretty=format:"%h%x09%an%x09%ad%x09%s"'
https://git-scm.com/book/tr/v2/Git-Basics-Git-Aliases
Or more colored with graph:
$ git config --global alias.work 'log --pretty=format:"%C(yellow)%h %ar %C(auto)%d %Creset %s , %Cblue%cn" --graph --all'
Several things:
Age
is not an integer - it is a nullable integer type. They are not the same. See the documentation for Nullable<T>
on MSDN for details.
??
is the null coalesce operator, not the ternary operator (actually called the conditional operator).
To check if a nullable type has a value use HasValue
, or check directly against null
:
if(Age.HasValue)
{
// Yay, it does!
}
if(Age == null)
{
// It is null :(
}
This one always keeps the right frame:
public extension UIView {
@discardableResult
public func addBlur(style: UIBlurEffect.Style = .extraLight) -> UIVisualEffectView {
let blurEffect = UIBlurEffect(style: style)
let blurBackground = UIVisualEffectView(effect: blurEffect)
addSubview(blurBackground)
blurBackground.translatesAutoresizingMaskIntoConstraints = false
blurBackground.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
blurBackground.topAnchor.constraint(equalTo: topAnchor).isActive = true
blurBackground.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
blurBackground.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
return blurBackground
}
}
Gold Noise
// Gold Noise ©2015 [email protected]
// - based on the Golden Ratio
// - uniform normalized distribution
// - fastest static noise generator function (also runs at low precision)
float PHI = 1.61803398874989484820459; // F = Golden Ratio
float gold_noise(in vec2 xy, in float seed){
return fract(tan(distance(xy*PHI, xy)*seed)*xy.x);
}
See Gold Noise in your browser right now!
This function has improved random distribution over the current function in @appas' answer as of Sept 9, 2017:
The @appas function is also incomplete, given there is no seed supplied (uv is not a seed - same for every frame), and does not work with low precision chipsets. Gold Noise runs at low precision by default (much faster).
print "bla: ", $_, "\n" if ($_ = $myvar) =~ s/a/b/g or 1;
[^a-zA-Z\d\s:]
There's a property spring.resources.staticLocations
that can be set in the application.properties
. Note that this will override the default locations. See org.springframework.boot.autoconfigure.web.ResourceProperties
.
def versiontuple(v):
return tuple(map(int, (v.split("."))))
>>> versiontuple("2.3.1") > versiontuple("10.1.1")
False
map
is the most logical solution for this problem.
let xs = [1, 2, 3];
xs = xs.map(x => 42);
xs // -> [42, 42, 42]
However, if there is a chance that the array is sparse, you'll need to use for
or, even better, for .. of
.
See:
import numpy as np
w=np.array([ 0.4, 0.8, 1.6, 0.8, 0.4])
np.random.choice(w, p=w/sum(w))
See the github repo, works with Django 3
Run startproject::
$ django-admin.py startproject sample
now a folder(sample) is created.
Create an app::
$ cd sample
$ python manage.py startapp uploader
Now a folder(uploader
) with these files are created::
uploader/
__init__.py
admin.py
app.py
models.py
tests.py
views.py
migrations/
__init__.py
On sample/settings.py
add 'uploader'
to INSTALLED_APPS
and add MEDIA_ROOT
and MEDIA_URL
, ie::
INSTALLED_APPS = [
'uploader',
...<other apps>...
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
in sample/urls.py
add::
...<other imports>...
from django.conf import settings
from django.conf.urls.static import static
from uploader import views as uploader_views
urlpatterns = [
...<other url patterns>...
path('', uploader_views.UploadView.as_view(), name='fileupload'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
update uploader/models.py
::
from django.db import models
class Upload(models.Model):
upload_file = models.FileField()
upload_date = models.DateTimeField(auto_now_add =True)
update uploader/views.py
::
from django.views.generic.edit import CreateView
from django.urls import reverse_lazy
from .models import Upload
class UploadView(CreateView):
model = Upload
fields = ['upload_file', ]
success_url = reverse_lazy('fileupload')
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['documents'] = Upload.objects.all()
return context
Create a folder sample/uploader/templates/uploader
Create a file upload_form.html ie sample/uploader/templates/uploader/upload_form.html
::
<div style="padding:40px;margin:40px;border:1px solid #ccc">
<h1>Django File Upload</h1>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form><hr>
<ul>
{% for document in documents %}
<li>
<a href="{{ document.upload_file.url }}">{{ document.upload_file.name }}</a>
<small>({{ document.upload_file.size|filesizeformat }}) - {{document.upload_date}}</small>
</li>
{% endfor %}
</ul>
</div>
Syncronize database and runserver::
$ python manage.py makemigrations
$ python manage.py migrate
$ python manage.py runserver
visit http://localhost:8000/
It will definitely cost you more space & bandwidth if you want to use base64 encoded images. However if your site has a lot of small images you can decrease the page loading time by encoding your images to base64 and placing them into html. In this way, the client browser wont need to make a lot of connections to the images, but will have them in html.
Oops, the sed command has to precede the tidy command of course:
echo "$htmlstr" |
sed '/type="global"/d' |
tidy -q -c -wrap 0 -numeric -asxml -utf8 --merge-divs yes --merge-spans yes 2>/dev/null |
xmlstarlet sel -N x="http://www.w3.org/1999/xhtml" -T -t -m "//x:table" -v '@name' -n
or in the .htaccess file
AddOutputFilter DEFLATE css js
ExpiresActive On
ExpiresByType application/x-javascript A2592000
Angular provides filters to modify a collection. In this case the collection would be null, i.e. [], and the filter also takes arguments, as follows:
<div id="demo">
<ul>
<li ng-repeat="not in []|fixedNumber:number track by $index">{{$index}}</li>
</ul>
</div>
JS:
module.filter('fixedNumber', function() {
return function(emptyarray, number) {
return Array(number);
}
});
module.controller('myCtrl', ['$scope', function($scope) {
$scope.number = 5;
}]);
This method is very similar to those proposed above and isn't necessarily superior but shows the power of filters in AngularJS.
There is an old plugin called HEX Editor here.
According to this question on Super User it does not work on newer versions of Notepad++ and might have some stability issues, but it still could be useful depending on your needs.
You could add dataformatstring="{0:M-dd-yyyy}
" attribute to the bound field, like this:
<asp:BoundField DataField="Date" HeaderText="Date" DataFormatString="{0:dd-M-yyyy}" />
What OS you are using and which Webserver? On Linux and Apache you can find the apache error_log in /var/log/apache2/
You want to get the computed width. Try: .offsetWidth
(I.e: this.offsetWidth='50px'
or var w=this.offsetWidth
)
You might also like this answer on SO.
In order to avoid the black background when starting an activity already in the stack, I added
overridePendingTransition(0,0)
in onStart()
:
@Override
protected void onStart() {
overridePendingTransition(0,0);
super.onStart();
}
You can use a custom style:
<!-- Alert Dialog -->
<style name="ThemeOverlay.MaterialComponents.MaterialAlertDialog_Background" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
<!-- Background Color-->
<item name="android:background">@color/.....</item>
<!-- Text Color for title and message -->
<item name="colorOnSurface">@color/......</item>
<!-- Style for positive button -->
<item name="buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
<!-- Style for negative button -->
<item name="buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
</style>
<style name="PositiveButtonStyle" parent="@style/Widget.MaterialComponents.Button">
<!-- text color for the button -->
<item name="android:textColor">@color/.....</item>
<!-- Background tint for the button -->
<item name="backgroundTint">@color/primaryDarkColor</item>
</style>
And just use the default MaterialAlertDialogBuilder
:
new MaterialAlertDialogBuilder(AlertDialogActivity.this,
R.style.ThemeOverlay_MaterialComponents_MaterialAlertDialog_Background)
.setTitle("Dialog")
.setMessage("Message... ....")
.setPositiveButton("Ok", /* listener = */ null)
.show();
This solution:
Minimum version of jQuery is 1.12
$(document).ready(function () {
function poll () {
$.get({
url: '/api/stream/',
success: function (data) {
console.log(data)
},
timeout: 10000 // == 10 seconds timeout
}).always(function () {
setTimeout(poll, 30000) // == 30 seconds polling period
})
}
// start polling
poll()
})
In both examples, you are assigning a new int[10]
to a reference variable.
Assigning to a reference variable either way will be equal in performance.
int[] array = new int[10];
The notation above is considered best practice for readability.
Cheers
Distinguishing contexts by setting the default schema
In EF6 you can have multiple contexts, just specify the name for the default database schema in the OnModelCreating
method of you DbContext
derived class (where the Fluent-API configuration is).
This will work in EF6:
public partial class CustomerModel : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("Customer");
// Fluent API configuration
}
}
This example will use "Customer" as prefix for your database tables (instead of "dbo").
More importantly it will also prefix the __MigrationHistory
table(s), e.g. Customer.__MigrationHistory
.
So you can have more than one __MigrationHistory
table in a single database, one for each context.
So the changes you make for one context will not mess with the other.
When adding the migration, specify the fully qualified name of your configuration class (derived from DbMigrationsConfiguration
) as parameter in the add-migration
command:
add-migration NAME_OF_MIGRATION -ConfigurationTypeName FULLY_QUALIFIED_NAME_OF_CONFIGURATION_CLASS
A short word on the context key
According to this MSDN article "Chapter - Multiple Models Targeting the Same Database" EF 6 would probably handle the situation even if only one MigrationHistory
table existed, because in the table there is a ContextKey column to distinguish the migrations.
However I prefer having more than one MigrationHistory
table by specifying the default schema like explained above.
Using separate migration folders
In such a scenario you might also want to work with different "Migration" folders in you project. You can set up your DbMigrationsConfiguration
derived class accordingly using the MigrationsDirectory
property:
internal sealed class ConfigurationA : DbMigrationsConfiguration<ModelA>
{
public ConfigurationA()
{
AutomaticMigrationsEnabled = false;
MigrationsDirectory = @"Migrations\ModelA";
}
}
internal sealed class ConfigurationB : DbMigrationsConfiguration<ModelB>
{
public ConfigurationB()
{
AutomaticMigrationsEnabled = false;
MigrationsDirectory = @"Migrations\ModelB";
}
}
Summary
All in all, you can say that everything is cleanly separated: Contexts, Migration folders in the project and tables in the database.
I would choose such a solution, if there are groups of entities which are part of a bigger topic, but are not related (via foreign keys) to one another.
If the groups of entities do not have anything to do which each other, I would created a separate database for each of them and also access them in different projects, probably with one single context in each project.
Tha is because getColumnDimensionByColumn receives the column index (an integer starting from 0), not a string.
The same goes for setCellValueByColumnAndRow
Which parameter between (data / json / files) should be used,it's actually depends on a request header named ContentType(usually check this through developer tools of your browser),
when the Content-Type is application/x-www-form-urlencoded, code should be:
requests.post(url, data=jsonObj)
when the Content-Type is application/json, your code is supposed to be one of below:
requests.post(url, json=jsonObj)
requests.post(url, data=jsonstr, headers={"Content-Type":"application/json"})
when the Content-Type is multipart/form-data, it's used to upload files, so your code should be:
requests.post(url, files=xxxx)
In my case, I forgot to add my IP address in firewall rules in Azure, basically as I was unable to connect to the database I was getting this error. So specifically for my case, I added my IP address in database firewall rules in Azure and it all worked well. Apart from this, it could be the issue of proxy/internet connection/DB username password/DB connection string etc. OR obviously, you might have pending migrations for which you need to run Update-Database command.
This solution works using Bootstrap v2, however in TBS3 the class INLINE. I haven't figured out what is the equivalent class (if there is one) in TBS3.
This gentleman had a pretty good article of the differences between v2 and v3.
http://mattduchek.com/differences-between-bootstrap-v2-3-and-v3-0/
EDIT - use CSS to target the li
elements to solve your problem as below
{ display: inline-block; }
In my situation I was targeting the UL, instead of the LI
nav ul li { display: inline-block; }
Same as the answer from 'Richie' but a bit more concise.
Query for user constraints only
SELECT column_name FROM all_cons_columns WHERE constraint_name = (
SELECT constraint_name FROM user_constraints
WHERE UPPER(table_name) = UPPER('tableName') AND CONSTRAINT_TYPE = 'P'
);
Query for all constraints
SELECT column_name FROM all_cons_columns WHERE constraint_name = (
SELECT constraint_name FROM all_constraints
WHERE UPPER(table_name) = UPPER('tableName') AND CONSTRAINT_TYPE = 'P'
);
You can use the code from this question: How can I save a screenshot directly to a file in Windows?
Just change WIN32_API.GetDesktopWindow()
to the Handle property of the window you want to capture.
There are some wonderful answers on here to this questions that get into all sorts of great detail about interfaces and loosely coupling code, inversion of control and so on. There are some fairly heady discussions, so I'd like to take the opportunity to break things down a bit for understanding why an interface is useful.
When I first started getting exposed to interfaces, I too was confused about their relevance. I didn't understand why you needed them. If we're using a language like Java or C#, we already have inheritance and I viewed interfaces as a weaker form of inheritance and thought, "why bother?" In a sense I was right, you can think of interfaces as sort of a weak form of inheritance, but beyond that I finally understood their use as a language construct by thinking of them as a means of classifying common traits or behaviors that were exhibited by potentially many non-related classes of objects.
For example -- say you have a SIM game and have the following classes:
class HouseFly inherits Insect {
void FlyAroundYourHead(){}
void LandOnThings(){}
}
class Telemarketer inherits Person {
void CallDuringDinner(){}
void ContinueTalkingWhenYouSayNo(){}
}
Clearly, these two objects have nothing in common in terms of direct inheritance. But, you could say they are both annoying.
Let's say our game needs to have some sort of random thing that annoys the game player when they eat dinner. This could be a HouseFly
or a Telemarketer
or both -- but how do you allow for both with a single function? And how do you ask each different type of object to "do their annoying thing" in the same way?
The key to realize is that both a Telemarketer
and HouseFly
share a common loosely interpreted behavior even though they are nothing alike in terms of modeling them. So, let's make an interface that both can implement:
interface IPest {
void BeAnnoying();
}
class HouseFly inherits Insect implements IPest {
void FlyAroundYourHead(){}
void LandOnThings(){}
void BeAnnoying() {
FlyAroundYourHead();
LandOnThings();
}
}
class Telemarketer inherits Person implements IPest {
void CallDuringDinner(){}
void ContinueTalkingWhenYouSayNo(){}
void BeAnnoying() {
CallDuringDinner();
ContinueTalkingWhenYouSayNo();
}
}
We now have two classes that can each be annoying in their own way. And they do not need to derive from the same base class and share common inherent characteristics -- they simply need to satisfy the contract of IPest
-- that contract is simple. You just have to BeAnnoying
. In this regard, we can model the following:
class DiningRoom {
DiningRoom(Person[] diningPeople, IPest[] pests) { ... }
void ServeDinner() {
when diningPeople are eating,
foreach pest in pests
pest.BeAnnoying();
}
}
Here we have a dining room that accepts a number of diners and a number of pests -- note the use of the interface. This means that in our little world, a member of the pests
array could actually be a Telemarketer
object or a HouseFly
object.
The ServeDinner
method is called when dinner is served and our people in the dining room are supposed to eat. In our little game, that's when our pests do their work -- each pest is instructed to be annoying by way of the IPest
interface. In this way, we can easily have both Telemarketers
and HouseFlys
be annoying in each of their own ways -- we care only that we have something in the DiningRoom
object that is a pest, we don't really care what it is and they could have nothing in common with other.
This very contrived pseudo-code example (that dragged on a lot longer than I anticipated) is simply meant to illustrate the kind of thing that finally turned the light on for me in terms of when we might use an interface. I apologize in advance for the silliness of the example, but hope that it helps in your understanding. And, to be sure, the other posted answers you've received here really cover the gamut of the use of interfaces today in design patterns and development methodologies.
I agree. Once it is uploaded to somewhere the user's browser can access then it is pretty easy to get the size. As you need to wait for the image to load you'll want to hook into the onload
event for img
.
var width, height;
var img = document.createElement("img");
img.onload = function() {
// `naturalWidth`/`naturalHeight` aren't supported on <IE9. Fallback to normal width/height
// The natural size is the actual image size regardless of rendering.
// The 'normal' width/height are for the **rendered** size.
width = img.naturalWidth || img.width;
height = img.naturalHeight || img.height;
// Do something with the width and height
}
// Setting the source makes it start downloading and eventually call `onload`
img.src = "http://your.website.com/userUploadedImage.jpg";
Based on this question, the answer will not work perfectly for ie and opera when there is new line in the textarea. The answer explain how to adjust the selectionStart, selectionEnd before calling setSelectionRange.
I have try the adjustOffset from the other question with the solution proposed by @AVProgrammer and it work.
function adjustOffset(el, offset) {
/* From https://stackoverflow.com/a/8928945/611741 */
var val = el.value, newOffset = offset;
if (val.indexOf("\r\n") > -1) {
var matches = val.replace(/\r\n/g, "\n").slice(0, offset).match(/\n/g);
newOffset += matches ? matches.length : 0;
}
return newOffset;
}
$.fn.setCursorPosition = function(position){
/* From https://stackoverflow.com/a/7180862/611741 */
if(this.lengh == 0) return this;
return $(this).setSelection(position, position);
}
$.fn.setSelection = function(selectionStart, selectionEnd) {
/* From https://stackoverflow.com/a/7180862/611741
modified to fit https://stackoverflow.com/a/8928945/611741 */
if(this.lengh == 0) return this;
input = this[0];
if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
} else if (input.setSelectionRange) {
input.focus();
selectionStart = adjustOffset(input, selectionStart);
selectionEnd = adjustOffset(input, selectionEnd);
input.setSelectionRange(selectionStart, selectionEnd);
}
return this;
}
$.fn.focusEnd = function(){
/* From https://stackoverflow.com/a/7180862/611741 */
this.setCursorPosition(this.val().length);
}
below is an generic example
//base class
class A {
// The virtual method
protected virtualStuff1?():void;
public Stuff2(){
//Calling overridden child method by parent if implemented
this.virtualStuff1 && this.virtualStuff1();
alert("Baseclass Stuff2");
}
}
//class B implementing virtual method
class B extends A{
// overriding virtual method
public virtualStuff1()
{
alert("Class B virtualStuff1");
}
}
//Class C not implementing virtual method
class C extends A{
}
var b1 = new B();
var c1= new C();
b1.Stuff2();
b1.virtualStuff1();
c1.Stuff2();
The best way to decide questions like this to benchmark them:
use strict;
use warnings;
use Benchmark qw(:all);
our @input_array = (0..1000);
my $a = sub {
my @array = @{[ @input_array ]};
my $index = 0;
foreach my $element (@array) {
die unless $index == $element;
$index++;
}
};
my $b = sub {
my @array = @{[ @input_array ]};
my $index = 0;
while (defined(my $element = shift @array)) {
die unless $index == $element;
$index++;
}
};
my $c = sub {
my @array = @{[ @input_array ]};
my $index = 0;
while (scalar(@array) !=0) {
my $element = shift(@array);
die unless $index == $element;
$index++;
}
};
my $d = sub {
my @array = @{[ @input_array ]};
foreach my $index (0.. $#array) {
my $element = $array[$index];
die unless $index == $element;
}
};
my $e = sub {
my @array = @{[ @input_array ]};
for (my $index = 0; $index <= $#array; $index++) {
my $element = $array[$index];
die unless $index == $element;
}
};
my $f = sub {
my @array = @{[ @input_array ]};
while (my ($index, $element) = each @array) {
die unless $index == $element;
}
};
my $count;
timethese($count, {
'1' => $a,
'2' => $b,
'3' => $c,
'4' => $d,
'5' => $e,
'6' => $f,
});
And running this on perl 5, version 24, subversion 1 (v5.24.1) built for x86_64-linux-gnu-thread-multi
I get:
Benchmark: running 1, 2, 3, 4, 5, 6 for at least 3 CPU seconds...
1: 3 wallclock secs ( 3.16 usr + 0.00 sys = 3.16 CPU) @ 12560.13/s (n=39690)
2: 3 wallclock secs ( 3.18 usr + 0.00 sys = 3.18 CPU) @ 7828.30/s (n=24894)
3: 3 wallclock secs ( 3.23 usr + 0.00 sys = 3.23 CPU) @ 6763.47/s (n=21846)
4: 4 wallclock secs ( 3.15 usr + 0.00 sys = 3.15 CPU) @ 9596.83/s (n=30230)
5: 4 wallclock secs ( 3.20 usr + 0.00 sys = 3.20 CPU) @ 6826.88/s (n=21846)
6: 3 wallclock secs ( 3.12 usr + 0.00 sys = 3.12 CPU) @ 5653.53/s (n=17639)
So the 'foreach (@Array)' is about twice as fast as the others. All the others are very similar.
@ikegami also points out that there are quite a few differences in these implimentations other than speed.
In first scenario I supposed that your table have IDENTITY column
CREATE TRIGGER [dbo].[insupddel_yourTable] ON [yourTable]
FOR INSERT, UPDATE, DELETE
AS
IF @@ROWCOUNT = 0 return
SET NOCOUNT ON;
DECLARE @action nvarchar(10)
SELECT @action = CASE WHEN COUNT(i.Id) > COUNT(d.Id) THEN 'inserted'
WHEN COUNT(i.Id) < COUNT(d.Id) THEN 'deleted' ELSE 'updated' END
FROM inserted i FULL JOIN deleted d ON i.Id = d.Id
In second scenario don't need to use IDENTITTY column
CREATE TRIGGER [dbo].[insupddel_yourTable] ON [yourTable]
FOR INSERT, UPDATE, DELETE
AS
IF @@ROWCOUNT = 0 return
SET NOCOUNT ON;
DECLARE @action nvarchar(10),
@insCount int = (SELECT COUNT(*) FROM inserted),
@delCount int = (SELECT COUNT(*) FROM deleted)
SELECT @action = CASE WHEN @insCount > @delCount THEN 'inserted'
WHEN @insCount < @delCount THEN 'deleted' ELSE 'updated' END
The reason it is showing this message because it is unable to find Linux containers as running. So, make sure you switch from windows to linux containers before running it.
If you have multiply rows to delete and you don't want to alter the structure of your tables you can use cursor. 1-You first need to select rows to delete(in a cursor) 2-Then for each row in the cursor you delete the referencing rows and after that delete the row him self.
Ex:
--id is primary key of MainTable
declare @id int
set @id = 1
declare theMain cursor for select FK from MainTable where MainID = @id
declare @fk_Id int
open theMain
fetch next from theMain into @fk_Id
while @@fetch_status=0
begin
--fkid is the foreign key
--Must delete from Main Table first then child.
delete from MainTable where fkid = @fk_Id
delete from ReferencingTable where fkid = @fk_Id
fetch next from theMain into @fk_Id
end
close theMain
deallocate theMain
hope is useful
To add search button on navigation bar use this code:
UIBarButtonItem *searchButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(toggleSearch:)];
self.navigationController.navigationBar.topItem.rightBarButtonItem = searchButton;
and implement following method:
- (IBAction)toggleSearch:(id)sender
{
// do something or handle Search Button Action.
}
I had this same issue but my resolution was different because this didn't completely work.
I found this on a GitHub forum - copy and paste this into your terminal. You don't have to change your password; it can be the exact same.
ALTER USER 'root'@'localhost' IDENTIFIED BY 'password' PASSWORD EXPIRE NEVER;
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '{NewPassword}';
<?php
// Script to test if the CURL extension is installed on this server
// Define function to test
function _is_curl_installed() {
if (in_array ('curl', get_loaded_extensions())) {
return true;
}
else {
return false;
}
}
// Ouput text to user based on test
if (_is_curl_installed()) {
echo "cURL is <span style=\"color:blue\">installed</span> on this server";
} else {
echo "cURL is NOT <span style=\"color:red\">installed</span> on this server";
}
?>
or a simple one -
<?
phpinfo();
?>
Just search for curl
For UBUNTU you can try the following command to check mysql version :
mysql --version
Quicksort is in place. You need very little extra memory. Which is extremely important.
Good choice of median makes it even more efficient but even a bad choice of median quarantees Theta(nlogn).
I do just like below, after you set your column AsEnumarable you can sort, order or how you want.
_dataTable.AsEnumerable().Select(p => p.Field<string>("ColumnName")).ToList();
COUNTIF
function can count cell which specific condition
where as COUNTA
will count all cell which contain any value
Example: Function in A7
: =COUNTA(A1:A6)
Range:
A1| a
A2| b
A3| banana
A4| 42
A5|
A6|
A7| 4 (result)
For those who want to do this in Node.js (running scripts on the server-side) another option is to use require
and module.exports
. Here is a short example on how to create a module and export it for use elsewhere:
file1.js
const print = (string) => {
console.log(string);
};
exports.print = print;
file2.js
const file1 = require('./file1');
function printOne() {
file1.print("one");
};
In 2020
check before use
You can use computedStyleMap()
The answer is valid but sometimes you need to check what unit it returns, you can get that without any slice()
or substring()
string.
var element = document.querySelector('.js-header-rep');
element.computedStyleMap().get('padding-left');
var element = document.querySelector('.jsCSS');_x000D_
var con = element.computedStyleMap().get('padding-left');_x000D_
console.log(con);
_x000D_
.jsCSS {_x000D_
width: 10rem;_x000D_
height: 10rem;_x000D_
background-color: skyblue;_x000D_
padding-left: 10px;_x000D_
}
_x000D_
<div class="jsCSS"></div>
_x000D_
I'm using a simplyfied version (just using position relative) based on @SimonEast answer:
li:before {
content: "\e080";
font-family: 'Glyphicons Halflings';
font-size: 9px;
position: relative;
margin-right: 10px;
top: 3px;
color: #ccc;
}
I've been using:
@media only screen and (min-width: 768px) {
/* tablets and desktop */
}
@media only screen and (max-width: 767px) {
/* phones */
}
@media only screen and (max-width: 767px) and (orientation: portrait) {
/* portrait phones */
}
It keeps things relatively simple and allows you to do something a bit different for phones in portrait mode (a lot of the time I find myself having to change various elements for them).
Assuming you are using Eclipse, on a MAC you can:
Eclipse.app
Eclipse -> Preferences
Java -> Installed JREs
Add...
buttonMacOS X VM
as the JRE type. Press Next./Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home
JDK 1.7
. Click Finish.File -> New -> Java Project
.Use default JRE (currently JDK 1.7)
Hope this helps
Here is an alternative method for doing multiple args. I use it when the arguments are too long for a one liner.
$app = 'C:\Program Files\MSBuild\test.exe'
$arg1 = '/genmsi'
$arg2 = '/f'
$arg3 = '$MySourceDirectory\src\Deployment\Installations.xml'
& $app $arg1 $arg2 $arg3
If You are a newbie then you can take reference from my code .. what i did was to put on a check so that i could only get the Alphabets and white spaces! You can Repeat the for loop after the second if statement to validate the string again
bool check = false;
Console.WriteLine("Please Enter the Name");
name=Console.ReadLine();
for (int i = 0; i < name.Length; i++)
{
if (name[i]>='a' && name[i]<='z' || name[i]==' ')
{
check = true;
}
else
{
check = false;
break;
}
}
if (check==false)
{
Console.WriteLine("Enter Valid Value");
name = Console.ReadLine();
}
you also can use "eval", and pass the method as a string argument, and then simply eval it in the other method.
Actually there is. There is a static method valueOf in the java.sql.Date
object which does exactly that. So we have
java.util.Date date = java.sql.Date.valueOf(localDate);
and that's it. No explicit setting of time zones because the local time zone is taken implicitly.
From docs:
The provided LocalDate is interpreted as the local date in the local time zone.
The java.sql.Date
subclasses java.util.Date
so the result is a java.util.Date
also.
And for the reverse operation there is a toLocalDate method in the java.sql.Date class. So we have:
LocalDate ld = new java.sql.Date(date.getTime()).toLocalDate();
I think its better you read data of text file in DataSet
Try out SqlBulkCopy - Bulk Insert into SQL from C# App
// connect to SQL
using (SqlConnection connection = new SqlConnection(connString))
{
// make sure to enable triggers
// more on triggers in next post
SqlBulkCopy bulkCopy = new SqlBulkCopy(
connection,
SqlBulkCopyOptions.TableLock |
SqlBulkCopyOptions.FireTriggers |
SqlBulkCopyOptions.UseInternalTransaction,
null
);
// set the destination table name
bulkCopy.DestinationTableName = this.tableName;
connection.Open();
// write the data in the "dataTable"
bulkCopy.WriteToServer(dataTable);
connection.Close();
}
// reset
this.dataTable.Clear();
or
after doing step 1 at the top
you can check this article for detail : Bulk Insertion of Data Using C# DataTable and SQL server OpenXML function
But its not tested with 2 million record, it will do but consume memory on machine as you have to load 2 million record and insert it.
After many hours trying to build cert files to get my Java 6 installation working with the new twitter cert's, I finally stumbled onto an incredibly simple solution buried in a comment in one of the message boards. Just copy the cacerts file from a Java 7 installation and overwrite the one in your Java 6 installation. Probably best to make a backup of the cacerts file first, but then you just copy the new one in and BOOM! it just works.
Note that I actually copied a Windows cacerts file onto a Linux installation and it worked just fine.
The file is located in jre/lib/security/cacerts
in both the old and new Java jdk installations.
Hope this saves someone else hours of aggravation.
Map<Integer, Point2D> hm = new HashMap<Integer, Point2D>();
I've covered this in a pet project.. use what you want.
Note that the ListEx implements the IDataReader interface.
people = new ListExCommand(command)
.Map(p=> new ContactPerson()
{
Age = p.GetInt32(p.GetOrdinal("Age")),
FirstName = p.GetString(p.GetOrdinal("FirstName")),
IdNumber = p.GetInt64(p.GetOrdinal("IdNumber")),
Surname = p.GetString(p.GetOrdinal("Surname")),
Email = "[email protected]"
})
.ToListEx()
.Where("FirstName", "Peter");
Or use object mapping like in the following example.
people = new ListExAutoMap(personList)
.Map(p => new ContactPerson()
{
Age = p.Age,
FirstName = p.FirstName,
IdNumber = p.IdNumber,
Surname = p.Surname,
Email = "[email protected]"
})
.ToListEx()
.Where(contactPerson => contactPerson.FirstName == "Zack");
Have a look at http://caprisoft.codeplex.com
Since my related question was removed by a righteous hand after I had killed the whole day searching how to beat the "macro not found or disabled" error, posting here the only syntax that worked for me (application.run didn't, no matter what I tried)
Set objExcel = CreateObject("Excel.Application")
' Didn't run this way from the Modules
'objExcel.Application.Run "c:\app\Book1.xlsm!Sub1"
' Didn't run this way either from the Sheet
'objExcel.Application.Run "c:\app\Book1.xlsm!Sheet1.Sub1"
' Nor did it run from a named Sheet
'objExcel.Application.Run "c:\app\Book1.xlsm!Named_Sheet.Sub1"
' Only ran like this (from the Module1)
Set objWorkbook = objExcel.Workbooks.Open("c:\app\Book1.xlsm")
objExcel.Run "Sub1"
Excel 2010, Win 7
Seems the answer(s) to this question are outdated with the release of Java 8.
public enum AccessLevel {
PRIVATE("private", 0),
PUBLIC("public", 1),
DEFAULT("default", 2);
AccessLevel(final String name, final int value) {
this.name = name;
this.value = value;
}
private final String name;
private final int value;
public String getName() {
return name;
}
public int getValue() {
return value;
}
static final Map<String, AccessLevel> names = Arrays.stream(AccessLevel.values())
.collect(Collectors.toMap(AccessLevel::getName, Function.identity()));
static final Map<Integer, AccessLevel> values = Arrays.stream(AccessLevel.values())
.collect(Collectors.toMap(AccessLevel::getValue, Function.identity()));
public static AccessLevel fromName(final String name) {
return names.get(name);
}
public static AccessLevel fromValue(final int value) {
return values.get(value);
}
}
Assuming you’ve literally got two date objects, you can subtract one from the other and query the resulting timedelta
object for the number of days:
>>> from datetime import date
>>> a = date(2011,11,24)
>>> b = date(2011,11,17)
>>> a-b
datetime.timedelta(7)
>>> (a-b).days
7
And it works with datetimes too — I think it rounds down to the nearest day:
>>> from datetime import datetime
>>> a = datetime(2011,11,24,0,0,0)
>>> b = datetime(2011,11,17,23,59,59)
>>> a-b
datetime.timedelta(6, 1)
>>> (a-b).days
6
as a beginner, i import acm packages, and in this package, run() starts executing of a thread, init() initialize the Java Applet.
This worked for me best for all navigation changes including hash navigation
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this._sub = this.route.fragment.subscribe((hash: string) => {
if (hash) {
const cmp = document.getElementById(hash);
if (cmp) {
cmp.scrollIntoView();
}
} else {
window.scrollTo(0, 0);
}
});
}
If after the installation curl-dev luarocks does not see the headers:
find /usr -name 'curl.h'
Example: /usr/include/x86_64-linux-gnu/curl/curl.h
luarocks install lua-cURL CURL_INCDIR=/usr/include/x86_64-linux-gnu/
Adding to Bartek Maciejiczek's answer, this is how it looks with Craco:
const ModuleScopePlugin = require("react-dev-utils/ModuleScopePlugin");
const path = require("path");
module.exports = {
webpack: {
configure: webpackConfig => {
webpackConfig.resolve.plugins.forEach(plugin => {
if (plugin instanceof ModuleScopePlugin) {
plugin.allowedFiles.add(path.resolve("./config.json"));
}
});
return webpackConfig;
}
}
};
Both join()
and concat()
way could solve the problem. However, there is one warning I have to mention: Reset the index before you join()
or concat()
if you trying to deal with some data frame by selecting some rows from another DataFrame.
One example below shows some interesting behavior of join and concat:
dat1 = pd.DataFrame({'dat1': range(4)})
dat2 = pd.DataFrame({'dat2': range(4,8)})
dat1.index = [1,3,5,7]
dat2.index = [2,4,6,8]
# way1 join 2 DataFrames
print(dat1.join(dat2))
# output
dat1 dat2
1 0 NaN
3 1 NaN
5 2 NaN
7 3 NaN
# way2 concat 2 DataFrames
print(pd.concat([dat1,dat2],axis=1))
#output
dat1 dat2
1 0.0 NaN
2 NaN 4.0
3 1.0 NaN
4 NaN 5.0
5 2.0 NaN
6 NaN 6.0
7 3.0 NaN
8 NaN 7.0
#reset index
dat1 = dat1.reset_index(drop=True)
dat2 = dat2.reset_index(drop=True)
#both 2 ways to get the same result
print(dat1.join(dat2))
dat1 dat2
0 0 4
1 1 5
2 2 6
3 3 7
print(pd.concat([dat1,dat2],axis=1))
dat1 dat2
0 0 4
1 1 5
2 2 6
3 3 7
input[type="button"]:disabled,
input[type="submit"]:disabled,
input[type="reset"]:disabled,
{
// apply css here what u like it will definitely work...
}
Based on Jakub's answer you can configure the following git aliases for convenience:
accept-ours = "!f() { git checkout --ours -- \"${@:-.}\"; git add -u \"${@:-.}\"; }; f"
accept-theirs = "!f() { git checkout --theirs -- \"${@:-.}\"; git add -u \"${@:-.}\"; }; f"
They optionally take one or several paths of files to resolve and default to resolving everything under the current directory if none are given.
Add them to the [alias]
section of your ~/.gitconfig
or run
git config --global alias.accept-ours '!f() { git checkout --ours -- "${@:-.}"; git add -u "${@:-.}"; }; f'
git config --global alias.accept-theirs '!f() { git checkout --theirs -- "${@:-.}"; git add -u "${@:-.}"; }; f'
Try the below:
pod deintegrate
pod install
Or, One-Liner:
pod deintegrate; pod install
Necromancing:
It's relativiely simple to emulate a COUNT DISTINCT over PARTITION BY with MAX via DENSE_RANK:
;WITH baseTable AS
(
SELECT 'RM1' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM1' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM2' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM2' AS RM, 'ADR2' AS ADR
UNION ALL SELECT 'RM2' AS RM, 'ADR2' AS ADR
UNION ALL SELECT 'RM2' AS RM, 'ADR3' AS ADR
UNION ALL SELECT 'RM3' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM2' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM3' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM3' AS RM, 'ADR2' AS ADR
)
,CTE AS
(
SELECT RM, ADR, DENSE_RANK() OVER(PARTITION BY RM ORDER BY ADR) AS dr
FROM baseTable
)
SELECT
RM
,ADR
,COUNT(CTE.ADR) OVER (PARTITION BY CTE.RM ORDER BY ADR) AS cnt1
,COUNT(CTE.ADR) OVER (PARTITION BY CTE.RM) AS cnt2
-- Not supported
--,COUNT(DISTINCT CTE.ADR) OVER (PARTITION BY CTE.RM ORDER BY CTE.ADR) AS cntDist
,MAX(CTE.dr) OVER (PARTITION BY CTE.RM ORDER BY CTE.RM) AS cntDistEmu
FROM CTE
Note:
This assumes the fields in question are NON-nullable fields.
If there is one or more NULL-entries in the fields, you need to subtract 1.
You should check it against null
.
If you want to check if object x is null or not, you can do:
if(x != null)
But if it is not null, it can have properties which are null or empty. You will check those explicitly:
if(x.getProperty() != null)
For "empty" check, it depends on what type is involved. For a Java String
, you usually do:
if(str != null && !str.isEmpty())
As you haven't mentioned about any specific problem with this, difficult to tell.
You can use textContent attribute to retrieve data from a label.
<script>
var datas = document.getElementById("excel-data-div").textContent;
</script>
<label id="excel-data-div" style="display: none;">
Sample text
</label>
This script will add a div that covers the entire window as the page loads. It will show a CSS-only loading spinner automatically. It will wait until the window (not the document) finishes loading, then it will wait an optional extra few seconds.
CSS loader code from https://projects.lukehaas.me/css-loaders
_x000D_
$('body').append('<div style="" id="loadingDiv"><div class="loader">Loading...</div></div>');_x000D_
$(window).on('load', function(){_x000D_
setTimeout(removeLoader, 2000); //wait for page load PLUS two seconds._x000D_
});_x000D_
function removeLoader(){_x000D_
$( "#loadingDiv" ).fadeOut(500, function() {_x000D_
// fadeOut complete. Remove the loading div_x000D_
$( "#loadingDiv" ).remove(); //makes page more lightweight _x000D_
}); _x000D_
}
_x000D_
.loader,_x000D_
.loader:after {_x000D_
border-radius: 50%;_x000D_
width: 10em;_x000D_
height: 10em;_x000D_
}_x000D_
.loader { _x000D_
margin: 60px auto;_x000D_
font-size: 10px;_x000D_
position: relative;_x000D_
text-indent: -9999em;_x000D_
border-top: 1.1em solid rgba(255, 255, 255, 0.2);_x000D_
border-right: 1.1em solid rgba(255, 255, 255, 0.2);_x000D_
border-bottom: 1.1em solid rgba(255, 255, 255, 0.2);_x000D_
border-left: 1.1em solid #ffffff;_x000D_
-webkit-transform: translateZ(0);_x000D_
-ms-transform: translateZ(0);_x000D_
transform: translateZ(0);_x000D_
-webkit-animation: load8 1.1s infinite linear;_x000D_
animation: load8 1.1s infinite linear;_x000D_
}_x000D_
@-webkit-keyframes load8 {_x000D_
0% {_x000D_
-webkit-transform: rotate(0deg);_x000D_
transform: rotate(0deg);_x000D_
}_x000D_
100% {_x000D_
-webkit-transform: rotate(360deg);_x000D_
transform: rotate(360deg);_x000D_
}_x000D_
}_x000D_
@keyframes load8 {_x000D_
0% {_x000D_
-webkit-transform: rotate(0deg);_x000D_
transform: rotate(0deg);_x000D_
}_x000D_
100% {_x000D_
-webkit-transform: rotate(360deg);_x000D_
transform: rotate(360deg);_x000D_
}_x000D_
}_x000D_
#loadingDiv {_x000D_
position:absolute;;_x000D_
top:0;_x000D_
left:0;_x000D_
width:100%;_x000D_
height:100%;_x000D_
background-color:#000;_x000D_
}
_x000D_
This script will add a div that covers the entire window as the page loads. It will show a CSS-only loading spinner automatically. It will wait until the window (not the document) finishes loading._x000D_
_x000D_
<ul>_x000D_
<li>Works with jQuery 3, which has a new window load event</li>_x000D_
<li>No image needed but it's easy to add one</li>_x000D_
<li>Change the delay for branding or instructions</li>_x000D_
<li>Only dependency is jQuery.</li>_x000D_
</ul>_x000D_
_x000D_
Place the script below at the bottom of the body._x000D_
_x000D_
CSS loader code from https://projects.lukehaas.me/css-loaders_x000D_
_x000D_
<!-- Place the script below at the bottom of the body -->_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
Very simple:
Use COUNT_BIG(*) AS NumStreams
echo
produces a trailing newline character which is hashed too. Try:
/bin/echo -n foobar | sha256sum
Just write :
$(document).ready( function () {
$('#example').dataTable( {
"lengthChange": false
} );
} );
Though this question has an answer, I resolved it differently when I had the same issue. I had this issue when I copied folders with the option Create Folder references
; then the above solution of adding the folder to the build_path worked.
But when the folder was added using the Create groups for any added folder
option, the headers were picked up automatically.
If you are really about to work on multi-gigabyte text files then do not use PowerShell. Even if you find a way to read it faster processing of huge amount of lines will be slow in PowerShell anyway and you cannot avoid this. Even simple loops are expensive, say for 10 million iterations (quite real in your case) we have:
# "empty" loop: takes 10 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) {} }
# "simple" job, just output: takes 20 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) { $i } }
# "more real job": 107 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) { $i.ToString() -match '1' } }
UPDATE: If you are still not scared then try to use the .NET reader:
$reader = [System.IO.File]::OpenText("my.log")
try {
for() {
$line = $reader.ReadLine()
if ($line -eq $null) { break }
# process the line
$line
}
}
finally {
$reader.Close()
}
UPDATE 2
There are comments about possibly better / shorter code. There is nothing wrong with the original code with for
and it is not pseudo-code. But the shorter (shortest?) variant of the reading loop is
$reader = [System.IO.File]::OpenText("my.log")
while($null -ne ($line = $reader.ReadLine())) {
$line
}
Since you are the only user:
git reset --hard HEAD@{1}
git push -f
git reset --hard HEAD@{1}
( basically, go back one commit, force push to the repo, then go back again - remove the last step if you don't care about the commit )
Without doing any changes to your local repo, you can also do something like:
git push -f origin <sha_of_previous_commit>:master
Generally, in published repos, it is safer to do git revert
and then git push
To checkout a branch which does not exist locally but is in the remote repo you could use this command:
git checkout -t -b master origin/master
For you LINQers out there that never use a regular dictionary constructor
myCollection.ToDictionary(x => x.PartNumber, x => x.PartDescription, StringComparer.OrdinalIgnoreCase)
var childNodeArray = document.getElementById('somethingOtherThanid').childNodes;
a = 'have a nice day'
symbol = 'abcdefghijklmnopqrstuvwxyz'
for key in symbol:
print key, a.count(key)
You almost got it. It should be this:
<input type="radio" name="group1" id="r1" value="1" />_x000D_
<label for="r1"> button one</label>
_x000D_
The value in for
should be the id of the element you are labeling.
I had similar troubles in eclipse and the only way to fix it for me was to
Just make sure you configure the web module before applying it as by default it will look for your web files in /WebContent/ and this is not what Maven project structure should be.
EDIT:
Here is a second way in case nothing else helps
org.eclipse.wst.common.project.facet.core.xml
, make backup, and remove the web module entry. Warning: do not use the following command unless you want to lose uncommitted work!
Using git reset
has been explained, but you asked for an explanation of the piped commands as well, so here goes:
git ls-files -z | xargs -0 rm -f
git diff --name-only --diff-filter=D -z | xargs -0 git rm --cached
The command git ls-files
lists all files git knows about. The option -z
imposes a specific format on them, the format expected by xargs -0
, which then invokes rm -f
on them, which means to remove them without checking for your approval.
In other words, "list all files git knows about and remove your local copy".
Then we get to git diff
, which shows changes between different versions of items git knows about. Those can be changes between different trees, differences between local copies and remote copies, and so on.
As used here, it shows the unstaged changes; the files you have changed but haven't committed yet. The option --name-only
means you want the (full) file names only and --diff-filter=D
means you're interested in deleted files only. (Hey, didn't we just delete a bunch of stuff?)
This then gets piped into the xargs -0
we saw before, which invokes git rm --cached
on them, meaning that they get removed from the cache, while the working tree should be left alone — except that you've just removed all files from your working tree. Now they're removed from your index as well.
In other words, all changes, staged or unstaged, are gone, and your working tree is empty. Have a cry, checkout your files fresh from origin or remote, and redo your work. Curse the sadist who wrote these infernal lines; I have no clue whatsoever why anybody would want to do this.
TL;DR: you just hosed everything; start over and use git reset
from now on.
Try use Gson
library to convert objects to Json
Example with servlets :
List<Party> parties = bean.getPartiesByIncidentId(incidentId);
String json = "";
try {
json = new Gson().toJson(parties);
} catch (Exception ex) {
ex.printStackTrace();
}
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
Fixed by adding crossorigin to the script tag.
From: https://code.jquery.com/
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
The integrity and crossorigin attributes are used for Subresource Integrity (SRI) checking. This allows browsers to ensure that resources hosted on third-party servers have not been tampered with. Use of SRI is recommended as a best-practice, whenever libraries are loaded from a third-party source. Read more at srihash.org
herein lies the answer... IIS Settings
IIS-->Default SMTP Virtual Server-->Properties-->Access-->Relay restrictions just add or exclude the IPs you care about, should resolve the issue.
well, this using lodash or vanilla javascript it depends on the situation.
but for just return the array that contains the duplicates it can be achieved by the following, offcourse it was taken from @1983
var result = result1.filter(function (o1) {
return result2.some(function (o2) {
return o1.id === o2.id; // return the ones with equal id
});
});
// if you want to be more clever...
let result = result1.filter(o1 => result2.some(o2 => o1.id === o2.id));
Like this:
<c:forEach var="entry" items="${myMap}">
Key: <c:out value="${entry.key}"/>
Value: <c:out value="${entry.value}"/>
</c:forEach>
While all the proposals for multiple resource sets may work, the problem is that the current logic for the Android Studio Gradle plug-in will not update the resource files after they have changed for nested resource sets. The current implementation attempts to check the resource directories using startsWith(), so a directory structure that is nested (i.e. src/main/res/layout/layouts and src/main/res/layout/layouts_category2) will choose src/main/res/layout/layouts consistently and never actually update the changes. The end result is that you have to rebuild/clean the project each time.
I submitted a patch at https://android-review.googlesource.com/#/c/157971/ to try to help resolve things.
Even though this is an old post, I thought it would be helpful to mention an additional (partial and tangential) solution to this question on top of the very helpful workarounds that are already present in this thread.
At the time of writing (6 January 2021), GitHub has released a feature to upload .mp4
and .mov
files up to 10 MB in size to issues, pull requests and discussion comments (as shared here). This is a direct embed, instead of "linking" it to external URLs as what we usually do. It is already out of public beta. You can attach files by dragging and dropping, selecting or pasting them. A preview of GitHub's new notice can be seen here:
Perhaps, in the future, we can slowly nudge GitHub to eventually extend this native feature to READMEs as well.
Add following at the bottom of your Info.plist
<key>ITSAppUsesNonExemptEncryption</key>
<false/>
Not every browser (e.g. IE 6) has options to remember credentials.
One thing you can do is to (once the user successfully logs in) store the user information via cookie and have a "Remember Me on this machine" option. That way, when the user comes again (even if he's logged off), your web application can retrieve the cookie and get the user information (user ID + Session ID) and allow him/her to carry on working.
Hope this can be suggestive. :-)
you could search with
aptitude search intl
after you can choose the right one, for example
sudo aptitude install php-intl
and finally
sudo service apache2 restart
good Luck!
Cast the operands to floats:
float ans = (float)a / (float)b;
Since you want to pivot multiple columns of data, I would first suggest unpivoting the result
, score
and grade
columns so you don't have multiple columns but you will have multiple rows.
Depending on your version of SQL Server you can use the UNPIVOT function or CROSS APPLY. The syntax to unpivot the data will be similar to:
select ratio, col, value
from GRAND_TOTALS
cross apply
(
select 'result', cast(result as varchar(10)) union all
select 'score', cast(score as varchar(10)) union all
select 'grade', grade
) c(col, value)
See SQL Fiddle with Demo. Once the data has been unpivoted, then you can apply the PIVOT function:
select ratio = col,
[current ratio], [gearing ratio], [performance ratio], total
from
(
select ratio, col, value
from GRAND_TOTALS
cross apply
(
select 'result', cast(result as varchar(10)) union all
select 'score', cast(score as varchar(10)) union all
select 'grade', grade
) c(col, value)
) d
pivot
(
max(value)
for ratio in ([current ratio], [gearing ratio], [performance ratio], total)
) piv;
See SQL Fiddle with Demo. This will give you the result:
| RATIO | CURRENT RATIO | GEARING RATIO | PERFORMANCE RATIO | TOTAL |
|--------|---------------|---------------|-------------------|-----------|
| grade | Good | Good | Satisfactory | Good |
| result | 1.29400 | 0.33840 | 0.04270 | (null) |
| score | 60.00000 | 70.00000 | 50.00000 | 180.00000 |
You can use pd.to_datetime()
to convert to a datetime object. It takes a format parameter, but in your case I don't think you need it.
>>> import pandas as pd
>>> df = pd.DataFrame( {'Symbol':['A','A','A'] ,
'Date':['02/20/2015','01/15/2016','08/21/2015']})
>>> df
Date Symbol
0 02/20/2015 A
1 01/15/2016 A
2 08/21/2015 A
>>> df['Date'] =pd.to_datetime(df.Date)
>>> df.sort('Date') # This now sorts in date order
Date Symbol
0 2015-02-20 A
2 2015-08-21 A
1 2016-01-15 A
For future search, you can change the sort statement:
>>> df.sort_values(by='Date') # This now sorts in date order
Date Symbol
0 2015-02-20 A
2 2015-08-21 A
1 2016-01-15 A
I had to uninstall then re-install the xunit.runner.visualstudio nuget package. I tried this after trying all the above suggestions, so may be it was a mixture of things.
You can use the action 'Fix doc comment'. It doesn't have a default shortcut, but you can assign the Alt+Shift+J shortcut to it in the Keymap, because this shortcut isn't used for anything else.
By default, you can also press Ctrl+Shift+A two times and begin typing Fix doc comment
in order to find the action.
Because the script will get executed first.. When the script will get executed, at that time controls are not getting loaded. So after loading controls you write a script.
It will work.
Grave digging... I like a different approach:
elem = $('form')
elem.on('keyup','input', checkStatus)
elem.on('change', 'select', checkStatus)
checkStatus = (e) =>
elems = $('form').find('input:enabled').not('input[type=hidden]').map(-> $(this).val())
filled = $.grep(elems, (n) -> n)
bool = elems.size() != $(filled).size()
$('input:submit').attr('disabled', bool)
Optional<User>.ifPresent()
takes a Consumer<? super User>
as argument. You're passing it an expression whose type is void. So that doesn't compile.
A Consumer is intended to be implemented as a lambda expression:
Optional<User> user = ...
user.ifPresent(theUser -> doSomethingWithUser(theUser));
Or even simpler, using a method reference:
Optional<User> user = ...
user.ifPresent(this::doSomethingWithUser);
This is basically the same thing as
Optional<User> user = ...
user.ifPresent(new Consumer<User>() {
@Override
public void accept(User theUser) {
doSomethingWithUser(theUser);
}
});
The idea is that the doSomethingWithUser()
method call will only be executed if the user is present. Your code executes the method call directly, and tries to pass its void result to ifPresent()
.
If you want padding between text try LineSpacingExtra="10dp"
<TextView
android:layout_width="match_parent"
android:layout_height="180dp"
android:lineSpacingExtra="10dp"/>
To append to an array, just use the +=
operator.
$Target += $TargetObject
Also, you need to declare $Target = @()
before your loop because otherwise, it will empty the array every loop.
Use jQuery $(document)
function...
$(document).ready(function(){
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x0 = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var x1 = d3.scale.ordinal();
var y = d3.scale.linear()
.range([height, 0]);
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
var xAxis = d3.svg.axis()
.scale(x0)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format(".2s"));
//d3.select('#chart svg')
//d3.select("body").append("svg")
//var svg = d3.select("#chart").append("svg:svg");
var svg = d3.select("#BarChart").append("svg:svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var updateData = function(getData){
d3.selectAll('svg > g > *').remove();
d3.csv(getData, function(error, data) {
if (error) throw error;
var ageNames = d3.keys(data[0]).filter(function(key) { return key !== "State"; });
data.forEach(function(d) {
d.ages = ageNames.map(function(name) { return {name: name, value: +d[name]}; });
});
x0.domain(data.map(function(d) { return d.State; }));
x1.domain(ageNames).rangeRoundBands([0, x0.rangeBand()]);
y.domain([0, d3.max(data, function(d) { return d3.max(d.ages, function(d) { return d.value; }); })]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Population");
var state = svg.selectAll(".state")
.data(data)
.enter().append("g")
.attr("class", "state")
.attr("transform", function(d) { return "translate(" + x0(d.State) + ",0)"; });
state.selectAll("rect")
.data(function(d) { return d.ages; })
.enter().append("rect")
.attr("width", x1.rangeBand())
.attr("x", function(d) { return x1(d.name); })
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); })
.style("fill", function(d) { return color(d.name); });
var legend = svg.selectAll(".legend")
.data(ageNames.slice().reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { return d; });
});
}
updateData('data1.csv');
});