In your example, j+=3
increments by 3.
(Not much else to say here, if it's syntax related I'd suggest Googling first, but I'm new here so I could be wrong.)
Here's an assertion I wrote in a server for a Hibernate/SQL project. An entity bean had two effectively-boolean properties, called isActive and isDefault. Each could have a value of "Y" or "N" or null, which was treated as "N". We want to make sure the browser client is limited to these three values. So, in my setters for these two properties, I added this assertion:
assert new HashSet<String>(Arrays.asList("Y", "N", null)).contains(value) : value;
Notice the following.
This assertion is for the development phase only. If the client sends a bad value, we will catch that early and fix it, long before we reach production. Assertions are for defects that you can catch early.
This assertion is slow and inefficient. That's okay. Assertions are free to be slow. We don't care because they're development-only tools. This won't slow down the production code because assertions will be disabled. (There's some disagreement on this point, which I'll get to later.) This leads to my next point.
This assertion has no side effects. I could have tested my value against an unmodifiable static final Set, but that set would have stayed around in production, where it would never get used.
This assertion exists to verify the proper operation of the client. So by the time we reach production, we will be sure that the client is operating properly, so we can safely turn the assertion off.
Some people ask this: If the assertion isn't needed in production, why not just take them out when you're done? Because you'll still need them when you start working on the next version.
Some people have argued that you should never use assertions, because you can never be sure that all the bugs are gone, so you need to keep them around even in production. And so there's no point in using the assert statement, since the only advantage to asserts is that you can turn them off. Hence, according to this thinking, you should (almost) never use asserts. I disagree. It's certainly true that if a test belongs in production, you should not use an assert. But this test does not belong in production. This one is for catching a bug that's not likely to ever reach production, so it may safely be turned off when you're done.
BTW, I could have written it like this:
assert value == null || value.equals("Y") || value.equals("N") : value;
This is fine for only three values, but if the number of possible values gets bigger, the HashSet version becomes more convenient. I chose the HashSet version to make my point about efficiency.
This simple CTE will give what's needed:
DECLARE @csv varchar(max) = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15';
--append comma to the list for CTE to work correctly
SET @csv = @csv + ',';
--remove double commas (empty entries)
SET @csv = replace(@csv, ',,', ',');
WITH CteCsv AS (
SELECT CHARINDEX(',', @csv) idx, SUBSTRING(@csv, 1, CHARINDEX(',', @csv) - 1) [Value]
UNION ALL
SELECT CHARINDEX(',', @csv, idx + 1), SUBSTRING(@csv, idx + 1, CHARINDEX(',', @csv, idx + 1) - idx - 1) FROM CteCsv
WHERE CHARINDEX(',', @csv, idx + 1) > 0
)
SELECT [Value] FROM CteCsv
I had the same problem and my solution was to add the push notification entitlement from Target -> Capabilities.
Mailutils makes this a piece of cake
echo "Body" | mail.mailutils -M -s "My Subject" -A attachment.pdf [email protected]
-A file
attaches a file-M
enables MIME, so that you can have an attachment and plaintext body.If not yet installed, run
sudo apt install mailutils
If you really want an 'Int only' implementation and don't want to coerce to/from Double
, you'll need to implement it. Here is a trivial implementation; there are faster algorithms but this will work:
func pow (_ base:Int, _ power:UInt) -> Int {
var answer : Int = 1
for _ in 0..<power { answer *= base }
return answer
}
> pow (2, 4)
$R3: Int = 16
> pow (2, 8)
$R4: Int = 256
> pow (3,3)
$R5: Int = 27
In a real implementation you'd probably want some error checking.
You can do something like this
Declare @min int=0, @max int =0 --Initialize variable here which will be use in loop
Declare @Recordid int,@TO nvarchar(30),@Subject nvarchar(250),@Body nvarchar(max) --Initialize variable here which are useful for your
select ROW_NUMBER() OVER(ORDER BY [Recordid] ) AS Rownumber, Recordid, [To], [Subject], [Body], [Flag]
into #temp_Mail_Mstr FROM Mail_Mstr where Flag='1' --select your condition with row number & get into a temp table
set @min = (select MIN(Rownumber) from #temp_Mail_Mstr); --Get minimum row number from temp table
set @max = (select Max(Rownumber) from #temp_Mail_Mstr); --Get maximum row number from temp table
while(@min <= @max)
BEGIN
select @Recordid=Recordid, @To=[To], @Subject=[Subject], @Body=Body from #temp_Mail_Mstr where Rownumber=@min
-- You can use your variables (like @Recordid,@To,@Subject,@Body) here
-- Do your work here
set @min=@min+1 --Increment of current row number
END
height
of your label to the same height
as the multiline textbox.Add the cssClass .alignTop{vertical-align: middle;}
for the label control.
<p>
<asp:Label ID="DescriptionLabel" runat="server" Text="Description: " Width="70px" Height="200px" CssClass="alignTop"></asp:Label>
<asp:Textbox id="DescriptionTextbox" runat="server" Width="400px" Height="200px" TextMode="MultiLine"></asp:Textbox>
<asp:RequiredFieldValidator id="DescriptionRequiredFieldValidator" runat="server" ForeColor="Red"
ControlToValidate="DescriptionTextbox" ErrorMessage="Description is a required field.">
</asp:RequiredFieldValidator>
Decode the string to Unicode. Assuming it's UTF-8-encoded:
str.decode("utf-8")
Call the replace
method and be sure to pass it a Unicode string as its first argument:
str.decode("utf-8").replace(u"\u2022", "*")
Encode back to UTF-8, if needed:
str.decode("utf-8").replace(u"\u2022", "*").encode("utf-8")
(Fortunately, Python 3 puts a stop to this mess. Step 3 should really only be performed just prior to I/O. Also, mind you that calling a string str
shadows the built-in type str
.)
This way I solved my problem. Hope it helps others. In my case I created a class, a field, their getter & setter and then provide the object instead of string.
Use this
public static class EncryptedData {
private String encryptedData;
public String getEncryptedData() {
return encryptedData;
}
public void setEncryptedData(String encryptedData) {
this.encryptedData = encryptedData;
}
}
@PutMapping(value = MY_IP_ADDRESS)
public ResponseEntity<RestResponse> updateMyIpAddress(@RequestBody final EncryptedData encryptedData) {
try {
Path path = Paths.get(PUBLIC_KEY);
byte[] bytes = Files.readAllBytes(path);
PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(base64.decode(bytes));
PrivateKey privateKey = KeyFactory.getInstance(CRYPTO_ALGO_RSA).generatePrivate(ks);
Cipher cipher = Cipher.getInstance(CRYPTO_ALGO_RSA);
cipher.init(Cipher.PRIVATE_KEY, privateKey);
String decryptedData = new String(cipher.doFinal(encryptedData.getEncryptedData().getBytes()));
String[] dataArray = decryptedData.split("|");
Method updateIp = Class.forName("com.cuanet.client.helper").getMethod("methodName", String.class,String.class);
updateIp.invoke(null, dataArray[0], dataArray[1]);
} catch (Exception e) {
LOG.error("Unable to update ip address for encrypted data: "+encryptedData, e);
}
return null;
Instead of this
@PutMapping(value = MY_IP_ADDRESS)
public ResponseEntity<RestResponse> updateMyIpAddress(@RequestBody final EncryptedData encryptedData) {
try {
Path path = Paths.get(PUBLIC_KEY);
byte[] bytes = Files.readAllBytes(path);
PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(base64.decode(bytes));
PrivateKey privateKey = KeyFactory.getInstance(CRYPTO_ALGO_RSA).generatePrivate(ks);
Cipher cipher = Cipher.getInstance(CRYPTO_ALGO_RSA);
cipher.init(Cipher.PRIVATE_KEY, privateKey);
String decryptedData = new String(cipher.doFinal(encryptedData.getBytes()));
String[] dataArray = decryptedData.split("|");
Method updateIp = Class.forName("com.cuanet.client.helper").getMethod("methodName", String.class,String.class);
updateIp.invoke(null, dataArray[0], dataArray[1]);
} catch (Exception e) {
LOG.error("Unable to update ip address for encrypted data: "+encryptedData, e);
}
return null;
}
You can use an array
$something = array(
'key' => 'value',
'key2' => 'value2'
);
or with standard object.
$something = new StdClass();
$something->key = 'value';
$something->key2 = 'value2';
Another approach is to first do a searchType: 'count'
, then and then do a normal search with size
set to results.count
.
The advantage here is it avoids depending on a magic number for UPPER_BOUND
as suggested in this similar SO question, and avoids the extra overhead of building too large of a priority queue that Shay Banon describes here. It also lets you keep your results sorted, unlike scan
.
The biggest disadvantage is that it requires two requests. Depending on your circumstance, this may be acceptable.
jQuery provides an each()
method, not forEach()
. You can break out of each
by returning false
. forEach()
is part of the ECMA-262 standard, and the only way to break out of that that I'm aware of is by throwing an exception.
function recurs(comment) {
try {
comment.comments.forEach(function(elem) {
recurs(elem);
if (...) throw "done";
});
} catch (e) { if (e != "done") throw e; }
}
Ugly, but does the job.
json_decode()
will return an object or array if second value it's true:
$json = '{"countryId":"84","productId":"1","status":"0","opId":"134"}';
$json = json_decode($json, true);
echo $json['countryId'];
echo $json['productId'];
echo $json['status'];
echo $json['opId'];
Web.Config file:
<configuration>
<system.net>
<mailSettings>
<smtp from="[email protected]">
<network host="smtp.gmail.com"
port="587"
userName="[email protected]"
password="yourpassword"
enableSsl="true"/>
</smtp>
</mailSettings>
</system.net>
</configuration>
For handling the event on overing, you can try something like this (it works for me):
In the Html template:
<div (mouseenter)="onHovering($event)" (mouseleave)="onUnovering($event)">
<img src="../../../contents/ctm-icons/alarm.svg" class="centering-me" alt="Alerts" />
</div>
In the angular component:
onHovering(eventObject) {
console.log("AlertsBtnComponent.onHovering:");
var regExp = new RegExp(".svg" + "$");
var srcObj = eventObject.target.offsetParent.children["0"];
if (srcObj.tagName == "IMG") {
srcObj.setAttribute("src", srcObj.getAttribute("src").replace(regExp, "_h.svg"));
}
}
onUnovering(eventObject) {
console.log("AlertsBtnComponent.onUnovering:");
var regExp = new RegExp("_h.svg" + "$");
var srcObj = eventObject.target.offsetParent.children["0"];
if (srcObj.tagName == "IMG") {
srcObj.setAttribute("src", srcObj.getAttribute("src").replace(regExp, ".svg"));
}
}
To populate ComboBox with JSON, you can consider using the: jqwidgets combobox, too.
If you want the time out as well as the date you want Date.toLocaleString()
.
This was direct from my console:
> new Date().toLocaleString()
> "11/10/2016, 11:49:36 AM"
You can then input locale strings and format string to get the precise output you want.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
With Gson, you'd just need to do something like:
List<Video> videos = gson.fromJson(json, new TypeToken<List<Video>>(){}.getType());
You might also need to provide a no-arg constructor on the Video
class you're deserializing to.
Atleast it is not mandatory in Java. According to JLS, it says atmost one default case can be present. Which means no default case is acceptable . It at times also depends on the context that you are using the switch statement. For example in Java, the following switch block does not require default case
private static void switch1(String name) {
switch (name) {
case "Monday":
System.out.println("Monday");
break;
case "Tuesday":
System.out.println("Tuesday");
break;
}
}
But in the following method which expects to return a String, default case comes handy to avoid compilation errors
private static String switch2(String name) {
switch (name) {
case "Monday":
System.out.println("Monday");
return name;
case "Tuesday":
System.out.println("Tuesday");
return name;
default:
return name;
}
}
though you can avoid compilation error for the above method without having default case by just having a return statement at the end, but providing default case makes it more readable.
Several third-party libraries have classes encapsulating the concept of a range, such as Apache commons-lang's Range (and subclasses).
Using classes such as this you could express your constraint similar to:
if (new IntRange(0, 5).contains(orderBean.getFiles().size())
// (though actually Apache's Range is INclusive, so it'd be new Range(1, 4) - meh
with the added bonus that the range object could be defined as a constant value elsewhere in the class.
However, without pulling in other libraries and using their classes, Java's strong syntax means you can't massage the language itself to provide this feature nicely. And (in my own opinion), pulling in a third party library just for this small amount of syntactic sugar isn't worth it.
I know this is an old question, but how about just binding to Command
if using MVVM?
ex:
<CheckBox Content="Case Sensitive" Command="{Binding bSearchCaseSensitive}"/>
For me it triggers on both Check
and Uncheck
.
Use Console.Write instead, so there's no newline written:
Console.Write("What is your name? ");
var name = Console.ReadLine();
ECMA Script 6 Version
If you are in an environment which supports ECMA Script 6's Set
, then you can use Array.prototype.some
and a Set
object, like this
let seen = new Set();
var hasDuplicates = values.some(function(currentObject) {
return seen.size === seen.add(currentObject.name).size;
});
Here, we insert each and every object's name
into the Set
and we check if the size
before and after adding are the same. This works because Set.size
returns a number based on unique data (set only adds entries if the data is unique). If/when you have duplicate names, the size won't increase (because the data won't be unique) which means that we would have already seen the current name and it will return true.
ECMA Script 5 Version
If you don't have Set
support, then you can use a normal JavaScript object itself, like this
var seen = {};
var hasDuplicates = values.some(function(currentObject) {
if (seen.hasOwnProperty(currentObject.name)) {
// Current name is already seen
return true;
}
// Current name is being seen for the first time
return (seen[currentObject.name] = false);
});
The same can be written succinctly, like this
var seen = {};
var hasDuplicates = values.some(function (currentObject) {
return seen.hasOwnProperty(currentObject.name)
|| (seen[currentObject.name] = false);
});
Note: In both the cases, we use Array.prototype.some
because it will short-circuit. The moment it gets a truthy value from the function, it will return true
immediately, it will not process rest of the elements.
You use something like
from flask import send_file
@app.route('/get_image')
def get_image():
if request.args.get('type') == '1':
filename = 'ok.gif'
else:
filename = 'error.gif'
return send_file(filename, mimetype='image/gif')
to send back ok.gif
or error.gif
, depending on the type query parameter. See the documentation for the send_file
function and the request
object for more information.
I've come up with a solution which is similar with RacZo's in the fact that I've also created a subclass of TextView
which handles making the text upper-case.
The difference is that instead of overriding one of the setText()
methods, I've used a similar approach to what the TextView
actually does on API 14+ (which is in my point of view a cleaner solution).
If you look into the source, you'll see the implementation of setAllCaps()
:
public void setAllCaps(boolean allCaps) {
if (allCaps) {
setTransformationMethod(new AllCapsTransformationMethod(getContext()));
} else {
setTransformationMethod(null);
}
}
The AllCapsTransformationMethod
class is not (currently) public, but still, the source is also available. I've simplified that class a bit (removed the setLengthChangesAllowed()
method), so the complete solution is this:
public class UpperCaseTextView extends TextView {
public UpperCaseTextView(Context context) {
super(context);
setTransformationMethod(upperCaseTransformation);
}
public UpperCaseTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setTransformationMethod(upperCaseTransformation);
}
public UpperCaseTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setTransformationMethod(upperCaseTransformation);
}
private final TransformationMethod upperCaseTransformation =
new TransformationMethod() {
private final Locale locale = getResources().getConfiguration().locale;
@Override
public CharSequence getTransformation(CharSequence source, View view) {
return source != null ? source.toString().toUpperCase(locale) : null;
}
@Override
public void onFocusChanged(View view, CharSequence sourceText,
boolean focused, int direction, Rect previouslyFocusedRect) {}
};
}
I suppose you don't want to change get_sublist
function, and just want to use DataFrame's apply
method to do the job. To get the result you want, I've wrote two help functions: get_sublist_list
and unlist
. As the function name suggest, first get the list of sublist, second extract that sublist from that list. Finally, We need to call apply
function to apply those two functions to the df[['col_1','col_2']]
DataFrame subsequently.
import pandas as pd
df = pd.DataFrame({'ID':['1','2','3'], 'col_1': [0,2,3], 'col_2':[1,4,5]})
mylist = ['a','b','c','d','e','f']
def get_sublist(sta,end):
return mylist[sta:end+1]
def get_sublist_list(cols):
return [get_sublist(cols[0],cols[1])]
def unlist(list_of_lists):
return list_of_lists[0]
df['col_3'] = df[['col_1','col_2']].apply(get_sublist_list,axis=1).apply(unlist)
df
If you don't use []
to enclose the get_sublist
function, then the get_sublist_list
function will return a plain list, it'll raise ValueError: could not broadcast input array from shape (3) into shape (2)
, as @Ted Petrou had mentioned.
There are two solutions posted on that page. The one with lower votes I would recommend if possible.
If you are using HTML5 then it is perfectly valid to put a div
inside of a
. As long as the div doesn't also contain some other specific elements like other link tags.
<a href="Music.html">
<div id="music" class="nav">
Music I Like
</div>
</a>
The solution you are confused about actually makes the link as big as its container div. To make it work in your example you just need to add position: relative
to your div. You also have a small syntax error which is that you have given the span a class instead of an id. You also need to put your span inside the link because that is what the user is clicking on. I don't think you need the z-index
at all from that example.
div { position: relative; }
.hyperspan {
position:absolute;
width:100%;
height:100%;
left:0;
top:0;
}
<div id="music" class="nav">Music I Like
<a href="http://www.google.com">
<span class="hyperspan"></span>
</a>
</div>
When you give absolute
positioning to an element it bases its location and size after the first parent it finds that is relatively positioned. If none, then it uses the document. By adding relative
to the parent div you tell the span to only be as big as that.
You could also do
function insertAfter(node1, node2) {
node1.outerHTML += node2.outerHTML;
}
or
function insertAfter2(node1, node2) {
var wrap = document.createElement("div");
wrap.appendChild(node2.cloneNode(true));
var node2Html = wrap.innerHTML;
node1.insertAdjacentHTML('afterend', node2Html);
}
Beside all of the good answers, I guess a great example from How to Think About Algorithms, by Jeff Edmonds can illustrate the concept very well:
EXAMPLE 1.2.1 "The Find-Max Two-Finger Algorithm"
1) Specifications: An input instance consists of a list L(1..n) of elements. The output consists of an index i such that L(i) has maximum value. If there are multiple entries with this same value, then any one of them is returned.
2) Basic Steps: You decide on the two-finger method. Your right finger runs down the list.
3) Measure of Progress: The measure of progress is how far along the list your right finger is.
4) The Loop Invariant: The loop invariant states that your left finger points to one of the largest entries encountered so far by your right finger.
5) Main Steps: Each iteration, you move your right finger down one entry in the list. If your right finger is now pointing at an entry that is larger then the left finger’s entry, then move your left finger to be with your right finger.
6) Make Progress: You make progress because your right finger moves one entry.
7) Maintain Loop Invariant: You know that the loop invariant has been maintained as follows. For each step, the new left finger element is Max(old left finger element, new element). By the loop invariant, this is Max(Max(shorter list), new element). Mathe- matically, this is Max(longer list).
8) Establishing the Loop Invariant: You initially establish the loop invariant by point- ing both fingers to the first element.
9) Exit Condition: You are done when your right finger has finished traversing the list.
10) Ending: In the end, we know the problem is solved as follows. By the exit condi- tion, your right finger has encountered all of the entries. By the loop invariant, your left finger points at the maximum of these. Return this entry.
11) Termination and Running Time: The time required is some constant times the length of the list.
12) Special Cases: Check what happens when there are multiple entries with the same value or when n = 0 or n = 1.
13) Coding and Implementation Details: ...
14) Formal Proof: The correctness of the algorithm follows from the above steps.
This is an easy solution that counts the number of files in a directory containing sub-folders. It may come in handy;
import os
from pathlib import Path
def count_files(rootdir):
'''counts the number of files in each subfolder in a directory'''
for path in pathlib.Path(rootdir).iterdir():
if path.is_dir():
print("There are " + str(len([name for name in os.listdir(path) \
if os.path.isfile(os.path.join(path, name))])) + " files in " + \
str(path.name))
count_files(data_dir) # data_dir is the directory you want files counted.
You should get an output similar to this (with the placeholders changed, of course);
There are {number of files} files in {name of sub-folder1}
There are {number of files} files in {name of sub-folder2}
In your example, the variable a
is just a reference to an instance of a string object. When you say a = "ty"
, you are not actually changing the string object, but rather pointing the reference at an entirely different instance of the string class.
Use the in
keyword.
if 'apples' in d:
if d['apples'] == 20:
print('20 apples')
else:
print('Not 20 apples')
If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get
function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None
instead):
if d.get('apples', 0) == 20:
print('20 apples.')
else:
print('Not 20 apples.')
You are converting cert into BKS Keystore, why aren't you using .cert
directly, from https://developer.android.com/training/articles/security-ssl.html:
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream instream = context.getResources().openRawResource(R.raw.gtux_cert);
Certificate ca;
try {
ca = cf.generateCertificate(instream);
} finally {
caInput.close();
}
KeyStore kStore = KeyStore.getInstance(KeyStore.getDefaultType());
kStore.load(null, null);
kStore.setCertificateEntry("ca", ca);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm(););
tmf.init(kStore);
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
okHttpClient.setSslSocketFactory(context.getSocketFactory());
//add cookie
var panelIdCookie = new HttpCookie("panelIdCookie");
panelIdCookie.Values.Add("panelId", panelId.ToString(CultureInfo.InvariantCulture));
panelIdCookie.Expires = DateTime.Now.AddMonths(2);
Response.Cookies.Add(panelIdCookie);
//read cookie
var httpCookie = Request.Cookies["panelIdCookie"];
if (httpCookie != null)
{
panelId = Convert.ToInt32(httpCookie["panelId"]);
}
In file - \vendor\autoload.php, define your gobals variable as follows, should be in the topmost line.
$global_variable = "Some value";//the global variable
Access that global variable anywhere as :-
$GLOBALS['global_variable'];
Enjoy :)
you can do it like this:
function MyClass() {
this.abc = function() {
alert("abc");
}
}
var myObject = new MyClass();
myObject["abc"]();
Something very similar can be seen on http://goo.gl when you shorten the URL.
There is a readonly input element that gets programmatically focused, with tooltip press CTRL-C to copy.
When you hit that shortcut, the input content effectively gets into the clipboard. Really nice :)
On a mac you have to set keybinding yourself. Simply go to
Sublime --> Preference --> Key Binding - User
and input the following:
{ "keys": ["shift+command+m"], "command": "goto_definition" }
This will enable keybinding of Shift + Command + M
to enable goto definition. You can set the keybinding to anything you would like of course.
The default value of the argument must be a constant expression. It can't be a variable or a function call.
If you need this functionality however:
function foo($foo, $bar = false)
{
if(!$bar)
{
$bar = $foo;
}
}
Assuming $bar
isn't expected to be a boolean of course.
TMTOWTDI. Here are several solutions in order of complexity.
(Short primer on complexity follows):O(n)
or "big o" means worst case scenario where n
means the number of elements in the array, and o(n)
or "little o" means best case scenario. Long discrete math story short, you only really have to worry about the worst case scenario, and make sure it's not n ^ 2
or n!
. It's more a measure of change in computing time as n
increases than it is overall computing time. Wikipedia has a good article about computational aka time complexity.
If experience has taught me anything, it's that spending too much time optimizing your programs' little-o is a distinct waste of time better spent doing something - anything - better.
O(n) / o(1)
complexity:This solution has a best case scenario of 1 comparison - 1 iteration thru the loop, but only provided the matching value is in position 0 of the array. The worst case scenario is it's not in the array, and thus has to iterate over every element of the array.
foreach ($my_array as $sub_array) {
if (@$sub_array['id'] === 152) {
return true;
}
}
return false;
O(n) / o(n)
complexity:This solution must loop thru the entire array no matter where the matching value is, so it's always going to be n
iterations thru the array.
return 0 < count(
array_filter(
$my_array,
function ($a) {
return array_key_exists('id', $a) && $a['id'] == 152;
}
)
);
O(n log n) / o(n log n)
complexity:A hash insertion is where the log n
comes from; n
hash insertions = n * log n
. There's a hash lookup at the end which is another log n
but it's not included because that's just how discrete math works.
$existence_hash = [];
foreach ($my_array as $sub_array) {
$existence_hash[$sub_array['id']] = true;
}
return @$existence_hash['152'];
It has to do with how the public members of the base class are exposed from the derived class.
As litb points out, public inheritance is traditional inheritance that you'll see in most programming languages. That is it models an "IS-A" relationship. Private inheritance, something AFAIK peculiar to C++, is an "IMPLEMENTED IN TERMS OF" relationship. That is you want to use the public interface in the derived class, but don't want the user of the derived class to have access to that interface. Many argue that in this case you should aggregate the base class, that is instead of having the base class as a private base, make in a member of derived in order to reuse base class's functionality.
Breaking Changes to LocalDB: Applies to SQL 2014; take a look over this article and try to use (localdb)\mssqllocaldb
as server name to connect to the LocalDB automatic instance, for example:
<connectionStrings>
<add name="ProductsContext" connectionString="Data Source=(localdb)\mssqllocaldb;
...
The article also mentions the use of 2012 SSMS to connect to the 2014 LocalDB. Which leads me to believe that you might have multiple versions of SQL installed - which leads me to point out this SO answer that suggests changing the default name of your LocalDB "instance" to avoid other version mismatch issues that might arise going forward; mentioned not as source of issue, but to raise awareness of potential clashes that multiple SQL version installed on a single dev machine might lead to ... and something to get in the habit of in order to avoid some.
Another thing worth mentioning - if you've gotten your instance in an unusable state due to tinkering with it to try and fix this problem, then it might be worth starting over - uninstall, reinstall - then try using the mssqllocaldb
value instead of v12.0
and see if that corrects your issue.
The workarounds above (thanks!) don't properly address the problem of getting back the objects provided to the deferred's resolve()
method because jQuery calls the done()
and fail()
callbacks with individual parameters, not an array. That means we have to use the arguments
pseudo-array to get all the resolved/rejected objects returned by the array of deferreds, which is ugly:
$.when.apply($,deferreds).then(function() {
var objects=arguments; // The array of resolved objects as a pseudo-array
...
};
Since we passed in an array of deferreds, it would be nice to get back an array of results. It would also be nice to get back an actual array instead of a pseudo-array so we can use methods like Array.sort()
.
Here is a solution inspired by when.js's when.all()
method that addresses these problems:
// Put somewhere in your scripting environment
if (typeof jQuery.when.all === 'undefined') {
jQuery.when.all = function (deferreds) {
return $.Deferred(function (def) {
$.when.apply(jQuery, deferreds).then(
function () {
def.resolveWith(this, [Array.prototype.slice.call(arguments)]);
},
function () {
def.rejectWith(this, [Array.prototype.slice.call(arguments)]);
});
});
}
}
Now you can simply pass in an array of deferreds/promises and get back an array of resolved/rejected objects in your callback, like so:
$.when.all(deferreds).then(function(objects) {
console.log("Resolved objects:", objects);
});
Per the documentation you posted, and this blog post - there's no difference when declaring the primitive between an unsigned int/long and a signed one. The "new support" is the addition of the static methods in the Integer and Long classes, e.g. Integer.divideUnsigned. If you're not using those methods, your "unsigned" long above 2^63-1 is just a plain old long with a negative value.
From a quick skim, it doesn't look like there's a way to declare integer constants in the range outside of +/- 2^31-1, or +/- 2^63-1 for longs. You would have to manually compute the negative value corresponding to your out-of-range positive value.
You're asking for all the elements of class facetContainerDiv
, of which there is only one (your outer-most div). Why not do
List<WebElement> checks = driver.findElements(By.class("facetCheck"));
// click the 3rd checkbox
checks.get(2).click();
This regex can help you to check your email-address according to all the criteria which gmail.com used.
var re = /^\w+([-+.'][^\s]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
var emailFormat = re.test($("#email").val()); // This return result in Boolean type
if (emailFormat) {}
If you are using Android Studio on a Mac, you may need to provide the full path to the adb
executable. To find this path, open:
Android Studio > Tools > Android > SDK Manager
Copy the path to the SDK location. The adb
executable will be within a platform-tools
directory. For me, this was the path:
~/Library/Android/sdk/platform-tools/adb
Now you can run this command:
~/Library/Android/sdk/platform-tools/adb shell input text 'thetextyouwanttopaste'
Some of the brokerage firms like TDAmeritrade have APIs you can use to get streaming data from their servers:
http://www.tdameritrade.com/tradingtools/partnertools/api_dev.html
If you are working with Web application you can try this.
StringBuilder sb = new StringBuilder();
sb.AppendLine("Some text with line one");
sb.AppendLine("Some mpre text with line two");
MyLabel.Text = sb.ToString().Replace(Environment.NewLine, "<br />")
Try this function instead.
string source = "My name is Marco and I'm from Italy";
string[] stringSeparators = new string[] {"is Marco and"};
var result = source.Split(stringSeparators, StringSplitOptions.None);
string
is short name of System.String
.
String
or System.String
is name of string in CTS(Common Type System)
.
My two cents:
I suggest to learn C first, because :
You would have to watch the DOM node changes. There is an API called MutationObserver
, but it looks like the support for it is very limited. This SO answer has a link to the status of the API, but it seems like there is no support for it in IE or Opera so far.
One way you could get around this problem is to have the part of the code that modifies the data-select-content-val
attribute dispatch an event that you can listen to.
For example, see: http://jsbin.com/arucuc/3/edit on how to tie it together.
The code here is
$(function() {
// Here you register for the event and do whatever you need to do.
$(document).on('data-attribute-changed', function() {
var data = $('#contains-data').data('mydata');
alert('Data changed to: ' + data);
});
$('#button').click(function() {
$('#contains-data').data('mydata', 'foo');
// Whenever you change the attribute you will user the .trigger
// method. The name of the event is arbitrary
$(document).trigger('data-attribute-changed');
});
$('#getbutton').click(function() {
var data = $('#contains-data').data('mydata');
alert('Data is: ' + data);
});
});
Let's suppose you have two different classes:
public class Person
{
public string Name, Email;
public Person(string name, string email)
{
Name = name;
Email = email;
}
}
class Data
{
public string Mail, SlackId;
public Data(string mail, string slackId)
{
Mail = mail;
SlackId = slackId;
}
}
Now, let's Prepare data to work with:
var people = new Person[]
{
new Person("Sudi", "[email protected]"),
new Person("Simba", "[email protected]"),
new Person("Sarah", string.Empty)
};
var records = new Data[]
{
new Data("[email protected]", "Sudi_Try"),
new Data("[email protected]", "Sudi@Test"),
new Data("[email protected]", "SimbaLion")
};
You will note that [email protected] has got two slackIds. I have made that for demonstrating how Join works.
Let's now construct the query to join Person with Data:
var query = people.Join(records,
x => x.Email,
y => y.Mail,
(person, record) => new { Name = person.Name, SlackId = record.SlackId});
Console.WriteLine(query);
After constructing the query, you could also iterate over it with a foreach like so:
foreach (var item in query)
{
Console.WriteLine($"{item.Name} has Slack ID {item.SlackId}");
}
Let's also output the result for GroupJoin:
Console.WriteLine(
people.GroupJoin(
records,
x => x.Email,
y => y.Mail,
(person, recs) => new {
Name = person.Name,
SlackIds = recs.Select(r => r.SlackId).ToArray() // You could materialize //whatever way you want.
}
));
You will notice that the GroupJoin will put all SlackIds in a single group.
In principle you're doing it correct already. For what you want you do need two malloc()
s.
Just some comments:
struct Vector y = (struct Vector*)malloc(sizeof(struct Vector));
y->x = (double*)malloc(10*sizeof(double));
should be
struct Vector *y = malloc(sizeof *y); /* Note the pointer */
y->x = calloc(10, sizeof *y->x);
In the first line, you allocate memory for a Vector object. malloc()
returns a pointer to the allocated memory, so y must be a Vector pointer. In the second line you allocate memory for an array of 10 doubles.
In C you don't need the explicit casts, and writing sizeof *y
instead of sizeof(struct Vector)
is better for type safety, and besides, it saves on typing.
You can rearrange your struct and do a single malloc()
like so:
struct Vector{
int n;
double x[];
};
struct Vector *y = malloc(sizeof *y + 10 * sizeof(double));
In the collapse package recently released on CRAN, I have attempted to compress most of the common apply functionality into just 2 functions:
dapply
(Data-Apply) applies functions to rows or (default) columns of matrices and data.frames and (default) returns an object of the same type and with the same attributes (unless the result of each computation is atomic and drop = TRUE
). The performance is comparable to lapply
for data.frame columns, and about 2x faster than apply
for matrix rows or columns. Parallelism is available via mclapply
(only for MAC). Syntax:
dapply(X, FUN, ..., MARGIN = 2, parallel = FALSE, mc.cores = 1L,
return = c("same", "matrix", "data.frame"), drop = TRUE)
Examples:
# Apply to columns:
dapply(mtcars, log)
dapply(mtcars, sum)
dapply(mtcars, quantile)
# Apply to rows:
dapply(mtcars, sum, MARGIN = 1)
dapply(mtcars, quantile, MARGIN = 1)
# Return as matrix:
dapply(mtcars, quantile, return = "matrix")
dapply(mtcars, quantile, MARGIN = 1, return = "matrix")
# Same for matrices ...
BY
is a S3 generic for split-apply-combine computing with vector, matrix and data.frame method. It is significantly faster than tapply
, by
and aggregate
(an also faster than plyr
, on large data dplyr
is faster though). Syntax:
BY(X, g, FUN, ..., use.g.names = TRUE, sort = TRUE,
expand.wide = FALSE, parallel = FALSE, mc.cores = 1L,
return = c("same", "matrix", "data.frame", "list"))
Examples:
# Vectors:
BY(iris$Sepal.Length, iris$Species, sum)
BY(iris$Sepal.Length, iris$Species, quantile)
BY(iris$Sepal.Length, iris$Species, quantile, expand.wide = TRUE) # This returns a matrix
# Data.frames
BY(iris[-5], iris$Species, sum)
BY(iris[-5], iris$Species, quantile)
BY(iris[-5], iris$Species, quantile, expand.wide = TRUE) # This returns a wider data.frame
BY(iris[-5], iris$Species, quantile, return = "matrix") # This returns a matrix
# Same for matrices ...
Lists of grouping variables can also be supplied to g
.
Talking about performance: A main goal of collapse is to foster high-performance programming in R and to move beyond split-apply-combine alltogether. For this purpose the package has a full set of C++ based fast generic functions: fmean
, fmedian
, fmode
, fsum
, fprod
, fsd
, fvar
, fmin
, fmax
, ffirst
, flast
, fNobs
, fNdistinct
, fscale
, fbetween
, fwithin
, fHDbetween
, fHDwithin
, flag
, fdiff
and fgrowth
. They perform grouped computations in a single pass through the data (i.e. no splitting and recombining).
Syntax:
fFUN(x, g = NULL, [w = NULL,] TRA = NULL, [na.rm = TRUE,] use.g.names = TRUE, drop = TRUE)
Examples:
v <- iris$Sepal.Length
f <- iris$Species
# Vectors
fmean(v) # mean
fmean(v, f) # grouped mean
fsd(v, f) # grouped standard deviation
fsd(v, f, TRA = "/") # grouped scaling
fscale(v, f) # grouped standardizing (scaling and centering)
fwithin(v, f) # grouped demeaning
w <- abs(rnorm(nrow(iris)))
fmean(v, w = w) # Weighted mean
fmean(v, f, w) # Weighted grouped mean
fsd(v, f, w) # Weighted grouped standard-deviation
fsd(v, f, w, "/") # Weighted grouped scaling
fscale(v, f, w) # Weighted grouped standardizing
fwithin(v, f, w) # Weighted grouped demeaning
# Same using data.frames...
fmean(iris[-5], f) # grouped mean
fscale(iris[-5], f) # grouped standardizing
fwithin(iris[-5], f) # grouped demeaning
# Same with matrices ...
In the package vignettes I provide benchmarks. Programming with the fast functions is significantly faster than programming with dplyr or data.table, especially on smaller data, but also on large data.
you can get the nodejs configuration from http://nodejs.org/
The important thing you need to keep in your mind is about its configuration in file app.js which consists of port number host and other settings these are settings working for me
backendSettings = { "scheme":"https / http ", "host":"Your website url", "port":49165, //port number 'sslKeyPath': 'Path for key', 'sslCertPath': 'path for SSL certificate', 'sslCAPath': '', "resource":"/socket.io", "baseAuthPath": '/nodejs/', "publishUrl":"publish", "serviceKey":"", "backend":{ "port":443, "scheme": 'https / http', //whatever is your website scheme "host":"host name", "messagePath":"/nodejs/message/"}, "clientsCanWriteToChannels":false, "clientsCanWriteToClients":false, "extensions":"", "debug":false, "addUserToChannelUrl": 'user/channel/add/:channel/:uid', "publishMessageToContentChannelUrl": 'content/token/message', "transports":["websocket", "flashsocket", "htmlfile", "xhr-polling", "jsonp-polling"], "jsMinification":true, "jsEtag":true, "logLevel":1};
In this if you are getting "Error: listen EADDRINUSE" then please change the port number i.e, here I am using "49165" so you can use other port such as 49170 or some other port.
For this you can refer to the following article
http://www.a2hosting.com/kb/installable-applications/manual-installations/installing-node-js-on-shared-hosting-accounts
if you are using **Bootstrap** this is solution, _x000D_
_x000D_
$(document).ready(function(e) {_x000D_
$('.bootpopup').click(function(){_x000D_
var frametarget = $(this).attr('href');_x000D_
targetmodal = '#myModal'; _x000D_
$('#modeliframe').attr("src", frametarget ); _x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
_x000D_
<!-- Optional theme -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">_x000D_
_x000D_
<!-- Latest compiled and minified JavaScript -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>_x000D_
<!-- Button trigger modal -->_x000D_
<a href="http://twitter.github.io/bootstrap/" title="Edit Transaction" class="btn btn-primary btn-lg bootpopup" data-toggle="modal" data-target="#myModal">_x000D_
Launch demo modal_x000D_
</a>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">_x000D_
<div class="modal-dialog" role="document">_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>_x000D_
<h4 class="modal-title" id="myModalLabel">Modal title</h4>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<iframe src="" id="modeliframe" style="zoom:0.60" frameborder="0" height="250" width="99.6%"></iframe>_x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
<button type="button" class="btn btn-primary">Save changes</button>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Unfortunately, most of these tools only return the NS record as provided by the actual name server itself. To be more accurate in determining which name servers are actually responsible for a domain, you'd have to either use "whois" and check the domains listed there OR use "dig [domain] NS @[root name server]" and run that recursively until you get the name server listings...
I wish there were a simple command line that you could run to get THAT result dependably and in a consistent format, not just the result that is given from the name server itself. The purpose of this for me is to be able to query about 330 domain names that I manage so I can determine exactly which name server each domain is pointing to (as per their registrar settings).
Anyone know of a command using "dig" or "host" or something else on *nix?
You can use:
SELECT 1 FROM MyTable WHERE <MyCondition>
If there is no record matching the condition, the resulted recordset is empty.
This is a fix for people who are not using maven. You also need to add standard.jar
to your lib folder for the core tag library to work. Works for jstl version 1.1.
<%@taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core"%>
For zsh you need to put it in this file: ~/.zshenv
For example, on OS X using the git-core package from MacPorts:
$ echo 'export PATH=/opt/local/sbin:/opt/local/bin:$PATH' > ~/.zshenv
In general custom audit (creating various tables) is a bad option. Database/table triggers can be disabled to skip some log activities. Custom audit tables can be tampered. Exceptions can take place that will bring down application. Not to mentions difficulties designing a robust solution. So far I see a very simple cases in this discussion. You need a complete separation from current database and from any privileged users(DBA, Developers). Every mainstream RDBMSs provide audit facilities that even DBA not able to disable, tamper in secrecy. Therefore, provided audit capability by RDBMS vendor must be the first option. Other option would be 3rd party transaction log reader or custom log reader that pushes decomposed information into messaging system that ends up in some forms of Audit Data Warehouse or real time event handler. In summary: Solution Architect/"Hands on Data Architect" needs to involve in destining such a system based on requirements. It is usually too serious stuff just to hand over to a developers for solution.
If all you need is to ensure uniqueness of elements, then HashSet is what you need.
What do you mean when you say "just a set implementation"? A set is (by definition) a collection of unique elements that doesn't save element order.
Just store the index generated in a variable, and then access the array using this varaible:
int idx = new Random().nextInt(fruits.length);
String random = (fruits[idx]);
P.S. I usually don't like generating new Random
object per randoization - I prefer using a single Random
in the program - and re-use it. It allows me to easily reproduce a problematic sequence if I later find any bug in the program.
According to this approach, I will have some variable Random r
somewhere, and I will just use:
int idx = r.nextInt(fruits.length)
However, your approach is OK as well, but you might have hard time reproducing a specific sequence if you need to later on.
Use Range("A1").Text
instead of .Value
post comment edit:
Why?
Because the .Text
property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92
then <- Text
will return exactly what it in the cell including any formatting.
The .Value
and .Value2
properties return what's stored in the cell under the hood excluding formatting. Specially .Value2
for date types, it will return the decimal representation.
If you want to dig deeper into the meaning and performance, I just found this article
which seems like a good guide
another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
now,
paste this code in a module
Sub main()
Dim ws As Worksheet, i&, j&
Set ws = Sheets(1)
For i = 3 To 7
For j = 1 To 4
Debug.Print _
"row " & i & vbTab & vbTab & _
Cells(i, j).Text & vbTab & _
Cells(i, j).Value & vbTab & _
Cells(i, j).Value2
Next j
Next i
End Sub
and Analyse
the output! Its really easy and there isn't much more i can do to help :)
.TEXT .VALUE .VALUE2
row 3 hello hello hello
row 3 hello hello hello
row 3 hello hello hello
row 3 hello hello hello
row 4 1 1 1
row 4 1 1 1
row 4 01/01/1900 31/12/1899 1
row 4 1.00% 0.01 0.01
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 6 63 63 63
row 6 =7*9 =7*9 =7*9
row 6 03/03/1900 03/03/1900 63
row 6 6300.00% 63 63
row 7 29/05/2013 29/05/2013 41423
row 7 29/05/2013 29/05/2013 29/05/2013
row 7 29/05/2013 29/05/2013 41423
row 7 29/05/2013% 29/05/2013% 29/05/2013%
Related answer, but if you want to run clean up a user inputting values into a form, here's what you can do:
const numFormatter = new Intl.NumberFormat('en-US', {
style: "decimal",
maximumFractionDigits: 2
})
// Good Inputs
parseFloat(numFormatter.format('1234').replace(/,/g,"")) // 1234
parseFloat(numFormatter.format('123').replace(/,/g,"")) // 123
// 3rd decimal place rounds to nearest
parseFloat(numFormatter.format('1234.233').replace(/,/g,"")); // 1234.23
parseFloat(numFormatter.format('1234.239').replace(/,/g,"")); // 1234.24
// Bad Inputs
parseFloat(numFormatter.format('1234.233a').replace(/,/g,"")); // NaN
parseFloat(numFormatter.format('$1234.23').replace(/,/g,"")); // NaN
// Edge Cases
parseFloat(numFormatter.format(true).replace(/,/g,"")) // 1
parseFloat(numFormatter.format(false).replace(/,/g,"")) // 0
parseFloat(numFormatter.format(NaN).replace(/,/g,"")) // NaN
Use the international date local via format
. This cleans up any bad inputs, if there is one it returns a string of NaN
you can check for. There's no way currently of removing commas as part of the locale (as of 10/12/19), so you can use a regex command to remove commas using replace
.
ParseFloat
converts the this type definition from string to number
If you use React, this is what your calculate function could look like:
updateCalculationInput = (e) => {
let value;
value = numFormatter.format(e.target.value); // 123,456.78 - 3rd decimal rounds to nearest number as expected
if(value === 'NaN') return; // locale returns string of NaN if fail
value = value.replace(/,/g, ""); // remove commas
value = parseFloat(value); // now parse to float should always be clean input
// Do the actual math and setState calls here
}
I'm very happy with kdesvn - integrates very well with konqueror, much like trortousesvn with windows explorer, and supports most of the functionality of tortoisesvn.
Of course, you'll benefit from this integration, if you use kubunto, and not ubuntu.
From the docs:
_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.
So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.
Edit: Further reading led me here:
http://www.analyticsmarket.com/blog/edit-ecommerce-data
Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.
From the DevTools console, you can run:
document.getElementsByTagName("head")[0].innerHTML += '<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"><\/script>';
Check the available jQuery version at https://code.jquery.com/jquery/.
To check whether it's loaded, see: Checking if jquery is loaded using Javascript.
...How can I step through my javascript code line by line using Google Chromes developer tools without it going into javascript libraries?...
For the record: At this time (Feb/2015) both Google Chrome and Firefox have exactly what you (and I) need to avoid going inside libraries and scripts, and go beyond the code that we are interested, It's called Black Boxing:
When you blackbox a source file, the debugger will not jump into that file when stepping through code you're debugging.
More info:
Open and read the file.
Reader r = new BufferedReader(filename);
String ret = "";
while((String s = r.nextLine()!=null))
{
ret+=s;
}
return ret;
You need to escape the dot if you want to split on a literal dot:
String extensionRemoved = filename.split("\\.")[0];
Otherwise you are splitting on the regex .
, which means "any character".
Note the double backslash needed to create a single backslash in the regex.
You're getting an ArrayIndexOutOfBoundsException
because your input string is just a dot, ie "."
, which is an edge case that produces an empty array when split on dot; split(regex)
removes all trailing blanks from the result, but since splitting a dot on a dot leaves only two blanks, after trailing blanks are removed you're left with an empty array.
To avoid getting an ArrayIndexOutOfBoundsException
for this edge case, use the overloaded version of split(regex, limit)
, which has a second parameter that is the size limit for the resulting array. When limit
is negative, the behaviour of removing trailing blanks from the resulting array is disabled:
".".split("\\.", -1) // returns an array of two blanks, ie ["", ""]
ie, when filename
is just a dot "."
, calling filename.split("\\.", -1)[0]
will return a blank, but calling filename.split("\\.")[0]
will throw an ArrayIndexOutOfBoundsException
.
Without using any external dependency or library:
$options = array(
'http' => array(
'method' => 'POST',
'content' => json_encode( $data ),
'header'=> "Content-Type: application/json\r\n" .
"Accept: application/json\r\n"
)
);
$context = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );
$response is an object. Properties can be accessed as usual, e.g. $response->...
where $data is the array contaning your data:
$data = array(
'userID' => 'a7664093-502e-4d2b-bf30-25a2b26d6021',
'itemKind' => 0,
'value' => 1,
'description' => 'Boa saudaÁ„o.',
'itemID' => '03e76d0a-8bab-11e0-8250-000c29b481aa'
);
Warning: this won't work if the allow_url_fopen setting is set to Off in the php.ini.
If you're developing for WordPress, consider using the provided APIs: https://developer.wordpress.org/plugins/http-api/
It is not elegant but possible to do it as one-liner <a>
element
<a href onclick="event.preventDefault(); location+='&like=like'">Like</a>
_x000D_
SimpleDateFormat has a constructor which takes the locale, have you tried that?
http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html
Something like
new SimpleDateFormat("your-pattern-here", Locale.getDefault());
Here is what you do in Excel 2003:
Here is what you do in Excel 2007:
Once this is done, the sheet is hidden and cannot be unhidden without the password. Make sense?
If you really need to keep some calculations secret, try this: use Access (or another Excel workbook or some other DB of your choice) to calculate what you need calculated, and export only the "unclassified" results to your Excel workbook.
We've solved this, although we didn't think having the addListener outside of the for would make any difference, it seems to. Here's the answer:
Create a new function with your information for the infoWindow in it:
function addInfoWindow(marker, message) {
var infoWindow = new google.maps.InfoWindow({
content: message
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
}
Then call the function with the array ID and the marker you want to create:
addInfoWindow(marker, hotels[i][3]);
Dictionaries in python have no order. You could use a list of tuples as your data structure instead.
d = { 'a': 10, 'b': 20, 'c': 30}
newd = [('a',10), ('b',20), ('c',30)]
Then this code could be used to find the locations of keys with a specific value
locations = [i for i, t in enumerate(newd) if t[0]=='b']
>>> [1]
I got the same error while using other one entity, He was annotating the class wrongly by using the table name inside the @Entity annotation without using the @Table annotation
The correct format should be
@Entity //default name similar to class name 'FooBar' OR @Entity( name = "foobar" ) for differnt entity name
@Table( name = "foobar" ) // Table name
public class FooBar{
Add this to html:
<svg id="mySVG" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"/>
Try this function and adapt for you program:
var svgNS = "http://www.w3.org/2000/svg";
function createCircle()
{
var myCircle = document.createElementNS(svgNS,"circle"); //to create a circle. for rectangle use "rectangle"
myCircle.setAttributeNS(null,"id","mycircle");
myCircle.setAttributeNS(null,"cx",100);
myCircle.setAttributeNS(null,"cy",100);
myCircle.setAttributeNS(null,"r",50);
myCircle.setAttributeNS(null,"fill","black");
myCircle.setAttributeNS(null,"stroke","none");
document.getElementById("mySVG").appendChild(myCircle);
}
I would use list comprehension :
somelists = [
[1, 2, 3],
['a', 'b'],
[4, 5]
]
cart_prod = [(a,b,c) for a in somelists[0] for b in somelists[1] for c in somelists[2]]
HTML Imports, part of the Web Components cast, is also a way to include HTML documents in other HTML documents. See http://www.html5rocks.com/en/tutorials/webcomponents/imports/
The accepted answer didn't work in my situation, not sure why. I switched from JRE1.7 to JRE1.8 and that resolved the issue automatically. JRE1.8 uses TLS1.2 by default
Constructor is special function used to initialise the data member, where the methods are functions to perform specific task.
Constructor name is the same name as the class name, where the method name may or may not or be class name.
Constructor does not allow any return type, where methods allow return type.
There are a couple of good solutions here.
Similar to the answer from Harpal, but within the facet, so doesn't require any change to underlying data or pre-plotting manipulation:
# Change this code:
facet_grid(.~size) +
# To this code:
facet_grid(~factor(size, levels=c('50%','100%','150%','200%')))
This is flexible, and can be implemented for any variable as you change what element is faceted, no underlying change in the data required.
P (Polynomial Time): As name itself suggests, these are the problems which can be solved in polynomial time.
NP (Non-deterministic-polynomial Time): These are the decision problems which can be verified in polynomial time. That means, if I claim that there is a polynomial time solution for a particular problem, you ask me to prove it. Then, I will give you a proof which you can easily verify in polynomial time. These kind of problems are called NP problems. Note that, here we are not talking about whether there is a polynomial time solution for this problem or not. But we are talking about verifying the solution to a given problem in polynomial time.
NP-Hard: These are at least as hard as the hardest problems in NP. If we can solve these problems in polynomial time, we can solve any NP problem that can possibly exist. Note that these problems are not necessarily NP problems. That means, we may/may-not verify the solution to these problems in polynomial time.
NP-Complete: These are the problems which are both NP and NP-Hard. That means, if we can solve these problems, we can solve any other NP problem and the solutions to these problems can be verified in polynomial time.
Update your view with null value instead of parent viewgroup in Adapter viewholder onCreateViewHolder method.
@Override
public AdapterItemSku.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflator.inflate(R.layout.layout_item, null, false);
return new MyViewHolder(view);
}
You need to add query.addEntity(SwitcherServiceSource.class) before calling the .list() on query.
Just to enhance @adivis12 answer, you don't need to do the if
statement. Put it like this:
fig, ax = plt.subplots()
for BAR in dict_of_dfs.keys():
dict_of_dfs[BAR].plot(ax=ax)
I did it! Using <intent-filter>
. Put the following into your manifest file:
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:host="www.youtube.com" android:scheme="http" />
</intent-filter>
This works perfectly!
I'm using a 3rd party program that executes Oracle SQL and I encountered this error. Prior to a SELECT
statement, I had some commented notes that included special characters. Removing the comments resolved the issue.
public static void main(String[] args) {
String str = "hello world here I am";
StringTokenizer strToken = new StringTokenizer(str);
int token = strToken.countTokens();
String str1 [] = new String[token];
char chr[] = new char[str.length()];
int counter = 0;
for(int j=0; j < str.length(); j++) {
if(str.charAt(j) != ' ') {
chr[j] = str.charAt(j);
}else {
str1[counter++] = new String(chr).trim();
chr = new char[str.length()];
}
}
str1[counter++] = new String(chr).trim();
for(int i=str1.length-1; i >= 0 ; i--) {
System.out.println(str1[i]);
}
}
O/P is: am I here world hello
A more compact (and modern) rewrite of @somethingthere's proposed solution:
let titleCase = (str => str.toLowerCase().split(' ').map(
c => c.charAt(0).toUpperCase() + c.substring(1)).join(' '));
document.write(titleCase("I'm an even smaller tea pot"));
_x000D_
Use the command svn status on your working copy to show the status of files, files that are not yet under version control (and not ignored) will have a question mark next to them.
As for ignoring files you need to edit the svn:ignore property, read the chapter Ignoring Unversioned Items in the svnbook at http://svnbook.red-bean.com/en/1.5/svn.advanced.props.special.ignore.html. The book also describes more about using svn status.
This Worked for me
^(?:(?:\+|0{0,2})91(\s*[\ -]\s*)?|[0]?)?[789]\d{9}|(\d[ -]?){10}\d$
Valid Scenarios:
+91-9883443344
9883443344
09883443344
919883443344
0919883443344
+919883443344
+91-9883443344
0091-9883443344
+91 -9883443344
+91- 9883443344
+91 - 9883443344
0091 - 9883443344
7856128945
9998564723
022-24130000
080 25478965
0416-2565478
08172-268032
04512-895612
02162-240000
+91 9883443344
022-24141414
Invalid Scenarios:
WAQU9876567892
ABCD9876541212
0226-895623124
6589451235
0924645236
0222-895612
098-8956124
022-2413184
According to Microsoft docs:
the read-first approach requires an extra database read, and can result in more complex code for handling concurrency conflict
However, you should know that using Update method on DbContext will mark all the fields as modified and will include all of them in the query. If you want to update a subset of fields you should use the Attach method and then mark the desired field as modified manually.
context.Attach(person);
context.Entry(person).Property(p => p.Name).IsModified = true;
context.SaveChanges();
Use get_the_category()
like this:
<?php
foreach((get_the_category()) as $category) {
echo $category->cat_name . ' ';
}
?>
It returns a list because a post can have more than one category.
The documentation also explains how to do this from outside the loop.
The new version of Qt Creator also has a "profile" build option between debug and release. Here's how I'm detecting that:
CONFIG(debug, debug|release) { DEFINES += DEBUG_MODE }
else:CONFIG(force_debug_info) { DEFINES += PROFILE_MODE }
else { DEFINES += RELEASE_MODE }
this will also work
data.groupby(data['date'].dt.year)
ImmutableMap does not accept null
values whereas Collections.unmodifiableMap()
does. In addition it will never change after construction, while UnmodifiableMap
may. From the JavaDoc:
An immutable, hash-based Map with reliable user-specified iteration order. Does not permit null keys or values.
Unlike Collections.unmodifiableMap(java.util.Map), which is a view of a separate map which can still change, an instance of ImmutableMap contains its own data and will never change. ImmutableMap is convenient for public static final maps ("constant maps") and also lets you easily make a "defensive copy" of a map provided to your class by a caller.
. argument of 0
is interpreted as infinite
. in order to drag the highGUI windows, you need to continually call the cv::waitKey()
function. eg for static images:
cv::imshow("winname", img);
while(cv::waitKey(1) != 27); // 27 = ascii value of ESC
I faced similar issue "CrashLoopBackOff" when I debugged getting pods and logs of pod. Found out that my command arguments are wrong
public class MenuFragment extends Fragment implements View.OnClickListener {
private Context mContext;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
FragmentMenuBinding binding=FragmentMenuBinding.inflate(inflater,container,false);
View view=binding.getRoot();
mContext=view.getContext();
return view;
}
}
When the project was originally created, the click-once signing certificate was added on the signing tab of the project's properties. This signs the click-once manifest when you build it. Between then and now, that certificate is no longer available. Either this wasn't the machine you originally built it on or it got cleaned up somehow. You need to re-add that certificate to your machine or chose another certificate.
How about this (in you don't want an one liner) ?
for row in df.collect():
d = row.asDict()
s = "%d\t%s\t%s\n" % (d["int_column"], d["string_column"], d["string_column"])
f.write(s)
f is a opened file descriptor. Also the separator is a TAB char, but it's easy to change to whatever you want.
If you have the column it's very easy.
Using the designer, you could set the column as an identity (1,1): right click on the table ? design ? in part left (right click) ? properties ? in identity columns, select #column.
Properties:
Identity column:
May be the virus by name CONFLICKER try d.exe tool from symantec on the machine hope your problem will be resolved. Check the security logs in domain controller and scan those machines because of this virus it creates bad passwords and lock the users.
You're very close. What you need to remember is when you're calling a method from another class you need to tell the compiler where to find that method.
So, instead of simply calling addWord("someWord")
, you will need to initialise an instance of the WordList class (e.g. WordList list = new WordList();
), and then call the method using that (i.e. list.addWord("someWord");
.
However, your code at the moment will still throw an error there, because that would be trying to call a non-static method from a static one. So, you could either make addWord()
static, or change the methods in the Words class so that they're not static.
My bad with the above paragraph - however you might want to reconsider ProcessInput()
being a static method - does it really need to be?
Check first what aliases you have...
git config --get-regexp alias
If it's not there you can create your own (reference: https://git-scm.com/book/en/v2/Git-Basics-Git-Aliases)
// git add
git config --global alias.a '!git add -A'
// git commit
git config --global alias.c '!git commit'
// git commit -m
git config --global alias.cm '!git commit -m'
// git add commit
git config --global alias.ac '!git add -A && git commit'
// git add commit -m
git config --global alias.acm '!git add -A && git commit -m'
For instance, if you use the last one...
git acm 'My commit'
A TortoiseSVN equivalent solution of the accepted answer (I had written this in an internal document for my company as we are newly adopting SVN) follows. I thought it would be helpful to share here as well:
Checking out a single file: Subversion does not support checkout of a single file, it only supports checkout of directory structures. (Reference: http://subversion.tigris.org/faq.html#single-file-checkout). This is because with every directory that is checked out as a working copy, the metadata regarding modifications/file revisions is stored as an internal hidden folder (.svn/_svn). This is not supported currently (v1.6) for single files.
Alternate recommended strategy: You will have to do the checkout directory part only once, following that you can directly go and checkout your single files. Do a sparse checkout of the parent folder and directory structure. A sparse checkout is basically checking out only the folder structure without populating the content files. So you checkout only the directory structures and need not checkout ALL the files as was the concern. Reference: http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-checkout.html
Step 1: Proceed to repository browser
Step 2: Right click the parent folder within the repository containing all the files that you wish to work on and Select Checkout.
Step 3: Within new popup window, ensure that the checkout directory points to the correct location on your local PC. There will also be a dropdown menu labeled “checkout depth”. Choose “Only this item” or “Immediate children, including folders” depending on your requirement. Second option is recommended as, if you want to work on nested folder, you can directly proceed the next time otherwise you will have to follow this whole procedure again for the nested folder.
Step 4: The parent folder(s) should now be available within your locally chosen folder and is now being monitored with SVN (a hidden folder “.svn” or “_svn” should now be present). Within the repository now, right click the single file that you wish to have checked out alone and select the “Update Item to revision” option. The single file can now be worked on and checked back into the repository.
I hope this helps.
That's a fine solution. I just wanted to add
set -e
as a rudimentary error mechanism. It will immediately stop your script if a simple command fails. I think this should have been the default behavior: since such errors almost always signify something unexpected, it is not really 'sane' to keep executing the following commands.
Swift 2.0
let dateNow = NSDate()
let calendar = NSCalendar.currentCalendar()
let hour = calendar.component(NSCalendarUnit.Hour, fromDate: dateNow)
let minute = calendar.component(NSCalendarUnit.Minute, fromDate: dateNow)
print(String(hour))
print(String(minute))
Please do take note of the cast to String in the print statement, you can easily assign that value to variables, like this:
var hoursString = String(hour)
var minutesString = String(minute)
Then you can concatenate values like this:
var compoundString = "\(hour):\(minute)"
print(compoundString)
dir /b /a-d /s *.*
will fulfill your requirement.
To expand on benscabbia's answer:
private RestTemplate restCaller = new RestTemplate(getClientHttpRequestFactory());
private ClientHttpRequestFactory getClientHttpRequestFactory() {
int connectionTimeout = 5000; // milliseconds
int socketTimeout = 10000; // milliseconds
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(connectionTimeout)
.setConnectionRequestTimeout(connectionTimeout)
.setSocketTimeout(socketTimeout)
.build();
CloseableHttpClient client = HttpClientBuilder
.create()
.setDefaultRequestConfig(config)
.build();
return new HttpComponentsClientHttpRequestFactory(client);
}
My version using variables in a bash script:
Find any backslashes and replace with forward slashes:
input="This has a backslash \\"
output=$(echo "$input" | sed 's,\\,/,g')
echo "$output"
Using context object you can get LayoutInflater from following code
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Using plain old JavaScript:
var val = "Fish";_x000D_
var sel = document.getElementById('sel');_x000D_
document.getElementById('btn').onclick = function() {_x000D_
var opts = sel.options;_x000D_
for (var opt, j = 0; opt = opts[j]; j++) {_x000D_
if (opt.value == val) {_x000D_
sel.selectedIndex = j;_x000D_
break;_x000D_
}_x000D_
}_x000D_
}
_x000D_
<select id="sel">_x000D_
<option>Cat</option>_x000D_
<option>Dog</option>_x000D_
<option>Fish</option>_x000D_
</select>_x000D_
<button id="btn">Select Fish</button>
_x000D_
But if you really want to use jQuery:
var val = 'Fish';
$('#btn').on('click', function() {
$('#sel').val(val);
});
var val = 'Fish';_x000D_
$('#btn').on('click', function() {_x000D_
$('#sel').val(val);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<select id="sel">_x000D_
<option>Cat</option>_x000D_
<option>Dog</option>_x000D_
<option>Fish</option>_x000D_
</select>_x000D_
<button id="btn">Select Fish</button>
_x000D_
In case your options have value attributes which differ from their text content and you want to select via text content:
<select id="sel">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
<script>
var val = 'Fish';
$('#sel option:contains(' + val + ')').prop({selected: true});
</script>
But if you do have the above set up and want to select by value using jQuery, you can do as before:
var val = 3;
$('#sel').val(val);
For the browsers that support document.querySelector
and the HTMLOptionElement::selected
property, this is a more succinct way of accomplishing this task:
var val = 3;
document.querySelector('#sel [value="' + val + '"]').selected = true;
<select data-bind="value: val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
<script>
var viewModel = {
val: ko.observable()
};
ko.applyBindings(viewModel);
viewModel.val(3);
</script>
<template id="template" is="dom-bind">
<select value="{{ val }}">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</template>
<script>
template.val = 3;
</script>
Note: this has not been updated for the final stable release.
<app id="app">
<select [value]="val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</app>
<script>
var App = ng.Component({selector: 'app'})
.View({template: app.innerHTML})
.Class({constructor: function() {}});
ng.bootstrap(App).then(function(app) {
app._hostComponent.instance.val = 3;
});
</script>
<div id="app">
<select v-model="val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
val: null,
},
mounted: function() {
this.val = 3;
}
});
</script>
There are a lot of good answers here with very accurate relational algebra examples. Here is a very simplified answer that might be helpful for amateur or novice coders with SQL coding dilemmas.
Basically, more often than not, JOIN
queries boil down to two cases:
For a SELECT
of a subset of A
data:
INNER JOIN
when the related B
data you are looking for MUST exist per database design;LEFT JOIN
when the related B
data you are looking for MIGHT or MIGHT NOT exist per database design.Use the overloads that take the controller name too...
return RedirectToAction("Index", "MyController");
and
@Html.ActionLink("Link Name","Index", "MyController", null, null)
You can use _.differenceBy from lodash
const myArray = [
{name: 'deepak', place: 'bangalore'},
{name: 'chirag', place: 'bangalore'},
{name: 'alok', place: 'berhampur'},
{name: 'chandan', place: 'mumbai'}
];
const toRemove = [
{name: 'deepak', place: 'bangalore'},
{name: 'alok', place: 'berhampur'}
];
const sorted = _.differenceBy(myArray, toRemove, 'name');
Example code here: CodePen
On Linux the command is whereis. Alternatively you can issue find / -name git
and wait for an eternity. Alternatively try echo $PATH | sed "s/:/ /g" | xargs -L 1 ls | grep git
I've been using this functionality in node.js, this is my fastest implementation so far:
var nLength = function(n) {
return (Math.log(Math.abs(n)+1) * 0.43429448190325176 | 0) + 1;
}
It should handle positive and negative integers (also in exponential form) and should return the length of integer part in floats.
The following reference should provide some insight into the method: Weisstein, Eric W. "Number Length." From MathWorld--A Wolfram Web Resource.
I believe that some bitwise operation can replace the Math.abs, but jsperf shows that Math.abs works just fine in the majority of js engines.
Update: As noted in the comments, this solution has some issues :(
Update2 (workaround) : I believe that at some point precision issues kick in and the Math.log(...)*0.434...
just behaves unexpectedly. However, if Internet Explorer or Mobile devices are not your cup of tea, you can replace this operation with the Math.log10
function. In Node.js I wrote a quick basic test with the function nLength = (n) => 1 + Math.log10(Math.abs(n) + 1) | 0;
and with Math.log10
it worked as expected. Please note that Math.log10
is not universally supported.
in terminal do:
sudo mysql -u root -p
enter the password.
select user from mysql.user;
now delete the user 'the_username'
DROP USER the_unername;
replace 'the_username' with the user that you want to delete.
Inspired by this post and by the Stack Overflow question that led me here -- Is it possible to insert multiple rows at a time in an SQLite database? -- I've posted my first Git repository:
https://github.com/rdpoor/CreateOrUpdate
which bulk loads an array of ActiveRecords into MySQL, SQLite or PostgreSQL databases. It includes an option to ignore existing records, overwrite them or raise an error. My rudimentary benchmarks show a 10x speed improvement compared to sequential writes -- YMMV.
I'm using it in production code where I frequently need to import large datasets, and I'm pretty happy with it.
Starting with Visual Studio 2017 you have the capability to have some compiler metrics about what takes time.
Add those parameters to C/C++ -> Command line (Additional Options) in the project properties window:
/Bt+ /d2cgsummary /d1reportTime
You can have more informations in this post.
You can simply check out a new branch, and then commit:
git checkout -b my_new_branch
git commit
Checking out the new branch will not discard your changes.
It's a linefeed character. How you use it would be up to you.
Select
is used for projecting some or all fields of a dataframe
. It won't give you an value
as an output but a new dataframe
. Its a transformation
.
How it looks:
Best solution to my case. I need video fit web view size. Use embed youtube link with your video id. Example:
WebView youtubeWebView; //todo find or bind web view
String myVideoYoutubeId = "-bvXmLR3Ozc";
outubeWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
WebSettings webSettings = youtubeWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(true);
youtubeWebView.loadUrl("https://www.youtube.com/embed/" + myVideoYoutubeId);
Web view xml code
<WebView
android:id="@+id/youtube_web_view"
android:layout_width="match_parent"
android:layout_height="200dp"/>
Try This
ImagePath = "http://localhost/profilepics/abc.png";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ImagePath);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receiveStream = response.GetResponseStream();
Try this
<input type="submit"
value="HOME"
onclick="goHome()"
style="font-size : 20px; width: 100%; height: 100px;" />
Here is the screen print showing the options to ignore the file or folder after the installation of the .ignore plugin. The generated file name would be .gitignore
$('input').on('ifChanged', function(event) {
if($(".checkbox").is(":checked")) {
$value = $(this).val();
}
else if($(".checkbox").is(":not(:checked)")) {
$value= $(this).val();
}
});
Check if Xcode is installed or not:
$ gcc --version
$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
$ brew doctor
$ brew update
http://techsharehub.blogspot.com/2013/08/brew-command-not-found.html "click here for exact instruction updates"
You can add data-dismiss="modal" to your button attributes which call angularjs funtion.
Such as;
<button type="button" class="btn btn-default" data-dismiss="modal">Send Form</button>
An alternative is to use String.format
:
double[] arr = { 23.59004,
35.7,
3.0,
9
};
for ( double dub : arr ) {
System.out.println( String.format( "%.2f", dub ) );
}
output:
23.59
35.70
3.00
9.00
You could also use System.out.format
(same method signature), or create a java.util.Formatter
which works in the same way.
Open CMD with administrative access(Right click then run as administrator) then type the following command there:
set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib
Replace My_python_lib with the folder name of your installed python like for me it was C:\python27
.
Then to check if the path variable is set, type echo %PATH%
you'll see your python part in the end. Hence now python
is accessible.
From this tutorial
Assuming your controller's action method is something like this:
public ActionResult AllCategories(int id = 0)
{
return View(db.Categories.Include(p => p.Products).ToList());
}
Modify your models to be something like this:
public class Product
{
[Key]
public int ID { get; set; }
public int CategoryID { get; set; }
//new code
public virtual Category Category { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Path { get; set; }
//remove code below
//public virtual ICollection<Category> Categories { get; set; }
}
public class Category
{
[Key]
public int CategoryID { get; set; }
public string Name { get; set; }
//new code
public virtual ICollection<Product> Products{ get; set; }
}
Then your since now the controller takes in a Category as Model (instead of a Product):
foreach (var category in Model)
{
<h3><u>@category.Name</u></h3>
<div>
<ul>
@foreach (var product in Model.Products)
{
// cut for brevity, need to add back more code from original
<li>@product.Title</li>
}
</ul>
</div>
}
UPDATED: Add ToList() to the controller return statement.
Check the Activity tab in iTunes Connect after you upload the app and wait until it processes:
I just had this error in a bash script. The issue was an accidental \ at the end of the previous line that was giving an error.
upstream
defines a cluster that you can proxy requests to. It's commonly used for defining either a web server cluster for load balancing, or an app server cluster for routing / load balancing.
The a == b
expression invokes A.__eq__
, since it exists. Its code includes self.value == other
. Since int's don't know how to compare themselves to B's, Python tries invoking B.__eq__
to see if it knows how to compare itself to an int.
If you amend your code to show what values are being compared:
class A(object):
def __eq__(self, other):
print("A __eq__ called: %r == %r ?" % (self, other))
return self.value == other
class B(object):
def __eq__(self, other):
print("B __eq__ called: %r == %r ?" % (self, other))
return self.value == other
a = A()
a.value = 3
b = B()
b.value = 4
a == b
it will print:
A __eq__ called: <__main__.A object at 0x013BA070> == <__main__.B object at 0x013BA090> ?
B __eq__ called: <__main__.B object at 0x013BA090> == 3 ?
Are you committing the cell before pressing the button (pressing Enter)? The contents of the cell must be stored before it can be used to name a sheet.
A better way to do this is to pop up a dialog box and get the name you wish to use.
Line Input works fine for small files. However, when file sizes reach around 90k, Line Input jumps all over the place and reads data in the wrong order from the source file. I tested it with different filesizes:
49k = ok
60k = ok
78k = ok
85k = ok
93k = error
101k = error
127k = error
156k = error
Lesson learned - use Scripting.FileSystemObject
If you need to download only text file into String
you can use this simple way, Swift 5:
let list = try? String(contentsOf: URL(string: "https://example.com/file.txt")!)
In case you want non optional result or error handling:
do {
let list = try String(contentsOf: URL(string: "https://example.com/file.txt")!)
}
catch {
// Handle error here
}
You should know that network operations may take some time, to prevent it from running in main thread and locking your UI, you may want to execute the code asynchronously, for example:
DispatchQueue.global().async {
let list = try? String(contentsOf: URL(string: "https://example.com/file.txt")!)
}
Simon's answer and Volcano's together explain what you're doing wrong, and Simon explains how you can fix it by redesigning your interface.
But if you really need to read 1 character, and then later read 1 line, you can do that. It's not trivial, and it's different on Windows vs. everything else.
There are actually three cases: a Unix tty, a Windows DOS prompt, or a regular file (redirected file/pipe) on either platform. And you have to handle them differently.
First, to check if stdin is a tty (both Windows and Unix varieties), you just call sys.stdin.isatty()
. That part is cross-platform.
For the non-tty case, it's easy. It may actually just work. If it doesn't, you can just read from the unbuffered object underneath sys.stdin
. In Python 3, this just means sys.stdin.buffer.raw.read(1)
and sys.stdin.buffer.raw.readline()
. However, this will get you encoded bytes, rather than strings, so you will need to call .decode(sys.stdin.decoding)
on the results; you can wrap that all up in a function.
For the tty case on Windows, however, input will still be line buffered even on the raw buffer. The only way around this is to use the Console I/O functions instead of normal file I/O. So, instead of stdin.read(1)
, you do msvcrt.getwch()
.
For the tty case on Unix, you have to set the terminal to raw mode instead of the usual line-discipline mode. Once you do that, you can use the same sys.stdin.buffer.read(1)
, etc., and it will just work. If you're willing to do that permanently (until the end of your script), it's easy, with the tty.setraw
function. If you want to return to line-discipline mode later, you'll need to use the termios
module. This looks scary, but if you just stash the results of termios.tcgetattr(sys.stdin.fileno())
before calling setraw
, then do termios.tcsetattr(sys.stdin.fileno(), TCSAFLUSH, stash)
, you don't have to learn what all those fiddly bits mean.
On both platforms, mixing console I/O and raw terminal mode is painful. You definitely can't use the sys.stdin
buffer if you've ever done any console/raw reading; you can only use sys.stdin.buffer.raw
. You could always replace readline
by reading character by character until you get a newline… but if the user tries to edit his entry by using backspace, arrows, emacs-style command keys, etc., you're going to get all those as raw keypresses, which you don't want to deal with.
Chiming in a bit late here, but couldn't resist.
You're question is half-flawed. Let me explain:
The first half of your question, on image replacement, is a valid question, and my opinion is that for a logo, a simple image; an alt attribute; and CSS for its positioning are sufficient.
The second half of your question, on the "SEO value" of the H1 for a logo is the wrong approach to deciding on which elements to use for different types of content.
A logo isn't a primary heading, or even a heading at all, and using the H1 element to markup the logo on each page of your site will do (slightly) more harm than good for your rankings. Semantically, headings (H1 - H6) are appropriate for, well, just that: headings and subheadings for content.
In HTML5, more than one heading is allowed per page, but a logo isn't deserving of one of them. Your logo, which might be a fuzzy green widget and some text is in an image off to the side of the header for a reason - it's sort of a "stamp", not a hierarchical element to structure your content. The first (whether you use more depends on your heading hierarchy) H1 of each page of your site should headline its subject matter. The main primary heading of your index page might be 'The Best Source For Fuzzy Green Widgets in NYC'. The primary heading on another page might be 'Shipping Details for Our Fuzzy Widgets'. On another page, it may be 'About Bert's Fuzzy Widgets Inc.'. You get the idea.
Side note: As incredible as it sounds, don't look at the source of Google-owned web properties for examples of correct markup. This is a whole post unto itself.
To get the most "SEO value" out HTML and its elements, take a look at the HTML5 specs, and make make markup decisions based on (HTML) semantics and value to users before search engines, and you'll have better success with your SEO.
jQuery(document).ready(function(){
jQuery(".head h3").html('Public Offers');
});
For space between the check mark and the text use:
android:paddingLeft="10dp"
But it becomes more than 10dp, because the check mark contains padding (about 5dp) around. If you want to remove padding, see How to remove padding around Android CheckBox:
android:paddingLeft="-5dp"
android:layout_marginStart="-5dp"
android:layout_marginLeft="-5dp"
// or android:translationX="-5dp" instead of layout_marginLeft
Move script tag at the end of BODY instead of HEAD because in current code when the script is computed html element doesn't exist in document.
Since you don't want to you jquery. Use window.onload or document.onload to execute the entire piece of code that you have in current script tag. window.onload vs document.onload
To display a phone number with (###) ###-#### format, you can create a new HtmlHelper.
@Html.DisplayForPhone(item.Phone)
public static class HtmlHelperExtensions
{
public static HtmlString DisplayForPhone(this HtmlHelper helper, string phone)
{
if (phone == null)
{
return new HtmlString(string.Empty);
}
string formatted = phone;
if (phone.Length == 10)
{
formatted = $"({phone.Substring(0,3)}) {phone.Substring(3,3)}-{phone.Substring(6,4)}";
}
else if (phone.Length == 7)
{
formatted = $"{phone.Substring(0,3)}-{phone.Substring(3,4)}";
}
string s = $"<a href='tel:{phone}'>{formatted}</a>";
return new HtmlString(s);
}
}
IE and Firefox both contain ways to execute JavaScript from CSS. As Paolo mentions, one way in IE is the expression
technique, but there's also the more obscure HTC behavior, in which a seperate XML that contains your script is loaded via CSS. A similar technique for Firefox exists, using XBL. These techniques don't exectue JavaScript from CSS directly, but the effect is the same.
Use a CSS rule like so:
body {
behavior:url(script.htc);
}
and within that script.htc file have something like:
<PUBLIC:COMPONENT TAGNAME="xss">
<PUBLIC:ATTACH EVENT="ondocumentready" ONEVENT="main()" LITERALCONTENT="false"/>
</PUBLIC:COMPONENT>
<SCRIPT>
function main()
{
alert("HTC script executed.");
}
</SCRIPT>
The HTC file executes the main()
function on the event ondocumentready
(referring to the HTC document's readiness.)
Firefox supports a similar XML-script-executing hack, using XBL.
Use a CSS rule like so:
body {
-moz-binding: url(script.xml#mycode);
}
and within your script.xml:
<?xml version="1.0"?>
<bindings xmlns="http://www.mozilla.org/xbl" xmlns:html="http://www.w3.org/1999/xhtml">
<binding id="mycode">
<implementation>
<constructor>
alert("XBL script executed.");
</constructor>
</implementation>
</binding>
</bindings>
All of the code within the constructor tag will be executed (a good idea to wrap code in a CDATA section.)
In both techniques, the code doesn't execute unless the CSS selector matches an element within the document. By using something like body
, it will execute immediately on page load.
This method is much faster. You can only tel when placing a lot of files in a directory. My A:\ external hard drive contains almost 1 terabit so it makes a big difference when dealing with a lot of files.
static void Main(string[] args)
{
DirectoryInfo di = new DirectoryInfo("A:\\");
FullDirList(di, "*");
Console.WriteLine("Done");
Console.Read();
}
static List<FileInfo> files = new List<FileInfo>(); // List that will hold the files and subfiles in path
static List<DirectoryInfo> folders = new List<DirectoryInfo>(); // List that hold direcotries that cannot be accessed
static void FullDirList(DirectoryInfo dir, string searchPattern)
{
// Console.WriteLine("Directory {0}", dir.FullName);
// list the files
try
{
foreach (FileInfo f in dir.GetFiles(searchPattern))
{
//Console.WriteLine("File {0}", f.FullName);
files.Add(f);
}
}
catch
{
Console.WriteLine("Directory {0} \n could not be accessed!!!!", dir.FullName);
return; // We alredy got an error trying to access dir so dont try to access it again
}
// process each directory
// If I have been able to see the files in the directory I should also be able
// to look at its directories so I dont think I should place this in a try catch block
foreach (DirectoryInfo d in dir.GetDirectories())
{
folders.Add(d);
FullDirList(d, searchPattern);
}
}
By the way I got this thanks to your comment Jim Mischel
RFC3966 defines the IETF standard URI for telephone numbers, that is the 'tel:' URI. That's the standard. There's no similar standard that specifies 'callto:', that's a particular convention for Skype on platforms where is allows registering a URI handler to support it.
I used:
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
to disable the screen timeout and
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
to re-enable it.
This question is old, the other answers are old. "Employed Russian"s answer is very good and informative, but it only works if you have the source code. If you don't, the alternatives back then were very tricky. Fortunately nowadays we have a simple solution to this problem (as commented in one of his replies), using patchelf. All you have to do is:
$ ./patchelf --set-interpreter /path/to/newglibc/ld-linux.so.2 --set-rpath /path/to/newglibc/ myapp
And after that, you can just execute your file:
$ ./myapp
No need to chroot
or manually edit binaries, thankfully. But remember to backup your binary before patching it, if you're not sure what you're doing, because it modifies your binary file. After you patch it, you can't restore the old path to interpreter/rpath. If it doesn't work, you'll have to keep patching it until you find the path that will actually work... Well, it doesn't have to be a trial-and-error process. For example, in OP's example, he needed GLIBC_2.3
, so you can easily find which lib provides that version using strings
:
$ strings /lib/i686/libc.so.6 | grep GLIBC_2.3
$ strings /path/to/newglib/libc.so.6 | grep GLIBC_2.3
In theory, the first grep would come empty because the system libc doesn't have the version he wants, and the 2nd one should output GLIBC_2.3 because it has the version myapp
is using, so we know we can patchelf
our binary using that path. If you get a segmentation fault, read the note at the end.
When you try to run a binary in linux, the binary tries to load the linker, then the libraries, and they should all be in the path and/or in the right place. If your problem is with the linker and you want to find out which path your binary is looking for, you can find out with this command:
$ readelf -l myapp | grep interpreter
[Requesting program interpreter: /lib/ld-linux.so.2]
If your problem is with the libs, commands that will give you the libs being used are:
$ readelf -d myapp | grep Shared
$ ldd myapp
This will list the libs that your binary needs, but you probably already know the problematic ones, since they are already yielding errors as in OP's case.
"patchelf" works for many different problems that you may encounter while trying to run a program, related to these 2 problems. For example, if you get: ELF file OS ABI invalid
, it may be fixed by setting a new loader (the --set-interpreter
part of the command) as I explain here. Another example is for the problem of getting No such file or directory
when you run a file that is there and executable, as exemplified here. In that particular case, OP was missing a link to the loader, but maybe in your case you don't have root access and can't create the link. Setting a new interpreter would solve your problem.
Thanks Employed Russian and Michael Pankov for the insight and solution!
Note for segmentation fault: you might be in the case where myapp
uses several libs, and most of them are ok but some are not; then you patchelf
it to a new dir, and you get segmentation fault. When you patchelf
your binary, you change the path of several libs, even if some were originally in a different path. Take a look at my example below:
$ ldd myapp
./myapp: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.20' not found (required by ./myapp)
./myapp: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.21' not found (required by ./myapp)
linux-vdso.so.1 => (0x00007fffb167c000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f9a9aad2000)
libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f9a9a8ce000)
libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f9a9a6af000)
libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f9a9a3ab000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f9a99fe6000)
/lib64/ld-linux-x86-64.so.2 (0x00007f9a9adeb000)
libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f9a99dcf000)
Note that most libs are in /lib/x86_64-linux-gnu/
but the problematic one (libstdc++.so.6
) is on /usr/lib/x86_64-linux-gnu
. After I patchelf'ed myapp
to point to /path/to/mylibs
, I got segmentation fault. For some reason, the libs are not totally compatible with the binary. Since myapp
didn't complain about the original libs, I copied them from /lib/x86_64-linux-gnu/
to /path/to/mylibs2
, and I also copied libstdc++.so.6
from /path/to/mylibs
there. Then I patchelf'ed it to /path/to/mylibs2
, and myapp
works now. If your binary uses different libs, and you have different versions, it might happen that you can't fix your situation. :( But if it's possible, mixing libs might be the way. It's not ideal, but maybe it will work. Good luck!
To write a newline use \n
not /n
the latter is just a slash and a n
Even if it is an old thread, maybe some is interested.
If it is an option to you to use the same method inside the same class and archive different return types, use generics: Oracle Lesson Generics
Simple example for generic value holder class:
class GenericValue<T> {
private T myValue;
public GenericValue(T myValue) { this.myValue = myValue; }
public T getVal() { return myValue; }
}
And use it like this:
public class ExampleGenericValue {
public static void main(String[] args) {
GenericValue<Integer> intVal = new GenericValue<Integer>(10);
GenericValue<String> strVal = new GenericValue<String>("go on ...");
System.out.format("I: %d\nS: %s\n", intVal.getVal(), strVal.getVal());
}
}
... will result in the following output:
I: 10
S: go on ...
The .Date
answer is misleading since you get the error mentioned before. Another way to compare, other than mentioned DbFunctions.TruncateTime
, may also be:
DateTime today = DateTime.Now.date;
var q = db.Games.Where(t => SqlFunctions.DateDiff("dayofyear", today, t.StartDate) <= 0
&& SqlFunctions.DateDiff("year", today, t.StartDate) <= 0)
It looks better(more readable) in the generated SQL query. But I admit it looks worse in the C# code XD. I was testing something and it seemed like TruncateTime
was not working for me unfortunately the fault was between keyboard and chair, but in the meantime I found this alternative.
I think there's a simpler solution: Just use the DialogInterface
argument that is passed to the onClick
method.
AlertDialog.Builder db = new AlertDialog.Builder(context);
db.setNegativeButton("cancel", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface d, int arg1) {
db.cancel();
//here db.cancel will dismiss the builder
};
});
See, for example, http://www.mkyong.com/android/android-alert-dialog-example.
you need to add padding-top to "fill" element, plus add box-sizing:border-box - sample here bootply
As of 8, May, 2019:
JVM heap size depends on system configuration, meaning:
a) client jvm vs server jvm
b) 32bit vs 64bit.
Links:
1) updation from J2SE5.0: https://docs.oracle.com/javase/6/docs/technotes/guides/vm/gc-ergonomics.html
2) brief answer: https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/ergonomics.html
3) detailed answer: https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/parallel.html#default_heap_size
4) client vs server: https://www.javacodegeeks.com/2011/07/jvm-options-client-vs-server.html
Summary: (Its tough to understand from the above links. So summarizing them here)
1) Default maximum heap size for Client jvm is 256mb (there is an exception, read from links above).
2) Default maximum heap size for Server jvm of 32bit is 1gb and of 64 bit is 32gb (again there are exceptions here too. Kindly read that from the links).
So default maximum jvm heap size is: 256mb or 1gb or 32gb depending on VM, above.
Try this
<script>
$(window).scrollTop(100);
</script>
Select * from Table1 t1 Left Join Table2 t2 on t1.id=t2.id
By definition: Left Join selects all columns mentioned with the "select" keyword from Table 1 and the columns from Table 2 which matches the criteria after the "on" keyword.
Similarly,By definition: Right Join selects all columns mentioned with the "select" keyword from Table 2 and the columns from Table 1 which matches the criteria after the "on" keyword.
Referring to your question, id's in both the tables are compared with all the columns needed to be thrown in the output. So, ids 1 and 2 are common in the both the tables and as a result in the result you will have four columns with id and name columns from first and second tables in order.
*select *
from Table1
left join Table2 on Table1.id = Table2.id
The above expression,it takes all the records (rows) from table 1 and columns, with matching id's from table 1 and table 2, from table 2.
select *
from Table2
right join Table1 on Table1.id = Table2.id**
Similarly from the above expression,it takes all the records (rows) from table 1 and columns, with matching id's from table 1 and table 2, from table 2. (remember, this is a right join so all the columns from table2 and not from table1 will be considered).
Actually there are many reasons for this issue. Mine was because of Invalid token passed. I was passing same token generated from one app and using same token in another app. Once token updated , it work for me.
Try this. It almost seemed to simple to be right. Simply convert the Integer to a string. Then you can use the method below or concatenate.
Dim I, J, K, L As Integer
Dim K1, L1 As String
K1 = K
L1 = L
Cells(2, 1) = K1 & " - uploaded"
Cells(3, 1) = L1 & " - expanded"
MsgBox "records uploaded " & K & " records expanded " & L
Let's use some java 8 feature:
IntStream.iterate(10, x -> x + 10).limit(5)
.forEach(System.out::println);
If you need to store the numbers you can collect them into a collection eg:
List numbers = IntStream.iterate(10, x -> x + 10).limit(5)
.boxed()
.collect(Collectors.toList());
And some delay added:
IntStream.iterate(10, x -> x + 10).limit(5)
.forEach(x -> {
System.out.println(x);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// Do something with the exception
}
});
I think that var_export()
, the forgotten brother of var_dump()
has the best output - it's more compact:
echo "<pre>";
var_export($menue);
echo "</pre>";
By the way: it's not allway necessary to use <pre>
. var_dump()
and var_export()
are already formatted when you take a look in the source code of your webpage.
sys.argv
is the list of arguments passed to the Python program. The first argument, sys.argv[0]
, is actually the name of the program as it was invoked. That's not a Python thing, but how most operating systems work. The reason sys.argv[0]
exists is so you can change your program's behaviour depending on how it was invoked. sys.argv[1]
is thus the first argument you actually pass to the program.
Because lists (like most sequences) in Python start indexing at 0, and because indexing past the end of the list is an error, you need to check if the list has length 2 or longer before you can access sys.argv[1]
.
A variation on the .agg() function; provides the ability to (1) persist type DataFrame, (2) apply averages, counts, summations, etc. and (3) enables groupby on multiple columns while maintaining legibility.
df.groupby(['att1', 'att2']).agg({'att1': "count", 'att3': "sum",'att4': 'mean'})
using your values...
df.groupby(['Name', 'Fruit']).agg({'Number': "sum"})
Shortcut way: (windows xp)
1) click Start > run > services.msc
2) Scroll down to 'Windows Presentation Foundation Font Cache 4.0.0.0' and then right click and select properties
Write-Warning "This is only a test warning." -WarningAction Inquire
You could quickly read it in, and increment a counter, just use a loop to increment, doing nothing with the text.
If java command is working and getting problem with javac. then first check in jdk's bin directory javac.exe file is there or not.
If javac.exe file is exist then set JAVA_HOME
as System variable.
The -m
switch of PuTTY takes a path to a script file as an argument, not a command.
Reference: https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-m
So you have to save your command (command_run
) to a plain text file (e.g. c:\path\command.txt
) and pass that to PuTTY:
putty.exe -ssh user@host -pw password -m c:\path\command.txt
Though note that you should use Plink (a command-line connection tool from PuTTY suite). It's a console application, so you can redirect its output to a file (what you cannot do with PuTTY).
A command-line syntax is identical, an output redirection added:
plink.exe -ssh user@host -pw password -m c:\path\command.txt > output.txt
See Using the command-line connection tool Plink.
And with Plink, you can actually provide the command directly on its command-line:
plink.exe -ssh user@host -pw password command > output.txt
Similar questions:
Automating running command on Linux from Windows using PuTTY
Executing command in Plink from a batch file
I had the same problem. The reason for the error is unsupported characters in the path to the file. Replaced the cyrillic in English - it helped.
You can convert the time using the following code.
TimeSpan _time = TimeSpan.Parse("07:35");
But if you want to get the current time of the day you can use the following code:
TimeSpan _CurrentTime = DateTime.Now.TimeOfDay;
The result will be:
03:54:35.7763461
With a object cantain the Hours, Minutes, Seconds, Ticks and etc.
xattr ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png
# com.apple.FinderInfo
# com.apple.lastuseddate#PS
# com.apple.metadata:kMDItemIsScreenCapture
# com.apple.metadata:kMDItemScreenCaptureGlobalRect
# com.apple.metadata:kMDItemScreenCaptureType
xattr -d com.apple.lastuseddate#PS ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png
xattr -d kMDItemIsScreenCapture ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png
xattr -l ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png
# com.apple.FinderInfo
# com.apple.metadata:kMDItemScreenCaptureGlobalRect
# com.apple.metadata:kMDItemScreenCaptureType
xattr -c ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png
xattr -r ~/Desktop
xattr -rd com.apple.FinderInfo ~/Desktop
xattr -rc ~/Desktop
WARN: Once you delete these you DON'T get them back!
FAULT ERROR: There is NO UNDO.
I wanted to address the error's people are getting.
Because the errors drove me nuts too...
On a mac if you install xattr
in python, then your environment may have an issue.
There are two different paths on my mac for
xattr
type -a xattr
# xattr is /usr/local/bin/xattr # PYTHON Installed Version
# xattr is /usr/bin/xattr # Mac OSX Installed Version
So in one of the example's where -c
will not work in xargs is because in bash you default to the non-python version.
-c
/usr/bin/xattr -c
-c
/usr/local/bin/xattr -c
# option -c not recognized
My Shell/Terminal defaults to /usr/local/bin/xattr because my $PATH
/usr/local/bin:
is before /usr/bin:
which I believe is the default.
I can prove this because, if you try to uninstall the python xattr
you will see:
pip3 uninstall xattr
Uninstalling xattr-0.9.6:
Would remove:
/usr/local/bin/xattr
/usr/local/lib/python3.7/site-packages/xattr-0.9.6.dist-info/*
/usr/local/lib/python3.7/site-packages/xattr/*
Proceed (y/n)?
To Fix option -c not recognized
Errors.
xattr
you may have: pip3 uninstall xattr
Terminal
windows & quit Terminal
Terminal
window.xattr
command and it should now work.OR
If you want to keep the Python
xattr
then use
/usr/bin/xattr
for any Shell
commands in Terminal
Python's version of xattr
doesn't handle images at all:
Good-Mac:~ JayRizzo$ xattr ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png
# com.apple.FinderInfo
# Traceback (most recent call last):
# File "/usr/local/bin/xattr", line 8, in <module>
# sys.exit(main())
# File "/usr/local/lib/python3.7/site-packages/xattr/tool.py", line 196, in main
# attr_value = attr_value.decode('utf-8')
# UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb0 in position 2: invalid start byte
Good-Mac:~ JayRizzo$ /usr/bin/xattr ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png
# com.apple.FinderInfo
# com.apple.lastuseddate#PS
# com.apple.metadata:kMDItemIsScreenCapture
# com.apple.metadata:kMDItemScreenCaptureGlobalRect
# com.apple.metadata:kMDItemScreenCaptureType
MAN PAGE for Python xattr VERSION 0.6.4
NOTE: I could not find the python help page for current VERSION 0.9.6
Thanks for Reading!
Open Control Panel Administrative Tools Services Select Extended services tab
Find SQL Server(MSSQLSERVER) & SQL Server(SQLEXPRESS) Stop these services and Start again (from the start & stop button displayed above)
Done.
Use java assist Java library for manipulating the Java bytecode (.class file) of an application.
-> Spring , Hibernate , EJB using this for proxy implementation
-> we can bytecode manipulation to do some program analysis
-> we can use Javassist to implement a transparent cache for method return values, by intercepting all method invocations and only delegating to the super implementation on the first invocation.
When it searches for java it looks from left to right in path entries which are separated by : so you need to add the path of latest jdk/bin directory before /usr/bin, so when it searches it'll find the latest one and stop searching further.
i.e. PATH=/usr/java/jdk_1.8/bin:/usr/bin:..... and so on.
then initialize user profile using command: source ~/.bash_profile
and check with: [which java]
you'll get the right one.
Ok I did this in Windows 7 32-bit system.
step 1: go to - C:\Program Files\Java\jdk1.6.0_26\bin - and run jarsigner.exe first ( double click)
step2: locate debug.keystore, in my case it was - C:\Users\MyPcName\.android
step3: open command prompt and go to dir - C:\Program Files\Java\jdk1.6.0_26\bin and give the following command: keytool -list -keystore "C:\Users\MyPcName\.android\debug.keystore"
step4: it will ask for Keystore password now. ( which I am figuring out... :-? )
update: OK in my case password was ´ android ´.
- (I am using Eclipse for android, so I found it here)
Follow the steps in eclipse:
Windows>preferences>android>build>..
( Look in `default Debug Keystore´ field.)
Command to change the keystore password (look here): Keystore change passwords
You should avoid using pool.getConnection()
if you can. If you call pool.getConnection()
, you must call connection.release()
when you are done using the connection. Otherwise, your application will get stuck waiting forever for connections to be returned to the pool once you hit the connection limit.
For simple queries, you can use pool.query()
. This shorthand will automatically call connection.release()
for you—even in error conditions.
function doSomething(cb) {
pool.query('SELECT 2*2 "value"', (ex, rows) => {
if (ex) {
cb(ex);
} else {
cb(null, rows[0].value);
}
});
}
However, in some cases you must use pool.getConnection()
. These cases include:
If you must use pool.getConnection()
, ensure you call connection.release()
using a pattern similar to below:
function doSomething(cb) {
pool.getConnection((ex, connection) => {
if (ex) {
cb(ex);
} else {
// Ensure that any call to cb releases the connection
// by wrapping it.
cb = (cb => {
return function () {
connection.release();
cb.apply(this, arguments);
};
})(cb);
connection.beginTransaction(ex => {
if (ex) {
cb(ex);
} else {
connection.query('INSERT INTO table1 ("value") VALUES (\'my value\');', ex => {
if (ex) {
cb(ex);
} else {
connection.query('INSERT INTO table2 ("value") VALUES (\'my other value\')', ex => {
if (ex) {
cb(ex);
} else {
connection.commit(ex => {
cb(ex);
});
}
});
}
});
}
});
}
});
}
I personally prefer to use Promise
s and the useAsync()
pattern. This pattern combined with async
/await
makes it a lot harder to accidentally forget to release()
the connection because it turns your lexical scoping into an automatic call to .release()
:
async function usePooledConnectionAsync(actionAsync) {
const connection = await new Promise((resolve, reject) => {
pool.getConnection((ex, connection) => {
if (ex) {
reject(ex);
} else {
resolve(connection);
}
});
});
try {
return await actionAsync(connection);
} finally {
connection.release();
}
}
async function doSomethingElse() {
// Usage example:
const result = await usePooledConnectionAsync(async connection => {
const rows = await new Promise((resolve, reject) => {
connection.query('SELECT 2*4 "value"', (ex, rows) => {
if (ex) {
reject(ex);
} else {
resolve(rows);
}
});
});
return rows[0].value;
});
console.log(`result=${result}`);
}
editTransactionRow.pay_id is Null so in fact you are doing: null.ToString() and it cannot be executed. You need to check editTransactionRow.pay_id and not editTransactionRow.pay_id.ToString();
You code should be (IF pay_id is a string):
If String.IsNullOrEmpty(editTransactionRow.pay_id) = False Then
stTransactionPaymentID = editTransactionRow.pay_id 'Check for null value
End If
If pay_id is an Integer than you can just check if it's null normally without String... Edit to show you if it's not a String:
If editTransactionRow.pay_id IsNot Nothing Then
stTransactionPaymentID = editTransactionRow.pay_id 'Check for null value
End If
If it's from a database you can use IsDBNull but if not, do not use it.
Try using SCP on Windows to transfer files, you can download SCP from Putty's website. Then try running:
pscp.exe filename.extension [email protected]:directory/subdirectory
There is a full length guide here.
You can't restyle the default MessageBox as that's dependant on the current Windows OS theme, however you can easily create your own MessageBox. Just add a new form (i.e. MyNewMessageBox) to your project with these settings:
FormBorderStyle FixedToolWindow
ShowInTaskBar False
StartPosition CenterScreen
To show it use myNewMessageBoxInstance.ShowDialog();
. And add a label and buttons to your form, such as OK and Cancel and set their DialogResults appropriately, i.e. add a button to MyNewMessageBox
and call it btnOK
. Set the DialogResult
property in the property window to DialogResult.OK
. When that button is pressed it would return the OK result:
MyNewMessageBox myNewMessageBoxInstance = new MyNewMessageBox();
DialogResult result = myNewMessageBoxInstance.ShowDialog();
if (result == DialogResult.OK)
{
// etc
}
It would be advisable to add your own Show method that takes the text and other options you require:
public DialogResult Show(string text, Color foreColour)
{
lblText.Text = text;
lblText.ForeColor = foreColour;
return this.ShowDialog();
}
Solution from typescript interfaces reference:
interface ClockConstructor {
new (hour: number, minute: number): ClockInterface;
}
interface ClockInterface {
tick();
}
function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface {
return new ctor(hour, minute);
}
class DigitalClock implements ClockInterface {
constructor(h: number, m: number) { }
tick() {
console.log("beep beep");
}
}
class AnalogClock implements ClockInterface {
constructor(h: number, m: number) { }
tick() {
console.log("tick tock");
}
}
let digital = createClock(DigitalClock, 12, 17);
let analog = createClock(AnalogClock, 7, 32);
So the previous example becomes:
interface AnimalConstructor {
new (): Animal;
}
class Animal {
constructor() {
console.log("Animal");
}
}
class Penguin extends Animal {
constructor() {
super();
console.log("Penguin");
}
}
class Lion extends Animal {
constructor() {
super();
console.log("Lion");
}
}
class Zoo {
AnimalClass: AnimalConstructor // AnimalClass can be 'Lion' or 'Penguin'
constructor(AnimalClass: AnimalConstructor) {
this.AnimalClass = AnimalClass
let Hector = new AnimalClass();
}
}
In Swift you would do it like this:
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.numberOfLines = 0
(Note that the way the lineBreakMode constant works is different to in ObjC)
A little more compact than the other answers if you want to use c as a TForm:
if(c is TForm form){
form.DoStuff();
}
//for update
(from x in dataBase.Customers
where x.Name == "Test"
select x).ToList().ForEach(xx => xx.Name="New Name");
//for delete
dataBase.Customers.RemoveAll(x=>x.Name=="Name");
You simply have to set the state
of the your button self.x
to normal
:
self.x['state'] = 'normal'
or
self.x.config(state="normal")
This code would go in the callback for the event that will cause the Button to be enabled.
Also, the right code should be:
self.x = Button(self.dialog, text="Download", state=DISABLED, command=self.download)
self.x.pack(side=LEFT)
The method pack
in Button(...).pack()
returns None
, and you are assigning it to self.x
. You actually want to assign the return value of Button(...)
to self.x
, and then, in the following line, use self.x.pack()
.
You can try accessing the NavigationBars Right Button item and set its selector property...heres a reference UIBarButtonItem reference, another thing if this doenst work that will def work is, set the right button item of the nav bar to a custom UIBarButtonItem that you create and set its selector...hope this helps
You can do this with php if the button opens a new page.
For example if the button link to a page named pagename.php as, url: www.website.com/pagename.php the button will stay red as long as you stay on that page.
I exploded the url by '/' an got something like:
url[0] = pagename.php
<? $url = explode('/', substr($_SERVER['REQUEST_URI'], strpos('/',$_SERVER['REQUEST_URI'] )+1,strlen($_SERVER['REQUEST_URI']))); ?>
<html>
<head>
<style>
.btn{
background:white;
}
.btn:hover,
.btn-on{
background:red;
}
</style>
</head>
<body>
<a href="/pagename.php" class="btn <? if (url[0]='pagename.php') {echo 'btn-on';} ?>">Click Me</a>
</body>
</html>
note: I didn't try this code. It might need adjustments.
Maybe this is a bit redundant, but no one appeared to have mentioned this as a solution.
As a beginner in SQL I find that when using a BEGIN
and END
SSMS usually adds a squiggly line with incorrect syntax near 'END'
to END, simply because there's no content in between yet. If you're just setting up BEGIN
and END
to get started and add the actual query later, then simply add a bogus PRINT
statement so SSMS stops bothering you.
For example:
IF (1=1)
BEGIN
PRINT 'BOGUS'
END
The following will indeed set you on the wrong track, thinking you made a syntax error which in this case just means you still need to add content in between BEGIN and END:
IF (1=1)
BEGIN
END
For details of setting up a proxy for Maven, see the mini guide.
Essentially you need to ensure the proxies section in either the global settings ([maven install]/conf/settings.xml
), or user settings (${user.home}/.m2/settings.xml
) is configured correctly. It is better to do this in your user settings to avoid storing the password in plain text in a public location.
Maven 2.1 introduced password encryption, but I've not got round to checking if the encryption applies for the proxy settings as well as repository passwords (don't see why it wouldn't though).
For info, there is a commented-out proxy configuration in your settings.xml and instructions on how to modify it.
From the mini-guide, your settings should look something like this:
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
[...]
<proxies>
<proxy>
<active>true</active>
<protocol>http</protocol>
<host>proxy.somewhere.com</host>
<port>8080</port>
<username>proxyuser</username>
<password>somepassword</password>
<nonProxyHosts>www.google.com|*.somewhere.com</nonProxyHosts>
</proxy>
</proxies>
[...]
</settings>
Enable TextWrapping="Wrap"
and AcceptsReturn="True"
on your TextBox.
You might also wish to enable AcceptsTab
and SpellCheck.IsEnabled
too.