_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d7801 | train | Although you should really switch to PDO / mysqli and prepared statements with bound parameters to avoid sql injection and breaking sql statements if your variables contain quotation marks, you will probably run into problems with PDO / mysqli as well: Your password (change it!) contains a $.
See the following example on codepad:
<?php
function test($var)
{
echo $var;
}
$test_var = "test$string";
test($test_var);
Output:
test
You will not be able to connect successfully to the database as your password will never be correct.
Change:
"=c(p$zTTH2Jm"
to:
'=c(p$zTTH2Jm' | unknown | |
d7802 | train | Beanstalk uses the security group you asked for, but on creation it also creates a unique one for that configuration. If you launch your instance it will be in the security group as expected.
A: Instead of stopping it from being created, was able to modify its rules such that I changed to just allow port 22 access only from my private security group.
Namespace: aws:autoscaling:launchconfiguration
OptionName: SSHSourceRestriction
Value: tcp, 22, 22, my-private-security-group
Visit : https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/command-options-general.html#SSHSourceRestriction | unknown | |
d7803 | train | In my opinion, your approach can be improved altogether
*
*Firstly, animating the margin property of an element is not a good way to move it left and right. Making the element fixed and animating the left and right properties would work much better.
*Secondly, you could greatly simplify the code by using an attribute on the button to determine direction instead of writing duplicated code with just a few words different for moving left vs right.
*Also, your calling your variable delay but using that variable to set the animation's duration which is misleading. You should re-name that duration
Here's how I would do it:
var easingsList = [
"swing",
"easeInQuad",
"easeOutQuad",
"easeInOutQuad",
"easeInCubic",
"easeOutCubic",
"easeInOutCubic",
"easeInQuart",
"easeOutQuart",
"easeInOutQuart",
"easeInQuint",
"easeOutQuint",
"easeInOutQuint",
"easeInSine",
"easeOutSine",
"easeInOutSine",
"easeInExpo",
"easeOutExpo",
"easeInOutExpo",
"easeInCirc",
"easeOutCirc",
"easeInOutCirc",
"easeInElastic",
"easeOutElastic",
"easeInOutElastic",
"easeInBack",
"easeOutBack",
"easeInOutBack",
"easeInBounce",
"easeOutBounce"
];
$('.move').click(function(){
var $this=$(this);
var duration = parseInt($("#duration").val());
var direction = $(this).data('direction');
var n =0;
moveBox($('.box').eq(n), easingsList[n], duration, direction);
moveBox($('.box').eq(n+1), easingsList[n+1], duration, direction);
});
function moveBox($element, easing, duration, direction) {
var pageWidth = $("body").width();
var boxWidth = $element.width();
$element.css('right','auto').css('left','auto');
var options = {duration:duration,easing:easing};
var properties ={};
properties[direction]=pageWidth - boxWidth + "px";
$element.stop().animate(properties,options);
}
body {
margin: 0;
}
.box {
height: 50px;
width: 150px;
display: block;
border: solid 1px black;
text-align: center;
text-decoration: none;
margin-bottom: 10px;
line-height: 50px;
position:fixed;
}
.box-holder{
width: 100%;
position:relative;
height: 50px;
margin-bottom: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
<h1> jQuery Animate Easing Examples </h1>
<input placeholder='duration; 100ms, 1s etc.' id='duration' value="3000">
<input placeholder='end color; rgb(0,0,0), #000000, rgba(0,0,0,1) etc.' id='endColor'>
<br>
<a href='#' class='link move' data-direction="right" > Move Left </a>
<a href='#' class='link move' data-direction="left" style='float:right'> Move Right </a>
<div class="box-holder"><div class="box"> swing </div> </div>
<div class="box-holder"><div class="box">easeInQuad</div></div>
<div class="box-holder"><div class="box">easOutQuad</div></div>
<div class="box-holder"><div class="box">easeInOutQuad</div></div>
<div class="box-holder"><div class="box">easeInCubic</div></div>
<div class="box-holder"><div class="box">easeOutCubic</div></div>
<div class="box-holder"><div class="box">easeInOutCubic</div></div>
<div class="box-holder"><div class="box">easeInQuart</div></div>
<div class="box-holder"><div class="box">easeOutQuart</div></div>
<div class="box-holder"><div class="box">easeInOutQuart</div></div>
<div class="box-holder"><div class="box">easInQuint</div></div>
<div class="box-holder"><div class="box">easeOutQuint</div></div>
<div class="box-holder"><div class="box">easeInOutQuint</div></div>
<div class="box-holder"><div class="box">easeInSine</div></div>
<div class="box-holder"><div class="box">easeOutSine</div></div>
<div class="box-holder"><div class="box">easeInOutSine</div></div>
<div class="box-holder"><div class="box">easeInExpo</div></div>
<div class="box-holder"><div class="box">easeOutExpo</div></div>
<div class="box-holder"><div class="box">easeInOutExpo</div></div>
<div class="box-holder"><div class="box">easeInCirc</div></div>
<div class="box-holder"><div class="box">easeOutCirc</div></div>
<div class="box-holder"><div class="box">easeInOutCirc</div></div>
<div class="box-holder"><div class="box">easeInElasic</div></div>
<div class="box-holder"><div class="box">easeOutElastic</div></div>
<div class="box-holder"><div class="box">easeInOutElatic</div></div>
<div class="box-holder"><div class="box">easeInBack</div></div>
<div class="box-holder"><div class="box">easeOutBack</div></div>
<div class="box-holder"><div class="box">easeInOutBack</div></div>
<div class="box-holder"><div class="box">easeInBounce</div></div>
<div class="box-holder"><div class="box">easeOutBounce</div></div> | unknown | |
d7804 | train | Is it size or execution time?
I'm going to assume that self is a UI object. If it is, the block should be:
Controller* __weak weakSelf = self;
dispatch_async(queue, ^{
Controller* strongSelf = weakSelf;
if (strongSelf) {
...
}
else {
// self has been deallocated in the meantime.
}
});
Thus you may prefer a MVVC solution, where a view model does the hard work, not the view controller. | unknown | |
d7805 | train | That topic comes up every once in a while, but the conclusion always has been that this isn't something that the core wants to support: https://github.com/cakephp/cakephp/issues/9197
So you're on your own here, and there's many ways how you could solve this in a more DRY manner, but that depends to a non-negligible degree on your application's specific needs. It's hard to give any proper generic advice on this, as doing things wrong can have dire consequences.
Like if you'd blindly apply a specific connection to all read operations, you'd very likely end up very sad when your application will issue a read on a different connection while you're in a transaction that writes something based on the read data.
All that being sad, you could split your models into read/write ones, going down the CQRS-ish route, you could use behaviors that provide a more straightforward and reusable API for your tables, you could move your operations into the model layer and hide the possibly a bit dirty implementation that way, you could configure the default connection based on the requested endpoint, eg whether it's a read or a write one, etc.
There's many ways to "solve" the problem, but I'm afraid it's not something anyone here could definitively answer.
A: I needed this too, and solved it by extending the Table class to an "AppTable." I overrode the find() method to use a different version of query(), which I called readQuery(). Within my readQuery(), I modified the $_connection member variable to use my read-only connection before generating the query with $this->query(). Then when the query was generated, I switched it back to the write connection. I included checks to make sure I didn't do this if there was an active transaction or if anything had been written previously in the request lifecycle (because the replication might not have finished yet, and I'd get old data).
It wasn't terribly difficult to set up; you just need to be willing to extend Cake's base Table class a bit to switch between the two connections when generating the Query object in find(). | unknown | |
d7806 | train | Try to remove parent LinearLayout. Because you have CardView which is acting as list item.
Try this row.xml -
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="@+id/imageViewFront" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_marginLeft="100dp"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="New Text"
android:textColor="#0055CC"
android:id="@+id/textViewPropertyname" />
<TextView
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:textColor="#0055CC"
android:layout_columnWeight="1"
android:id="@+id/textViewPropertyDescription"/>
</LinearLayout>
</android.support.v7.widget.CardView>
Hope it will help :)
A: Just add notifyDataSetChanged() to your Activity as below:
aQuery.ajax(URL, JSONObject.class,new AjaxCallback<JSONObject>(){
@Override
public void callback(String url, JSONObject object, AjaxStatus status) {
try {
bean = new Bean();
list = new ArrayList<Bean>();
String string = object.getString("data");
JSONArray jsonArray = new JSONArray(string);
for (int i=0;i<jsonArray.length();i++) {
jsonObject = jsonArray.getJSONObject(i);
bean.setPropertyName("property_name");
bean.setPropertyDescription("property_desc");
list.add(bean);
}
//here notify your adapter
//is to Notify any registered observers that the data set has changed.
mAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
A: Because on your callback you have created new instance of list
list = new ArrayList<Bean>();
then in fact, the new created list and DataList in your adapter are pointing to 2 difference objects => calling notifyDataSetChanged here won't work. Try writing method updateData on MyAdapter and call it from your callback method
public void updateData(List<Bean> List){
DataList = List;
notifyDataSetChanged();
}
On your callback:
aQuery.ajax(URL, JSONObject.class,new AjaxCallback<JSONObject>(){
@Override
public void callback(String url, JSONObject object, AjaxStatus status) {
try {
bean = new Bean();
list = new ArrayList<Bean>();
String string = object.getString("data");
JSONArray jsonArray = new JSONArray(string);
for (int i=0;i<jsonArray.length();i++) {
jsonObject = jsonArray.getJSONObject(i);
bean.setPropertyName("property_name");
bean.setPropertyDescription("property_desc");
list.add(bean);
}
// update data
mAdapter.updateData(list);
} catch (JSONException e) {
e.printStackTrace();
}
}
}); | unknown | |
d7807 | train | I'm assuming you have a file that looks like this:
stuff
`ifdef
some code
`endif
stuff
With the cursor on `ifdef (or `ifndef), you want to jump to `endif with % then back to `ifdef if you press % again. I'm also assuming you're using the matchit plugin.
Solution:
:let b:match_words='`ifdef\>\|`ifndef\>:`endif\>'
Notice that the | has to be escaped with a backslash. Also, you need quotation marks '. So the backticks were not the problem. | unknown | |
d7808 | train | You're not sending the form to the context in your shelley_test method - see the difference in the render line compared with get_input.
Note though you don't need shelley_test at all: just go straight to /get_input/ to see the empty form. | unknown | |
d7809 | train | Try to add the following line at the begin of your code :
# -*- coding: utf-8 -*- | unknown | |
d7810 | train | This could be due to the fact that IE6 does not support the preventDefault method.
Where you make use of this method (e.preventDefault()), replace the call with the following
if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; }
See if that works for you :)
While it feels warm and fuzzy to be able to support all browsers, IE6 is not a warm and fuzzy kind of browser. You will keep running into problems if you want to fully support IE6, I'm afraid. | unknown | |
d7811 | train | It isn't clear in this example. But you can not have inline scripts containing <script> or </script> inside of a string, or the browser will try and process it like a script tag.
Escaping and unescaping html avoids this problem. A better solution is to put the script in a separate file from the html document.
A: For xhtml compliance you cannot have any HTML tag (<div></div> or <img />) inside a script block so either you use unescape or concatenation '<' + 'div...' or you add //<![CDATA[ ... //]]> inside the script block to pass validation.
A: Line breaks and similar quotes to the JavaScript's break the parser.
var test = "This "string", for example.";
Backslash escapes are built-in, so this works:
var test = "This \"string\", for example.";
But then you'd have to find a function to escape ", ', \n, \r, and from the other answers, < and > as well.
escape() already encodes strings to remove most non-alphanumeric characters, and unescape() undoes escape().
escape("It's > 20% less complicated this way.")
"It%27s%20%3E%2020%25%20less%20complicated%20this%20way."
If the escaped spaces bother you, try:
escape("It's > 20% less complicated this way.").replace(/%20/g, " ")
"It%27s %3E 20%25 less complicated this way." | unknown | |
d7812 | train | The container images will use the underlying OS license. Microsoft calls it supplmental license.
You are licensed to use this Supplement in conjunction with the
underlying host operating system software (βHost Softwareβ) solely to
assist running the containers feature in the Host Software. The Host
Software license terms apply to your use of the Supplement. You may
not use it if you do not have a license for the Host Software. You may
use this Supplement with each validly licensed copy of the Host
Software. | unknown | |
d7813 | train | If you have a data model like this:
Zoo{
name:string
animalCages<-->>AnimalCage.zoo
}
AnimalCage{
nameOfSpecies:string
zoo<<-->Zoo.animalCages
animals<-->>Animal.animalCage
}
Animal{
name:string
animalCage<<-->AnimalCage.animals
}
The to find a specific AnimalCage by name of species for a given Zoo object:
NSString *soughtSpecies=@"Canis Lupis"; // normally this variable would be passed in to the method
NSPredicate *p=[NSPredicate predicateWithFormat:@"nameOfSpecies==%@", soughtSpecies];
NSSet *wolves=[[zoo animalCages] filteredSetUsingPredicate:p];
Or you can use objectPassingTest: if you like blocks.
If you use custom NSManagedObject subclasses, then you get custom accessor methods and can use self.dot notation so the above would be:
Zoo *zoo= // fetch the appropriate zoo object
NSString *soughtSpecies=@"Canis Lupis";
NSPredicate *p=[NSPredicate predicateWithFormat:@"nameOfSpecies==%@", soughtSpecies];
NSSet *wolves=[zoo.animalCages filteredSetUsingPredicate:p];
If you know before hand that you are going to have to find cages a lot, you could wrap the above up in a method on your Zoo class e.g.
@implementation Zoo
//... other stuff
-(AnimalCage *) cageForSpecieNamed:(NSString *) specieName{
NSPredicate *p=[NSPredicate predicateWithFormat:@"nameOfSpecies==%@", specieName];
NSSet *wolves=[self.animalCages filteredSetUsingPredicate:p];
return [wolves anyObject]; // assuming one cage per species
}
Objective-c is intentionally verbose because it was supposed to be "self documenting" and the editor written for the language at the beginning had autocomplete. So, if your used to a more expressive language it might seem you are doing a lot of work but logically you aren't. | unknown | |
d7814 | train | Perhaps changing your for loop into this:
# cursor fetchall() method returns all rows from a query
for Title,Content in cur.fetchall():
... will fix the issue? | unknown | |
d7815 | train | I suggest to create dictionary with enumerate:
df = pd.DataFrame({
'A':list('abcdef'),
'B':[4,5,4,5,5,4],
'C':[7,8.0,9,4.0,2,3],
'D':[1,3,5,7,1,0],
'E':[5,3,6,9,2,4],
'F':list('aaabbb')
})
d = dict(enumerate(df))
print (d)
{0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F'}
Or list of tuples like suggested @Chris in comments:
L = list(enumerate(df))
print (L)
[(0, 'A'), (1, 'B'), (2, 'C'), (3, 'D'), (4, 'E'), (5, 'F')] | unknown | |
d7816 | train | As long as the ranges passed to .Range are valid ranges, your code should work.
Based upon your code, the first instance:
Sheets("Issues Database").Range(xrng1, xrng2).Interior.ColorIndex = 19
should be fine.
However, your second instance:
Sheets("Issues Database").Range(xrng2, xrng3).Interior.ColorIndex = 2 is referencing ranges that are not in scope since you are reusing xrng2 which is defined in a different logic path.
Presumable updating your second problem line to this:
Sheets("Issues Database").Range(xrng3, xrng4).Interior.ColorIndex = 2 will give you your expected behavior. | unknown | |
d7817 | train | This answer worked. I had to delete the cache.
before(async () => {
delete require.cache[require.resolve('../../fileToTest.js')]; // <------
sinon.stub(greeting, 'greeting').callsFake((req, res, next) => 'bye!');
fileToTest = require('../../fileToTest.js');
}); | unknown | |
d7818 | train | You have to change the quantity instead of removing the product. Number of product units in the cart = quantity.
Try something like this:
function remove_from_cart(){
$product_id = 47;
$cart = WC()->cart;
$product_cart_id = $cart->generate_cart_id( $product_id );
$cart_item_key = $cart->find_product_in_cart( $product_cart_id );
if ( $cart_item_key ){
$quantity = $cart->get_cart_item($cart_item_key)['quantity'] - 1;
$cart->set_quantity($cart_item_key, $quantity);
}
} | unknown | |
d7819 | train | The save is performed after the form validation, you can make the category obj creation during the validation.
Have a look at the form fields' clean methods that you can override on django docs http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other
A: Thank you for your code, I've just tested it. But it's not exactly what I'm looking for, I will explain what I want to do.
Let's say that we have Category and Article classes in our model, each one has a title. To make this title reusable, I created another application that will manage fields, I created the class Title and I added it as foreignkey to Category and Article forms.
I switched the select box to an input field using raw_id_fields.
Now, when I create a category or an article, I have to select or write a title, when this title exists, it works perfectly but when it doesn't exist I want to create it before creating the category so it can use it.
I tried to do that in the save method, in the pre_save signal and in the clean method but I always get the error "Select a valid choice. That choice is not one of the available choices."
I'm using a hard coded solution to create the title now, I want just to see if it will work, these are the lines that I inserted in the different methods to create the title before creating the category :
t = Title(title = "MyTitle")
t.save()
I tried to create a Category with MyTitle as title but I get the same error, when I try to create another one using an existing title, it works and the title "MyTitle" is created. That's mean that the creation of the object happens after the form verification. What I want is just doing this before. The title object should be created before the verification.
Thank you very much for your help
A: You should probably consider putting the code to create Category entries in the model's manager:
class CategoryManager(Manager):
def create_category(category, title):
t = Title.objects.get_or_create(title=title)
return self.create(title=t)
class Category(models.Model):
title = models.ForeignKey(Title, verbose_name="Title")
objects = CategoryManager()
Then use create_category every time you want to create a Category. | unknown | |
d7820 | train | In verilog all signals declared in module are only visible in this module. You have ports D and Q declared as input and output ports of module dff which is ok, but you are trying to use D and Q in firfilter module which doesn't know anything about D and Q from module dff. What you should do is put an instance of module dff in module firfilter and connect its ports to signals like this:
module firfilter(
input din,
input clock,
output dout
);
parameter b0 = 1'd1;
parameter b1 = 1'd1;
wire Q;
reg D;
// instance of dff module:
dff dff_inst(.D(D), .clock(clock), .Q(Q) );
assign dout = b0 - b1 * Q;
always@ (posedge clock)
D <= din;
endmodule
module dff (
input D,
input clock,
output reg Q
);
always@ (posedge clock)
Q <= #(1) D;
endmodule
Also you need to know that you cannot drive wire signals inside always blocks so I changed them to regs.
Pay more attention to code formatting as your snippet is barely readable. | unknown | |
d7821 | train | There are quite a few ways of doing this, but the easiest way, given the code you have supplied, is just to input the current $_GET['dl'] value. Like so:
<a href="index.php?dc=downloads&sort=id&dl=<?=$_GET['dl']?>" >id</a>
<?=$_GET['dl']?>: This will take the dl value that is currently in the get parameters and place it into your link.
A better method would probably be to check if there is already a dl value in the GET parameters first:
<? if(isset($_GET['dl']) && $_GET['dl'] != ''): ?>
<a href="index.php?dc=downloads&sort=id&dl=<?=$_GET['dl']?>">id</a>
<? else: ?>
<a href="index.php?dc=downloads&sort=id">id</a>
<? endif; ?>
This way, you wont end up with a link like index.php?dc=download&sort=id&dl= if dl hasn't yet been set. | unknown | |
d7822 | train | A for loop has the following structure:
for (initialization; condition; update)
The update is executed after every execution of the loop.
Therefore the following two loops are identical:
for (int i = 0; i < 10; i++) {
and
for (int i = 0; i < 10; ++i) {
A:
my question is should k not be 1 because its been pre-incremented?
The ++k happens at the end of the loop iteration, i.e. after the if statement.
It makes no difference whether it's ++k or k++; in either case the first value of k is zero.
So the answer they give is "Hello-1"
This is clearly incorrect, since counter is never incremented and stays at zero throughout the program.
A: k cannot be 1.
This is because when a for loop runs, it only updates after it has executed all the code within the loop. Since the loop breaks even before the first iteration is completed, k remains 0. | unknown | |
d7823 | train | When you do this:
this.$el.html( this.subView.render().el );
You're effectively saying this:
this.$el.empty();
this.$el.append( this.subView.render().el );
and empty kills the events on everything inside this.$el:
To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.
So you lose the delegate call that binds events on this.subView and the SubView#render won't rebind them.
You need to slip a this.subView.delegateEvents() call into this.$el.html() but you need it to happen after the empty(). You could do it like this:
render: function(){
console.log( "Composer.render" );
this.$el.empty();
this.subView.delegateEvents();
this.$el.append( this.subView.render().el );
return this;
}
Demo: http://jsfiddle.net/ambiguous/57maA/1/
Or like this:
render: function(){
console.log( "Composer.render" );
this.$el.html( this.subView.render().el );
this.subView.delegateEvents();
return this;
}
Demo: http://jsfiddle.net/ambiguous/4qrRa/
Or you could remove and re-create the this.subView when rendering and sidestep the problem that way (but this might cause other problems...).
A: There's a simpler solution here that doesn't blow away the event registrations in the first place: jQuery.detach().
http://jsfiddle.net/ypG8U/1/
this.subView.render().$el.detach().appendTo( this.$el );
This variation is probably preferable for performance reasons though:
http://jsfiddle.net/ypG8U/2/
this.subView.$el.detach();
this.subView.render().$el.appendTo( this.$el );
// or
this.$el.append( this.subView.render().el );
Obviously this is a simplification that matches the example, where the sub view is the only content of the parent. If that was really the case, you could just re-render the sub view. If there were other content you could do something like:
var children = array[];
this.$el.children().detach();
children.push( subView.render().el );
// ...
this.$el.append( children );
or
_( this.subViews ).each( function ( subView ) {
subView.$el.detach();
} );
// ...
Also, in your original code, and repeated in @mu's answer, a DOM object is passed to jQuery.html(), but that method is only documented as accepting strings of HTML:
this.$el.html( this.subView.render().el );
Documented signature for jQuery.html():
.html( htmlString )
http://api.jquery.com/html/#html2
A: When using $(el).empty() it removes all the child elements in the selected element AND removes ALL the events (and data) that are bound to any (child) elements inside of the selected element (el).
To keep the events bound to the child elements, but still remove the child elements, use:
$(el).children().detach(); instead of $(.el).empty();
This will allow your view to rerender successfully with the events still bound and working. | unknown | |
d7824 | train | It seems like you look for ActiveRecord::Base attr_readonly:
class Foo < ActiveRecord::Base
attr_readonly :bar
end
foo = Foo.create(bar: "first_value")
foo.bar
=> "first_value"
foo.update(bar: "second_value") #column `bar` ignored in SQL query
foo.bar
=> "first_value" | unknown | |
d7825 | train | *
*Your <textarea> doesn't have a name, so it can't be a successful control.
*You never attempt to access $_POST['Firstname'] (or $query_vars['Firstname] for that matter)
*Ditto $_POST['email']
Also your HTML is invalid (use a validator) and you are abusing the placeholder attribute as a label. | unknown | |
d7826 | train | Based on @GertArnold 's suggestion I looked a little closer at the main query that grabs the collection of users and tried to see if I could disable lazy loading. Because I was using a generic repository pattern and unit of work, I wasn't able to specifically disable it just for that call so I ended up using the context directly and everything behaved properly without disabling needed -- this breaks my pattern, but I now have the benefit of being able to use projection and save my application from eagerly loading unnecessary data columns.
If anyone can point me down the right path for implementing projection in a generic repository, I'd be greatful, but I can live with this alternative solution for now.
This msdn article also helped: https://msdn.microsoft.com/en-us/data/jj574232.aspx | unknown | |
d7827 | train | The problem in IE6 is probably due to negative margins on the views-field-title class (though I don't have IE6 installed to check).
You don't actually need negative margins to achieve the effect you want. So suggest removing them like this:
*
*Remove margin-left: -4px; from #left_cplist .cplist-bg .view-content .views-field-title
*Remove margin-left: 5px; form #left_cplist .cplist-bg .views-row | unknown | |
d7828 | train | For anyone come across this problem, I was able to get both secret key and public key the way it was retrieved in the google_recaptcha module as shown below.
variable_get('google_recaptcha')['public_key'];
variable_get('google_recaptcha')['secret_key']; | unknown | |
d7829 | train | Enabling Microsoft Defender for Key Vault does not require any agent or extension and is an Azure-native threat protection service, which detects unusual and potentially harmful access to Key Vault accounts. It provides an additional layer of security intelligence for the keys, secrets and certificates stored in the Microsoft Key Vault by alerting you to suspicious or malicious access. This layer of security allows you to address threats without being a security expert, and without the need to manage third-party security monitoring systems. Weβre not aware of any repercussions or similar you can find more information here : https://learn.microsoft.com/en-us/azure/defender-for-cloud/defender-for-key-vault-introduction | unknown | |
d7830 | train | You can get it with the following shell command (remove --partition parameter to get offsets for all topic's partitions):
./bin/kafka-run-class kafka.tools.GetOffsetShell --broker-list <host>:<port> --topic <topic-name> --partition <partition-number> --time -1
As you can see, this is using the GetOffsetShell [0] object that you may use to get the last message offset and compare it with record's offset.
[0] https://github.com/apache/kafka/blob/trunk/core/src/main/scala/kafka/tools/GetOffsetShell.scala | unknown | |
d7831 | train | We store an SQL script of the changes that are needed in git, with the branch that contains the changes.
This SQL script can be applied repeatedly to "fresh" copies of production data, verifying that it will work as expected.
It is our strong opinion that a focused DBA or Release Engineer should apply the changes, AFTER making appropriate backups and restoration measures.
--
Navicat MySQL is also an amazing tool for helping with that. Their schema diff tool is great for verifying changes, and even applying them. | unknown | |
d7832 | train | The short answer is, SSO-inside-an-installed-PWA is broken on Chrome for Desktop as of Chrome 70 (November 2018).
The good news is, the W3C web.manifest standard has changed, and will no longer require browsers to open out-of-scope navigation in a separate window. This will fix the case of installed PWAs with single-sign-on authentication. This will be fixed in Chrome 71 on the desktop (due December 2018), and is already fixed on Chrome for Android.
Here's the update to the W3C web.manifest spec that details the change. In short, the spec says browsers must not block out-of-scope navigation inside an installed PWA. Instead, the spec encourages browsers to show some prominent UI (perhaps a bar at the top) notifying the user that the navigation is out-of-scope.
"Unlike previous versions of this specification, user agents are no
longer required or allowed to block off-scope navigations, or open
them in a new top-level browsing context. This practice broke a lot of
sites that navigate to a URL on another origin..." | unknown | |
d7833 | train | There is no built-in way for searching, but I use a free addon Access Dependency Checker. It has many useful features, shows table/query structure, highlights a found field position and allows to open objects in design mode. | unknown | |
d7834 | train | The main things Validate Request is looking for are < and > characters, to stop you opening your site up to malicious users posting script and or HTML to your site.
If you're happy with the code you've got stripping out HTML mark-up, or you are not displaying the saved data back to the website without processing, then you should be ok.
A: Basically validating user input by replacing special characters usually cause more trouble and doesn't really solve the problem. It all depends what the user will input, sometimes they need the special characters like
& # < > " β % @ =
think about savvy users could still use xp_ command or even use CONVERT() function to do a ASCII/binary automated attack. As long as you parametrized all input, it should be ok.
A: i think that the problem is not only about SQL injection attacks, but about Cross Site Scripting and JS execution attacks.
To prevent this you cannot rely on parametrized queries alone, you should do a "sanitization" of the html the user sends! maybe a tool like html tidy could help. | unknown | |
d7835 | train | Looking into documentation on Taurus Console Reporter it is possible to amend only the following parameters:
modules:
console:
# disable console reporter
disable: false # default: auto
Β
# configure screen type
screen: console
# valid values are:
# - console (ncurses-based dashboard, default for *nix systems)
# - gui (window-based dashboard, default for Windows, requires Tkinter)
# - dummy (text output into console for non-tty cases)
dummy-cols: 140 # width for dummy screen
dummy-rows: 35 # height for dummy screen
If you can understand and write Python code you can try amending reporting.py file which is responsible for generating stats and summary table. This is a good point to start:
def __report_summary_labels(self, cumulative):
data = [("label", "status", "succ", "avg_rt", "error")]
justify = {0: "left", 1: "center", 2: "right", 3: "right", 4: "left"}
sorted_labels = sorted(cumulative.keys())
for sample_label in sorted_labels:
if sample_label != "":
data.append(self.__get_sample_element(cumulative[sample_label], sample_label))
table = SingleTable(data) if sys.stdout.isatty() else AsciiTable(data)
table.justify_columns = justify
self.log.info("Request label stats:\n%s", table.table)
Otherwise alternatively you can use Online Interactive Reports or configure your JMeter test to use Grafana and InfluxDB as 3rd-party metrics storage and visualisation systems. | unknown | |
d7836 | train | realurl is no longer supported. you have to use the new site be modul. or for extension: https://docs.typo3.org/typo3cms/extensions/core/Changelog/9.5/Feature-86365-RoutingEnhancersAndAspects.html | unknown | |
d7837 | train | In my experience, VS2008 can open VS2010 project files if there aren't VS2010-specific bits in it - so simple class libraries or console apps are fine, for example. There will be a warning that the tools version is unknown, but it will basically work. (You'll still need to target .NET 3.5, I believe - I haven't tried opening a .NET 4 project in VS2008, but I wouldn't really expect it to work, at least not if it uses new language features.)
Where I've used this approach, I've had two different solution files - one for VS2008 and one for VS2010, both including the same projects. That way both can open without any problems, and without any conversion prompts. So far it's worked fine.
As I say, that's my experience - YMMV.
A: I was able to open a project file created in VS2010 by simply opening it in VS2008. I was then able to go into Project Properties and set the target framework - just be sure to check the Build settings too, as 2010 is version 4, which isn't supported in 2008.
In my particular case, I targeted Framework v2.0, which involved removing unused LINQ references. The project compiled happily, and I was able to run the app.
A: No, the project file format has been extended. | unknown | |
d7838 | train | With your signature, the only thing you can do is:
void mymalloc_wrapper(size_t size) {
malloc(size);
}
Wonderful, you have allocated memory and you have lost the pointer to it. That's not a good idea.
If you want a void function, you can pass a pointer to return the pointer to allocated memory:
void mymalloc_wrapper(size_t size, void** ptr) {
*ptr = malloc(size);
} | unknown | |
d7839 | train | How about pure JS sort method:
var k=[{'type': 'apple', 'like': 7}, {'type': 'pear', 'like': 5},{'type': 'pear', 'like': 10}];
console.log(k.sort((a,b)=>a.like-b.like));
If you want to understand it better, read it here.
I hope this helps. Thanks!
A: You can directly do this in javascript in the following manner:
var my_arr = [{'type': 'apple', 'like': 3}, {'type': 'pear', 'like': 5}, {'type': 'pea', 'like': 7}, {'type': 'orange', 'like': 1}, {'type': 'grape', 'like': 4}]
console.log(my_arr)
my_arr.sort((a, b) => (a.like > b.like) ? 1 : -1)
console.log(my_arr)
where my_arr is the original array you were attempting to sort | unknown | |
d7840 | train | You can use for example:
Get-Variable -Name "A$i" |select Value
but it seems like a bad practice to use a variable for each file...
But you did not specify if you compare paths or files.
If files, combine with Get-Content.
UPDATE:
$i=1
while ($i -le 5)
{
$file1=Get-Content -Path $($(Get-Variable "A$i").Value)
$file2=Get-Content -Path $($(Get-Variable "B$i").Value)
foreach ($line1 in $file1)
{
$found = $false
foreach ($line2 in $file2)
{
if ($line1 -eq $line2)
{
write-host "Do something"
}
}
}
Remove-Variable "file1"
Remove-Variable "file2"
$i++
}
This is the version without Get-Content at every variable | unknown | |
d7841 | train | You can't do that for security reasons. Just imagine the possibilities. I enter a file by JavaScript in a hidden field. You press submit. I get your file. Any file. Terrifying, right?
A:
You can not select file in file uploader because of Browser security .
User can only do this not the script .
A: this script already upload the files to the server.. what you need is a way to get back the files name/id from the server and attach them to hidden form.. than when someone submit the form you will know which files he uploaded..
youd do this by listen to the onSuccess event..
A: For security reasons you can not dynamically change the value an input field of type file. If that were possible, a malicious user could set the value to say: "c:\maliciousfile" and harm your system
A: Looks like your question is two-part:
*
*How to dynamically add files to a form using JavaScript
1a. (I'll throw in a bonus - previewing images)
*How to perform an Ajax file upload
1 Dynamically adding files to a form
What you want to do here create an <input type="file"> field and change the form value by Javascript. You can hide the input using CSS display: none;.
As far as I know, this can only be done using the FileReader API and drag and drop, and the API is limited.
You can replace and remove all files from an input but you can't append or remove individual files.
The basic drag/drop file upload looks like this:
const dropZone = document.getElementById('dropzone');
const fileInput = document.getElementById('file-input');
dropzone.addEventListener('dragover', event => {
// we must preventDefault() to let the drop event fire
event.preventDefault();
});
dropzone.addEventListener('drop', event => {
event.preventDefault();
// drag/drop files are in event.dataTransfer
let files = event.dataTransfer.files;
fileInput.files = files;
console.log(`added ${files.length} files`);
});
.upload {
border: 1px solid #eee;
border-radius: 10px;
padding: 20px
}
.hidden {
opacity: 0.5;
}
<div id="dropzone" class="upload">Drop images here</div>
<input type="file" id="file-input" class="hidden" />
1a Previewing files
Working with Javascript opens up some fun options for form interactions, such as previewing uploaded files. Take for example an image uploader which can preview multiple drag-and-dropped images.
const imageTypeFilter = /image.*/;
const dropZone = document.getElementById('dropzone');
const fileInput = document.getElementById('file-input');
const previewContainer = document.getElementById('preview-container');
function generateImagePreview(file) {
const fileReader = new FileReader();
fileReader.addEventListener('load', event => {
// generate an image preview
let image = document.createElement('img');
image.classList.add('preview-image');
srcAttr = document.createAttribute('src');
srcAttr.value = fileReader.result;
image.setAttributeNode(srcAttr);
previewContainer.append(image);
}, false);
// open and read the file
fileReader.readAsDataURL(file);
}
function processFiles(files) {
previewContainer.innerHTML = "";
([...files]).forEach((file, index) => {
if (!file.type.match(imageTypeFilter)) {
console.error("Incorrect file type:");
console.log(file);
} else {
generateImagePreview(file);
}
});
}
dropZone.addEventListener('dragover', event => {
// required to fire the drop event
event.preventDefault();
});
dropZone.addEventListener('drop', event => {
event.preventDefault();
const files = event.dataTransfer.files;
fileInput.files = files;
processFiles(files);
});
fileInput.addEventListener('change', event => {
processFiles(event.target.files);
});
.upload {
border: 1px solid #eee;
border-radius: 10px;
padding: 20px
}
.preview-image {
max-width: 100px;
max-height: 100px;
}
.hidden {
opacity: 0.5;
}
<div id="dropzone" class="upload">
Drag images here
</div>
<input id="file-input" type="file" multiple accept="image/jpeg,image/png,image/gif" class="hidden" />
<div id="preview-container"></div>
2 Perform an AJAX upload when the user clicks the submit button.
In this case, you want to override the default the form submit event which I believe would look something like this:
const submitUrl = 'https://httpbin.org/post';
const form = document.getElementById('ajax-form');
form.addEventListener('submit', event => {
// this line prevents the default submit
event.preventDefault();
// convert the form into POST data
const serializedFormData = new FormData(event.target);
// use your favorite AJAX library
axios.post(
submitUrl,
serializedFormData
).then(response => {
console.log("success!");
}).catch(error => {
console.log("falied");
console.log(error.response);
});
});
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<form id="ajax-form" method="post" enctype="multipart/form-data">
<input type="text" name="name"/>
<input name="file" type="file" />
<button type="submit">Submit</button>
</form> | unknown | |
d7842 | train | ZF2 doesn't support YouTube like ZF1. However there is a module https://github.com/snapshotpl/ZfSnapGoogle to using Google APIs. | unknown | |
d7843 | train | Any .xls file can be saved as a XML Workbook ( File-Save As from Excel), which is an XML document. You can see that this an XML doc you open it in notepad.
Now, the trick is to get hands on the schema used for generating this, which is perhaps proprietary for microsoft and may not be given out. So, the workaround is, if your excel file is failrly simple, you can save it as the Workbook and see the XML and generate an XSD based on it.
Now, map your incoming XML to this Workbook XSD and the resultant XML will open directly in Excel, when you double-click on it.
Hope this helps.
A: in that case you need to developed a custom pipeline
biztalk-custom-excel-pipeline-component | unknown | |
d7844 | train | for TCP/UDP, you could use stream-route feature to support them.
TCP is the protocol for many popular applications and services, such as > > > LDAP, MySQL, and RTMP. UDP (User Datagram Protocol) is the protocol for many > popular non-transactional applications, such as DNS, syslog, and RADIUS.
APISIX can dynamically load balancing TCP/UDP proxy. In Nginx world, we call > TCP/UDP proxy to stream proxy, we followed this statement.
Please check https://apisix.apache.org/docs/apisix/stream-proxy | unknown | |
d7845 | train | Try to extract Error messages
getErrorMessage (ParseError p xs) = show p ++ concat $ map messageString xs | unknown | |
d7846 | train | You could use lockfiles in the filesystem. | unknown | |
d7847 | train | I am assuming you are using the MVVM pattern? In this case, you really shouldn't be programmatically making changes to your view!
Anyhow, you could handle the Loaded event, or the LayoutUpdated event (hard to determine which you need without more code). You can then navigate the visual tree, using my Linq-to-VisualTree for example, to navigate the elements in the view that was constructed - and make your changes. | unknown | |
d7848 | train | Inside the event handler, this refers to the clicked element. So you can do something like this:
$(".help-info-link").click(function(event){
event.preventDefault();
$(this).closest('.help-info').toggleClass('help-info-open');
$(this).toggleClass('help-info-link-open');
$(this).closest('.help-info').next('.help-info-text').toggle();
});
See here: http://jsfiddle.net/4q6b0gn4/
A: Instead of closest you could use the direct parent function, and a next function like i've done here:
http://jsfiddle.net/uq6xcdo5/1/
$(".help-info-link").click(function(event){
event.preventDefault();
$(this).parent().toggleClass('help-info-open');
$(this).toggleClass('help-info-link-open');
$(this).parent().next(".help-info-text").toggle();
}); | unknown | |
d7849 | train | It looks like you use bootstrap-select plugin.
After every DOM manipulation to select you need to use refresh method of selectpicker.
for (var key in result) {
if (result.hasOwnProperty(key)) {
var opt = document.createElement('option');
opt.innerHTML = result[key].contactName;
opt.value = result[key].id;
sel.appendChild(opt);
}
}
$('#userSelect').selectpicker('refresh'); | unknown | |
d7850 | train | You should return false from your .click() handler. But looking at your code there is something conceptually wrong with it. You call the .load method immediately after firing off your AJAX request without even waiting for this AJAX request to finish. Also there is very little point in invoking a controller action that does a redirect to another action using AJAX.
A: you can use request.Abort()
$(document).ready(function () {
$("#submit").click(function () {
var request = $.ajax({
type: "POST",
url: url,
data: $('#theForm').serialize()
});
$("#stlist").load('@Url.Action("KitsEdit","Spr")' + '?id=' + '@Model.sprid');
request.Abort()
});
}); | unknown | |
d7851 | train | You can use this c++ library wxwidgets. Add the path to xcode and it should work fine. | unknown | |
d7852 | train | first add the HH to be able to convert it to a pandas timedelta:
df['Time'] = '00:'+df['Time'].astype(str)
then convert to timedelta
df['Time'] = pd.to_timedelta(df['Time'])
then make a new column equal to sales per minute
df['Sales Rate'] = df['Sales'] / (df['Time'].dt.total_seconds()/60)
output:
Sales Time Sales Rate
Jame 603 00:14:59 40.2447
Sam 903 00:34:00 26.5588
Lee 756 00:34:55 21.6516
A: You could do the following if you have datetime dtype in time column:
s = '''Name Sales Time
Jame 603 14:59
Sam 903 34:00
Lee 756 34:55'''
df = (pd.read_csv(io.StringIO(s),
sep='\s+',
converters={'Time':lambda x: pd.to_datetime(x, format='%M:%S')})
)
df['rate'] = df['Sales'] / (df['Time'].dt.minute + df['Time'].dt.second.div(60)) | unknown | |
d7853 | train | You have to cache the original content into another object when the user presses the link, and then take it back when the user press the original link.
somethin like this (untested)
$('.load-page').on("click", function() {
var href = $(this).attr("href");
if ($('#hidden-cache').html() == ''){
$('#hidden-cache').html($('#in-the-news').html());
}
$('#in-the-news').load(href);
return false
});
$('.original-page').on("click", function() {
$('#in-the-news').html($('#hidden-cache').html());
return false
});
<div id="in-the-news" class="original-page">
<p>original content</p>
</div> | unknown | |
d7854 | train | py.test -> session scoped fixtures and their finalization should help you
You can use conftest.py to code your fixture. | unknown | |
d7855 | train | $db->loadObjectList() returns an array which you can't echo. You can create a foreach loop like so:
foreach ( $result as $row ) {
echo $row->description;
}
A: You have to load the results from the model method in view.html.php.
In view.html.php
function display($tpl = null) {
$model = JModelLegacy::getInstance('ModelName', 'FrontendModel'); //(or BackendModel)
$variable = $model->getNameOfModelMethod();
$this->assignRef('variable', $variable);
}
And in default.php just call $this->variable. | unknown | |
d7856 | train | The UIResponder Touches methods are returning coordinates in your UIViewController.view's coordinates, but you need to draw in your imageViews coordinates. UIView has multiple methods to help you with this. try this one:
myImageView.convert(fromPoint, from: view) | unknown | |
d7857 | train | In general "help me do my homework" will not be answered here - see https://softwareengineering.meta.stackexchange.com/questions/6166/open-letter-to-students-with-homework-problems
However, I think you might find the following enlightening - often these we know how to do these sorts of tasks ourselves, and (especially for a student) have trouble breaking down the steps. I suggest the following:
Find a friend, and do the procedure with him. I see from your code that you know the rough procedure. Just do it yourself - keep numbers on paper if you need to. Don't concentrate on HOW you're doing it, don't analyse it. Just do it. Then do it again, writing down the steps you took - don't use loops at this stage, and don't generalize it yet, just note it down - if you have an audio recorder, say the steps out loud, so you can concentrate on what you're doing practically, not the underlying code. Write it down, break it down into steps, look at what you've done, roll up the loops. Then write the code.
A: Anything other than "y" should work for response. I suggest setting it to none: response = None. See https://docs.python.org/2/library/constants.html for info about None. | unknown | |
d7858 | train | This might help you to get started:
function makeDoc(){
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('myDoc');
var vA=sh.getDataRange().getValues();
var name=vA[0][0];
var doc=DocumentApp.create(name);
var body=doc.getBody();
for(var i=1;i<vA.length;i++){
body.appendParagraph(vA[i][0]);
}
var root=DriveApp.getRootFolder();
var files=root.getFilesByName(name);
while(files.hasNext()){
var child=files.next();
}
var newFolder=DriveApp.getFolderById('finalFolderId');
newFolder.addFile(child)
root.removeFile(child);
} | unknown | |
d7859 | train | brew cask install <formula> is supposed to symlink your app in Applications automatically. | unknown | |
d7860 | train | true].
Is this the right way to access the values? What is the best way to retrieve only the checked checbox values?
2) Another question is, once I get the list of checked checkboxes values, how can I pass them to the contentCtrl.js that controls the content on right side?
A: You should inject the controller into the controller you want to use. The answer has already been answered here is the link.
How do I inject a controller into another controller in AngularJS | unknown | |
d7861 | train | To reduce queries, you can first query out your needed answers, and then fetch all related answerers,
answers = Answer.objects.select_related('answerer').filter(xxxx)
# fetch related user id's
userids_in_answer = [answer.answerer.id for answer in answers]
# fetch user ids
user_id_set = set(User.objects.filter(id__in=userids_in_answer).values('id', flat=True)
after that, you can easily know whether user exists by,
for answer in answers:
if answer.answerer.id in user_id_set:
xxx
The query num is reduced, you can check whether this helps.
A: In your view:
answered_ids = [ans.question_id for ans in Answer.objects.filter(answerer=request.user)]
In your template:
{% if not obj.id in answered_ids %}
# can answer
{% else %}
# cannot answer
{% endif %} | unknown | |
d7862 | train | General advice would be to make sure that any domain logic exists in your models, rather than the view.
Also, extract mark-up into partials if your views are getting too long.
You might also want to look at the MVVM pattern: http://en.wikipedia.org/wiki/Model_View_ViewModel | unknown | |
d7863 | train | It seems juliemr answers your question:
tests are sharded by file, not by scenario, so you'll need to split the scenarios into separate files.
https://github.com/angular/protractor/issues/864#issuecomment-45571006
So you'll need to split the scenarios into separate feature files and, if desired, set maxInstances to however many you want to run at once. For example:
capabilities: {
'browserName': 'chrome',
'shardTestFiles': true,
'maxInstances': 10
}
A: Add a hook after each scenario to close the browser:
this.After(function(scenario, done) {
this.quit(done);
}); | unknown | |
d7864 | train | It will be good if you convert the second array into MAP then you can easily complete your task.Key will be number and value will be text of array in MAP
A: Use a HashMap:
HashMap<String,String> hashMap = new HashMap<String,String>();
String[] string1 = {"5648", "4216", "3254", "2541", "10"};
String[] string2 = {"Derp: 10", "Herp: 3254", "peter: 2541", "jdp: 4216", "dieter: 5648"};
for (String str : string2)
{
String[] keyVal = str.split(": ");
hashMap.put(keyVal[1],keyVal[0]);
}
for (String key : string1)
{
String val = hashMap.get(key);
System.out.println(val+": "+key);
}
A: Using the Map is good solution.
for example:
Map<String, Integer> data = new HashMap<String, Integer>();
data.put("Herp", 3254);
data.put("peter", 2541);
//...
for (String name: data.keySet()) {
System.out.println(name + ": " + data.get(name) );
}
Yes, if this data is your input, collect the map as described in previous answer. But if possible, use the map initially. | unknown | |
d7865 | train | Well, it's not okay, you have syntax errors in your literal where you're creating the applyStaffDiscount property
voidLastTransaction : function(){
this.total -= this.lastTransactionAmount;
this.lastTransactionAmount = 0;
},
applyStaffDiscount(employee){
this.total -= (this.total * (employee.discountpercent/100));
}
Let's assume you where really trying to create a function, as you're trying to pass arguments and have parenthesis etc
voidLastTransaction : function(){
this.total -= this.lastTransactionAmount;
this.lastTransactionAmount = 0;
},
applyStaffDiscount : function(employee){
this.total -= (this.total * (employee.discountpercent/100));
} | unknown | |
d7866 | train | Following the rules of selection within d3.js (https://bost.ocks.org/mike/selection/) the code should look something like this:
svg_summ.selectAll("path")
.data(group_by_sailing_date)
.enter()
.append("path")
.attr("stroke", "steelblue")
.attr("fill", "none")
.attr("stroke-width", "1px")
.attr("d", (d) => valueline(d));
A: Ok, I've made it work, but I don't know why. I removed the .data(s) line, and changed "valueline" to "valueline(s)". No idea why this works. Technically, it's all good, but I'd be thrilled if someone could help me understand what this code actually means.
group_by_sailing_date.forEach(function (s) {
svg_summ.append("path")
.attr("stroke", "steelblue")
.attr("fill", "none")
.attr("stroke-width", "1px")
.attr("d", valueline(s));
}); | unknown | |
d7867 | train | As per your query filter and columns needed, please make index on respected columns.
By default SQL will create clustered index on your primary key, but you may create some other unclustered index on your table to make your execution faster.
You may find this link for your reference or Google it there are hundreds of article available on Internet for same.
"https://learn.microsoft.com/en-us/sql/t-sql/statements/create-index-transact-sql?view=sql-server-2017" | unknown | |
d7868 | train | I think spring boot automated this process completely. One doesn't have to inject the data source manually & connection pool mechanism is also automated. Just adding the connection properties and pool properties in yaml file or properties file under src/main/resources. It will inject the data source for you. | unknown | |
d7869 | train | Try loading images into imageview as bitmap
try {
File f=new File(filepath, "imagename.jpg"); // internal or external storage path
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
ImageView img=(ImageView)findViewById(R.id.imgPicker);
img.setImageBitmap(b);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
Hope this may work! | unknown | |
d7870 | train | Try to set modalPresentationStyle of the presenting view controller to UIModalPresentationCustom | unknown | |
d7871 | train | Try the following. Leave the NAs as they are
rowSums(M, na.rm=TRUE) / 2 - (is.na(L) + is.na(R))
## WHERE
M = cbind(IMILEFT, IMIRIGHT)
L = IMILEFT
R = IMIRIGHT
if you have rows were both columns are NA, then have the denominator be
pmin(1, 2 - (is.na(L) + is.na(R))) | unknown | |
d7872 | train | If you have associated your application with a particular file extension, it will be launched automatically when you double-click such a file (as you have said).
When this happens, your application is launched with the file name (actually the full path) supplied as a command line argument to your application.
In SDI MFC applications, this is handled automatically by the framework as long as you haven't overridden the default File/Open handling mechanism, but if you have a dialog-based application you will need to add code for this yourself.
A: Your dialog COpenImageDlg is created and displayed inside the call to DoModal before the command line has a chance to be processed. When the DoModal returns, the dialog is already destroyed, so there is no dialog for the code to draw upon.
A: I understand that when you double click the file to choose a image on file dialog, the image doesn't show. I just tried your code of function OnBnClickedButton1 and OpenImage1. And it turns out that the image is displayed when double click to choose a image. I use VS2010 on win7. I hope this will help you though i donot find the error of your code.
A: I found the answer to my question.
It was actually a very stupid mistake.
When I read the file address using Commandline, the address has single slash, whereas I need to pass the address using double slash.
Such a silly bug. Sorry to waste your time. | unknown | |
d7873 | train | Use caution, as you may need to further qualify the WHEN NOT MATCHED BY SOURCE.
For example, if the TARGET table has a column that the SOURCE does not .. and you are setting that target column during the aforementioned insert .. then you'll likely want to define that constraint:
WHEN NOT MATCHED BY SOURCE AND (TARGET.SomeColumn = yada)
A: WHEN NOT MATCHED BY TARGET - You should use this clause to insert new rows into the target table. The rows you insert into the table are those rows in the source table for which there are no matching rows in the target.
WHEN NOT MATCHED BY SOURCE - If you want to delete a row from the target table that does not match a row in the source table
A: Yow want to match target table with source table.at end your target table should be similar to source table
WHEN NOT MATCHED BY SOURCE : focus on SOURCE : there is some rows in target that you don't have any equivalent for it in source table. so you should delete it.
WHEN NOT MATCHED BY Target: focus on Target : there is some rows in Source that you don't have any equivalent for it in Target table. so you can insert them | unknown | |
d7874 | train | Yes, you need a different way, because of event-driven nature of Tkinter GUI programming. When some event lead you to your wait() function there it is: you're stuck in infinite loop, and you can't get outside with events anymore!
As @Bryan Oakley pointed - GUI is constantly in a waiting state by default, since you reached a mainloop(). And I think, that you trying just suppress all other events (or just navigate keys) when user navigating through a tree , except this two (Left and Right clicks).
So here is a small example:
import tkinter as tk
# Main - application
class App(tk.Tk):
# init of our application
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.minsize(width=450, height=100)
self.wm_title('Just another example from SO')
self.wait_state = False
self.init_events()
# switch state
def switch_wait_state(self, event):
self.wait_state = not self.wait_state
print('Wait state switched to: %s ' % self.wait_state)
# init events
def init_events(self):
self.bind('<Key>', self.wait)
self.bind('<Control-s>', self.switch_wait_state)
# waiter(listener) for keypress
def wait(self, event):
if self.wait_state and any(key == event.keysym for key in ['Left', 'Right']):
print('I have successfully waited until %s keypress!' % event.keysym)
self.do_smth(event.keysym)
else:
print('Wait state: %s , KeyPress: %s' % (self.wait_state, event.keysym))
self.do_nhth()
@staticmethod
def do_smth(side):
print("Don't be rude with me, Im trying my best on a %s side!" % side)
@staticmethod
def do_nhth():
pass
app = App()
app.mainloop() | unknown | |
d7875 | train | For anyone who might find this question later on: the problem was about having the right absolute path to your DB in your SQLALCHEMY_DATABASE_URI config value.
Also (this wasnt the case here, but it might possibly gotcha with the same symptoms) - if you omit __tablename__ on Model declaration, SQLAlchemy might autogenerate something you wont expect. Just a thing to keep in mind, if you're working with an existing DB with some schema already in place. | unknown | |
d7876 | train | When you use GLES 2.0 on devices you must be careful with indices. On many devices you cannot use int index. Every device supports unsigned short index. For render you must use:
GLushort indicies[] = { 0, 1, 2, 0, 2, 3 };
...
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, indicies); | unknown | |
d7877 | train | As you mentioned the page is loaded dynamically. Issue here is that you get the html prior the html tree you are looking for being part of the DOM.
driver = webdriver.Chrome()
driver.get('https://tracker.icon.foundation/addresses/1?count=100')
# Wait until the element is loaded (found)
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, '.table-box')))
#Parse the page_source
soup = BeautifulSoup(driver.page_source, 'lxml')
driver.quit()
box = soup.find('div', {'class': 'table-box'})
all_addresses = box.find_all('span', {'class': 'ellipsis'})
AddressList = []
for address in all_addresses:
a_type = address.find('a', {'class': 'on'}).text
AddressList.append(a_type)
print(AddressList)
Output:
['hxcd6f04b2a5184715ca89e523b6c823ceef2f9c3d', 'hx9f0c84a113881f0617172df6fc61a8278eb540f5', 'hx1729b35b690d51e9944b2e94075acff986ea0675', 'hx562dc1e2c7897432c298115bc7fbcc3b9d5df294', 'hx68646780e14ee9097085f7280ab137c3633b4b5f', 'hx0cc3a3d55ed55df7c8eee926a4fafb5412d0cca4', 'hx9d9ad1bc19319bd5cdb5516773c0e376db83b644', 'hxa9c54005bfa47bb8c3ff0d8adb5ddaac141556a3', 'hxc1481b2459afdbbde302ab528665b8603f7014dc', 'hx3f945d146a87552487ad70a050eebfa2564e8e5c', 'hx6b38701ddc411e6f4e84a04f6abade7661a207e2', 'hx7062a97bed64624846f3134fdab3fb856dce7075', 'hx8913f49afe7f01ff0d7318b98f7b4ae9d3cd0d61', 'hx980ab0c7473013f656339795a1c63bf44898ce95', 'hxbc2f530a7cb6170daae5876fd24d5d81170b93fe', 'hxc17ff524858dd51722367c5b04770936a78818de', 'hxfc7888bf63d45df125cf567fd8753c05facb3d12', 'hxd3b53e10d8c4c755879be09ff9ba975069664b7a', 'hxdf6bd350edae21f84e0a12392c17eac7e04817e7', 'hx9e19d60c9d6a0ecc2bcace688eff9053622c0c4c', 'hxa527f96d8b988a31083167f368105fc0f2ab1143', 'hx1000000000000000000000000000000000000000', 'hx294c5d0699615fc8d92abfe464a2601612d11bf7', 'hxd42f6e3abfb7f5b14dbdafa34f03ffecf2a53a92', 'hxe322ab9b11b63c89b85b9bc7b23350b1d6604595', 'hx87b6da94535754c2baee9d69010eb1b91eaa4c37', 'hx58b2592941f61f97c7a8bed9f84c543f12099239', 'hx8d6aa6dce658688c76341b7f70a56dce5361e7ef', 'hx930bb66751f476babc2d49901cf77429c5cf05c1', 'hx39f2636582cee00b72586a2f74dc6028c0f0213f', 'hxd9fb974459fe46eb9d5a7c438f17ae6e75c0f2d1', 'hx49c5c7eead084999342dd6b0656bc98fa103b185', 'hx76dcc464a27d74ca7798dd789d2e1da8193219b4', 'hxc05ec08b6446a2a16b64eb19b96ea02225b840ab', 'hxe295a8dc5d6c29109bc402e59394d94cf600562e', 'hxf6f5f2583a0821f281fe7d35b013b9389daf2aaa', 'hxb6a65d0e7d5c1c0150310287e97c612a8ac825eb', 'hx6d14b2b77a9e73c5d5804d43c7e3c3416648ae3d', 'hxeb00139ddd1fa4507d3158e46e22c4ab7e8b9202', 'hx538de7e0fc0d312aa82549aa9e4daecc7fabcce9', 'hx6eb81220f547087b82e5a3de175a5dc0d854a3cd', 'hxc4193cda4a75526bf50896ec242d6713bb6b02a3', 'hx266c053380ad84224ea64ab4fa05541dccc56f5f', 'hx476455c56c64fea4f425bd62f0d2d3ab8cdcace0', 'hx85532472e789802a943bd34a8aeb86668bc23265', 'hx56ef2fa4ebd736c5565967197194da14d3af88ca', 'hx5d0409cabaacd0f1ef22d32f41a30649ee990103', 'hxbf90314546bbc3ed980454c9e2a9766160389302', 'hxe07878b53679ba1278d0aab1dac7646d8898d344', 'hx96505aac67c4f9033e4bac47397d760f121bcc44', 'hx18d14ad97ab2903dfc246ccc4e5631a3a1e13141', 'hx39f24d1d23b710b9d6ef6f56acfb3022deed8f4d', 'hxc574629fa3d1cc846611f1ab91d504ad7fc35413', 'hxd7a34c15c2345d9f0891545350181c7b162d9e08', 'hx314348ecbaf01ff6c65c2877a6c593a5facecb35', 'hx23cb1d823ef96ac22ae30c986a78bdbf3da976df', 'hx307c01535bfd1fb86b3b309925ae6970680eb30d', 'hx206846faa5ba46a3717e7349bff9c20d6fe1bba3', 'hx161665fb51075d37cee2c98c2eacbc94d207a58b', 'hxaf3a561e3888a2b497941e464f82fd4456db3ebf', 'hxa55446e81997c03ee856a58ee18432325a4ef924', 'hx6607ef84572ac9bdb1ebbcf49bd0cddaf8903b8e', 'hx37f86d0a4e1e2fada3ca724a401037c83e0a670e', 'hxc4bb0a9c4b3e9e5953262aa7cb940dbecb568ff6', 'hxc39a4c8438abbcb6b49de4691f07ee9b24968a1b', 'hxc35567f68c43bd98b020e5f0fab69ca21edb2726', 'hxc0fc3fca32bddba77f372c69c5998c1da81d531d', 'hx25c5dace83bceae42c11360a07c9e42a3b5c6122', 'hx387f3016ee2e5fb95f2feb5ba36b0578d5a4b8cf', 'hx94a7cd360a40cbf39e92ac91195c2ee3c81940a6', 'hx748717b9f846120033ba44e986722d82ef710afb', 'hxebfc6198ce53846b2e5d4ef31d6d13d0fa951c01', 'hx4602589eb91cf99b27296e5bd712387a23dd8ce5', 'hxa67e30ec59e73b9e15c7f2c4ddc42a13b44b2097', 'hx558b4cd8cd7c25fa25e3109414bb385e3c369660', 'hxad2bc6446ee3ae23228889d21f1871ed182ca2ca', 'hx777ee46b7b9d90a26388fbcdeafc742f5f217af7', 'hx10ed7a7065d920e146c86d3915491f5a67248647', 'hx33fc29d457e7815fe6c7cec4304500d5214fdac1', 'hx1494e29d38aea1a8e39fb40663c37f714bffb9df', 'hx9db3998119addefc2b34eaf408f27ab8103edaef', 'hxa91a8cd8141d192f78540d092d912456fb81d281', 'hx0b047c751658f7ce1b2595da34d57a0e7dad357d', 'hxc0b37fc42b52bf467720cf362c87c650ae3a7915', 'hx1216aa95cf2aea0a387b7c243412022f3d7cf29f', 'hx4c7c152410d4defd66da1d6c399c01de0bc295a5', 'hx4d83813703f81cdb85f952a1d1ee736faf732655', 'hx6d2240f9c5fd0db5df6977ee586c3d74e1b1e4aa', 'hxaafc8af9559d5d320745345ec006b0b2170194aa', 'hxabdde23cda5b425e71907515940a8f23e29a3134', 'hx6c22cdba886614d3173e3d2499dc1597bdb57f2c', 'hxd8ba6317da2eec0d9d7d1feed4c9c1f3cf358ae1', 'hxdd4bc4937923dc140adba57916e3559d039f4203', 'hx27664cffd284b8cf488eefb7880f55ce82f42297', 'hx8243caf740598c2b8d57c177adc999da68ea46bf', 'hx230fdd2eb239d5f590c7ff2d94a32b8899fc0628', 'hxd3f062437b70ab6d6a5f21b208ede64973f70567', 'hxc41d0b098fe9b86b241dfbfa9741f00975db2847', 'hxed97cf0deba62ffe843262f7f4596e155e8ea0b9', 'hx8d45deb8de633ca9d5de5fc5a64c51bccd8e9960']
Note you will need the following additional imports:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
For your other question about performance, you might use an headless browser which will speed things up a bit.
options = webdriver.ChromeOptions()
options.add_argument('--headless')
driver = webdriver.Chrome(options=options)
A: The data is loaded dynamically, therefore requests won't support it. However, we can get the data via sending a GET requests to
https://tracker.icon.foundation/v3/address/list?page=<PAGE NUM>&count=100
To get all the data from pages 1-100, we can use the range() function
import requests
url = "https://tracker.icon.foundation/v3/address/list?page={}&count=100"
for page in range(1, 101):
print("URL: ", url.format(page))
response = requests.get(url.format(page)).json()
print([data["address"] for data in response["data"]], "\n")
Output (partial):
URL: https://tracker.icon.foundation/v3/address/list?page=1&count=100
['hxcd6f04b2a5184715ca89e523b6c823ceef2f9c3d', .... 'hx8d45deb8de633ca9d5de5fc5a64c51bccd8e9960']
...
... | unknown | |
d7878 | train | BEGIN TRANSACTION
update person set Address1 = Address2, Address2 = null
where Address1 is null and Address2 is not null;
update person set Address2 = Address3, Address3 = null
where Address2 is null and Address3 is not null;
update person set Address1 = Address2, Address2 = null
where Address1 is null and Address2 is not null;
select top 100 * from person
ROLLBACK TRANSACTION
This would get very ugly if you had lots of address fields, but for 3 is acceptable. Remember to test any script copy and pasted from the interwebs in a transaction that you rollback so you don't get your database wiped :)
EDIT:
With further info (6 address fields):
You could do like above only repeat 5 times to move so in worst case you where still done
Declare StoredProcedure OneRound
BEGIN
update person set Address1 = Address2, Address2 = null
where Address1 is null and Address2 is not null;
update person set Address2 = Address3, Address3 = null
where Address2 is null and Address3 is not null;
update person set Address3 = Address4, Address4 = null
where Address3 is null and Address4 is not null;
update person set Address4 = Address5, Address5 = null
where Address4 is null and Address5 is not null;
update person set Address5 = Address6, Address6 = null
where Address5 is null and Address6 is not null;
END
Declare StoredProc FixAllAddresses
BEGIN
call OneRound
call OneRound
call OneRound
call OneRound
call OneRound
END
You could also use a cusor (warning psydo code) I have not looked up the syntax for T-SQL cursors and it has been a while so I will get the details wrong, check the syntax in the online help.
Declare cursor @personCursor for select ID,Address1,Address2,... from person;
OPEN @personCursor
FETCH @personCursor into (@personID, @addr1, @addr2, @addr3...)
while(@@FETCH_STATUS)
BEGIN
IF @addr1 is null
BEGIN
IF @addr2 is not null
BEGIN
@addr1 = @addr2
@addr2 = null
END
ELSE IF @addr3 is not null
@addr1 = @addr3
@addr3 = null
BEGIN
-- Boaring, ugly code goes here for addr4,addr5,addr6
END
END
IF @addr2 is null
IF @addr3 is not null
BEGIN
@addr2 = @addr3
@addr3 = null
END
ELSE IF @addr4 is not null
@addr2 = @addr4
@addr4 = null
BEGIN
-- Boaring, ugly code goes here for addr5, addr6
END
BEGIN
-- repeat for addr3, addr4,
if @addr5 is null
BEGIN
IF addr6 is not null
BEGIN
@addr5 = @addr6
@addr6 = null
END
END
END
update person set address1 = @addr1, address2 = @addr2, ...
where PersonId = @personId
FETCH @personCursor into (@personID, @addr1, @addr2, @addr3...)
END
The Stored proc begin called 5 times makes for less code and may be less error prone, the cursor only iterates through your people once, but does not filter. I suspect the stored proc solution below will be faster but it will depend on your data.
A: David's solution is the most efficient. One that might be more easily extend-able for greater numbers of columns is.
;WITH cte
AS (SELECT *,
MAX(CASE WHEN RN=1 THEN value END) OVER (PARTITION BY ContactId) AS new_Address1,
MAX(CASE WHEN RN=2 THEN value END) OVER (PARTITION BY ContactId) AS new_Address2,
MAX(CASE WHEN RN=3 THEN value END) OVER (PARTITION BY ContactId) AS new_Address3
FROM #Addresses
OUTER APPLY (SELECT ROW_NUMBER() OVER (ORDER BY CASE WHEN value IS NULL THEN 1 ELSE 0 END, idx) AS
RN, idx, value
FROM (VALUES(1,Address1),
(2,Address2),
(3,Address3)) t (idx, value)) d)
UPDATE cte
SET Address1 = new_Address1,
Address2 = new_Address2,
Address3 = new_Address3 | unknown | |
d7879 | train | what is the correct syntax to define the get methode for std::vector outside the class ?
That would be to just declare it in the class template and then go ahead and define it outside:
struct s {
template < class X >
void get (X x) {
cout << "inner\n";
}
template <class X> // declaration
void get(std::vector<X> v);
};
template <class X> // definition
void s::get(std::vector<X> v) {} | unknown | |
d7880 | train | I just wanted to thank everyone who helped. I am going to just stick with my initial solution of filter, copy, paste, filter, delete, filter, copy, paste, sort.
See my first code block for what I am talking about. Cheers. | unknown | |
d7881 | train | The code that solved the question:
const removeImagesFromBody = (event) => {
const item = Office.context.mailbox.item;
const type = Office.CoercionType.Html;
item.body.getAsync(type, (result) => {
let body = result.value;
let match;
const regex1 = new RegExp('v:shapes="([^"]+)"', 'gi');
while ((match = regex1.exec(result.value)) !== null) {
const regex2 = new RegExp(`<v:shape id="${match[1]}"[^]*?</v:shape>`, 'gi');
body = body.replace(regex2, '');
}
body = body.replace(/<img [^>]*>/gi, '');
item.body.setAsync(body, { coercionType: type }, () => {
event.completed({ allowEvent: true });
});
});
} | unknown | |
d7882 | train | Add another parameter your pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'search' })
export class SearchPipe implements PipeTransform {
transform(value: any, q?: any,colName: any="EmpName"): any {
if(!value) return null;
if(!q) return value;
q = q.toLowerCase();
return value.filter((item)=> {
return item[colName].toLowerCase().includes(q);
});
}
}
home.component.html
<tr *ngFor="let employe of employee | search:query:selected | paginate: { itemsPerPage: 10, currentPage: p }" > | unknown | |
d7883 | train | filtered_cols = parsed_data.map(lambda x: x[1])
model = KMeans.train(filtered_cols, 3, maxIterations=10, runs=10, initializationMode="random")
centers = model.clusterCenters
for center in centers: print(center) | unknown | |
d7884 | train | Try this:
+ (NSString *) displayPropertyName:(NSString *) propConst{
if ([propConst isEqualToString:@"_$!<Anniversary>!$_"]) return @"anniversary";
if ([propConst isEqualToString:@"_$!<Assistant>!$_"]) return @"assistant";
if ([propConst isEqualToString:@"_$!<AssistantPhone>!$_"]) return @"assistant";
if ([propConst isEqualToString:@"_$!<Brother>!$_"]) return @"brother";
if ([propConst isEqualToString:@"_$!<Car>!$_"]) return @"car";
if ([propConst isEqualToString:@"_$!<Child>!$_"]) return @"child";
if ([propConst isEqualToString:@"_$!<CompanyMain>!$_"]) return @"company main";
if ([propConst isEqualToString:@"_$!<Father>!$_"]) return @"father";
if ([propConst isEqualToString:@"_$!<Friend>!$_"]) return @"friend";
if ([propConst isEqualToString:@"_$!<Home>!$_"]) return @"home";
if ([propConst isEqualToString:@"_$!<HomeFAX>!$_"]) return @"home fax";
if ([propConst isEqualToString:@"_$!<HomePage>!$_"]) return @"home page";
if ([propConst isEqualToString:@"_$!<Main>!$_"]) return @"main";
if ([propConst isEqualToString:@"_$!<Manager>!$_"]) return @"manager";
if ([propConst isEqualToString:@"_$!<Mobile>!$_"]) return @"mobile";
if ([propConst isEqualToString:@"_$!<Mother>!$_"]) return @"mother";
if ([propConst isEqualToString:@"_$!<Other>!$_"]) return @"other";
if ([propConst isEqualToString:@"_$!<Pager>!$_"]) return @"pager";
if ([propConst isEqualToString:@"_$!<Parent>!$_"]) return @"parent";
if ([propConst isEqualToString:@"_$!<Partner>!$_"]) return @"partner";
if ([propConst isEqualToString:@"_$!<Radio>!$_"]) return @"radio";
if ([propConst isEqualToString:@"_$!<Sister>!$_"]) return @"sister";
if ([propConst isEqualToString:@"_$!<Spouse>!$_"]) return @"spouse";
if ([propConst isEqualToString:@"_$!<Work>!$_"]) return @"work";
if ([propConst isEqualToString:@"_$!<WorkFAX>!$_"]) return @"work fax";
return @"";
}
A: Tried using ABAddressBookCopyLocalizedLabel?
Something like:
ABAddressBookRef ab = ABAddressBookCreate();
ABRecordID personID = <someid>;
CFIndex phoneNumberIndex = <anIndexFromSomewhere>;
ABRecordRef person = ABAddressBookGetPersonWithRecordID(ab, personID);
CFStringRef name = ABRecordCopyCompositeName(person);
ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
CFStringRef number = ABMultiValueCopyValueAtIndex(phoneNumbers, phoneNumberIndex);
CFStringRef label = ABMultiValueCopyLabelAtIndex(phoneNumbers, phoneNumberIndex);
CFStringRef localizedLabel = ABAddressBookCopyLocalizedLabel(label);
NSLog(@"Person: %@", name);
NSLog(@"%@ : %@", localizedLabel, number);
CFRelease(label);
CFRelease(localizedLabel);
CFRelease(number);
CFRelease(phoneNumbers);
CFRelease(name);
CFRelease(ab);
A: You'll have to detect labels with the suffix and prefix. Then do a substring to get the label.
The values you're getting are the correct label of the strings in the address book database. They're just polished up a bit before presentation to the user. That's all.
A: In the newer Contacts framework, you have a class function
Here is the example in swift 4
let emailValue: CNLabeledValue<NSString> = ...
let label = emailValue.label ?? ""
let prettyLabel = type(of: emailValue).localizedString(forLabel: label)
This changes "_$!<Work>!$_" to "work"
Even better you can make an extension
extension CNLabeledValue {
@objc func prettyLabel() -> String? {
if let label = label {
return type(of: self).localizedString(forLabel: label)
}
return nil
}
}
And now you have even more simple call
let emailValue: CNLabeledValue<NSString> = ...
let prettyLabel = emailValue.prettyLabel() | unknown | |
d7885 | train | The problem is the flexbox, it breaks because your div doesnt have the properties it needs.
.MuiGrid-grid-xs-12 {
flex-grow: 0;
max-width: 100%;
flex-basis: 100%;
}
Adding this to the div will have the same result like giving the Grid the style property directly.
But the left,right and top border will be outside of the view, because of the .MuiGrid-spacing-xs-3 class.
.MuiGrid-spacing-xs-3 {
width: calc(100% + 24px);
margin: -12px;
}
Depending on your needs use a different spacing like 0 for normal 100% width without margin and at it yourself.
A: I don't know what you expect as result, but you can do is add width:100% to your div.
Another option would be to add the same classes a Grid has, that would be MuiGrid-root MuiGrid-item MuiGrid-grid-xs-12
Result:
option 1 <div style={{ border: "4px double black", width: '100%' }}>
options 2 <div className="MuiGrid-root MuiGrid-item MuiGrid-grid-xs-12" style={{ border: "4px double black" }}>
A: Just add your border styles to classes.paper
It seems from your example that you can just add the border to the paper inside the grid element to get the desired style.
paper: {
padding: theme.spacing(2),
textAlign: "center",
color: theme.palette.text.secondary,
border: "4px double black"
}
If you want multiple classes on an element, use string interpolation:
<Paper className={`${classes.paper1} ${classes.paper2}`}> | unknown | |
d7886 | train | If you look at the gist provided in the article
https://gist.github.com/josiahcarlson/80584b49da41549a7d5c
There is comment which asks
In over_limit_sliding_window_lua_, should
if old_ts > now then
at here be
if old_ts > saved.block_id then
And I agree to this, the old_ts is supposed to have the bucket and when the bucket jumps to the next slot, that is when old_ts will be greater then than the block_id | unknown | |
d7887 | train | getItems is a redux action, you need to call it in dispatch
dispatch(getItems()) | unknown | |
d7888 | train | I guess your start_date column has the DATETIME or the TIMESTAMP data type. If that isn't true, please update your question.
There's a common trap in date-range processing in all kinds of SQL, due to the fact that when you compare a pure DATE with a DATETIME, they hardly ever come out equal. That's because, for example, DATE('2011-07-1') means the same thing as 2011-07-01 00:00:00.
So you need
start_date >= '$start_date_start'
AND start_date < '$start_date_end' + INTERVAL 1 DAY
instead of what you have, which is
start_date BETWEEN '$start_date_start%' AND '$start_date_end%' /*wrong!*/
The second clause with the < ... + INTERVAL 1 DAY picks up all possible times on the last day of your interval.
Edit Now that you've disclosed that you have two DATETIME columns, called start_date and end_date, it sounds like you're looking for items which start on or before a specific date, and end on or after that same date. Try something like this:
WHERE DATE(start_date) <= DATE('$specific_date')
AND DATE(end_date) >= DATE('$specific_date')
The trick on queries like this is to spend the majority of your time thinking through and specifying the results you want. If you do this, the SQL is often perfectly obvious. | unknown | |
d7889 | train | You can use splice and join like:
function customSplit(str, splitter, max) {
let res = str.split(splitter);
if(max < res.length)
res.push(res.splice(max - 1).join(splitter));
return res;
}
console.log(customSplit('Billy Bob Joe', ' ', 2));
console.log(customSplit('a b c d e f g h', ' ', 4));
A: Try something like this (run code snippet to see result):
var base_str = 'Billy Bob Joe whatever';
//try here limit 1 , 2, 3 and see console.log result
var base_split = base_str.split(' ',2);
var second_str = base_split.join(' ');
var second_split = base_str.split(second_str);
base_split.push(second_split[1].trim());
console.log(base_split);
A: Here is what I came up with, but it's not super optimized
function explode(del, str, limit) {
let items = str.split(del), r = []
for(let i = 0; i < limit - 1; i++){ r.push(items.shift()) }
r.push(items.join(' '))
return r
}
console.log(explode(' ', 'Billy Bob Joe', 2));
console.log(explode(' ', 'a b c d e f g h', 4));
A: You can create a function that will create a regex string matching the number of words passed as an argument.
const buildRegexString = function(numWords) {
let regexStr = '^'
for (let i = 1; i < numWords; i++) {
regexStr += '(\\S+)\\s';
}
regexStr += '(.*)';
return regexStr;
}
const input = 'Billy Bob Joe Ringo George';
const regex = new RegExp(buildRegexString(3));
const match = input.match(regex);
const result = match.slice(1);
console.log(result);
A: I think you can't do that using split function
you can use
var str = "Billy Bob Joe";
var res = str.split(" ",1);
str=str.replace(res,'');
Now str have Bob Joe | unknown | |
d7890 | train | When you get an exception and you don't understand what's causing it, a good first step is to isolate exactly where it is happening. There are a lot of things happening in that one line of code, so it's difficult to know exactly what operation is causing the error.
Seeing the full stack trace of the exception might help, since it would give an idea of where you are in the execution path when the exception occurs.
However, a simple debugging technique is to break that one line with many operations into many lines with fewer operations, and see which line actually generates the exception. In your case this might be something like:
Object o = request.getAttribute("testVal");
String s = (String) o;
boolean b = Util.parseBoolean( s, false )
If the cause suggested by Shivan Dragon is correct, then the exception would occur on the second of these three lines.
A: Most likely this code: request.getAttribute("testVal") returns a Boolean, which cannot be cast to String, hence the (runtime) exception.
Either:
*
*check for code that populates the request attribute "testVal" with the boolean value (something like request.setAttribute("testVal", Boolean.FALSE)) and replace the value with a String
or
*
*Don't cast the value to String in your code, and don't use what seems to be a utility class for building a boolean value out of a String (*)
(*) which, btw, the Boolean class can do all by its lonesome self, no need to make your own library for that:
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Boolean.html#valueOf(java.lang.String) | unknown | |
d7891 | train | Why not just write the code for it?
var listOfA = new List<A>();
var listOfB = new List<A>();
... // Code for adding values
listOfA.ToC(listOfB);
public static class OuterJoinExtension
{
public static List<C> ToC(this List<A> listOfA, List<B> listOfB)
{
var listOfC = new List<C>();
listOfA.ForEach(a => listOfB.ForEach(b =>
{
if (b.JoinId == a.JoinId)
{
listOfC.Add(new C { Id = a.Id, JoinId = b.JoinId, Name = b.Name });
}
}));
return listOfC;
}
}
A: For simplicity I'll assume these are contained within another class:
class Original
{
List<ClassA> ClassAs { get; set; }
List<ClassB> ClassBs { get; set; }
}
class Result
{
List<ClassC> ClassCs { get; set; }
}
You can map the former to the latter using
Mapper.CreateMap<Original, Result>().ForMember(x => x.ClassCs,
x => x.MapFrom(x.ClassAs.Join(
y.ClassBs,
xEntry => xEntry.JoinId,
yEntry => yEntry.JoinId,
(xEntry, yEntry) => new ClassC {
Id = xEntry.Id,
Name = yEntry.Name,
JoinId = xEntry.JoinId}); | unknown | |
d7892 | train | If you have some patience (about 50s worth), you'll see that you do get one line of output and that line will be "1\n". You have two problems:
*
*count is using buffered output. This means that nothing will show up in your stdin until count's output buffer is full; given the small number of bytes that you're printing, the buffer won't be flushed until count finishes.
*Your popen block is only looking for one line.
You can solve the first one by using STDOUT.sync = true to turn off the output buffering in count:
STDOUT.sync = true
for i in 1..50 do
STDOUT.puts i
sleep 1
end
Then in your popen, you can iterate over the lines using each:
IO.popen("count","r+") { |fp| fp.each { |line| puts line } }
Then you should one line of output showing up each second. | unknown | |
d7893 | train | I'm happy to say that I've forgotten how SourceSafe works, but Subversion has an export feature that will copy the current version of all files. You can also set up commit hooks that will perform tasks whenever someone commits changes. | unknown | |
d7894 | train | You could use @keyframes animation and nested styles in SCSS to achieve something like this without javascript. Not sure if you're wanting to go this route, but it seems the most straightforward to me.
Particularly you're looking to set the animation-iteration-count to infinite on the elements that you want to rotate.
The below code is just some rough concept stuff, not sure the animation you're looking to set, or the full context of your elements, etc.
.logoSvg {
&:hover {
&:first-child {
animation-name: someAnimation;
animation-iteration-count: infinite;
}
&:last-child {
animation-name: someAnimation;
animation-iteration-count: infinite;
}
}
}
@keyframes someAnimation {
0%: {transform: some transformation};
100%: {transform: some transformation};
}
I hope this is helpful Chris, or at least gets you going in the right direction.
A: The rollover code itself looks ok (assuming missing code is, if you still get stuck I would put up a jsfiddle or jsbin), it's just applying to the wrong type of elements.
I'm guessing you are using jquery for the selections? If so, I'm not sure that will work..rather than doing..
var logo = $("#logoSvg");
try
var logo = Snap("#logoSvg");
That way you will get the Snap element (which links to the DOM element) to operate on, not a DOM or jquery object.
You can't transform the 'svg' element itself typically (as it doesn't technically support the transform attribute as far as I'm aware).
So, I would put the two svgs you want to transform inside a g/group element and transform that g element. You could look into css, but css transforms on svg don't always play nice regarding browser support, so whilst Davids answer may be good for normal elements, I'm not sure it would play nice for svg elements (especially rotations), do test different browsers very early if you do try that method. | unknown | |
d7895 | train | (Gathered from the now removed comments)
I have tried myself to build myself v4.14.78 followed by the latest available v4.14.214. I have found that former fails while the latter builds. So, I have bisected down to v4.14.116 that first builds correctly. Then I simple looked into the changes and found commit 760f8522ce08 ("selinux: use kernel linux/socket.h for genheaders and mdp") in the Linux stable tree which fixes the issue.
You may try to cherry-pick it to your branch and compile again. | unknown | |
d7896 | train | Here is a simple recursive function which solves the problem
def getValue(dict, keys):
if len(keys) == 1:
return dict.get(keys[0])
return getValue(dict.get(keys[0]), keys[1:])
And an iterative approach if you're boring
temp = data
for key in key_to_get:
temp = temp.get(key)
print(temp) | unknown | |
d7897 | train | There is only one method. You have to reorder your array
foreach($thearray as $key=>$item) {
$items[$item->catid][] = $item;
}
foreach($items AS $catid => $cat_items) {
echo '<h3>'.$catid.'</h3>';
foreach($cat_items AS $item)
echo $item->name.'<br>';
}
Something like this. | unknown | |
d7898 | train | You should definitely not use single variables for each country. Instead use an array.
This can be done in multiple flavors:
*
*Use a VLA matching your list of names:
...
int lencountry = sizeof(countrylist)/sizeof(countrylist[0]);
int countrycounts[lencountry]; // VLA cannot be initialized
for (int i = 0; i<lencountry; i++)
{
countrycounts[i] = 0;
}
Then you can simply increment the corresponding index in that array:
if(!strcmp(countrylist[i], s[j]))
{
countrycounts[i]++;
}
*Use a struct and store counter together with names.
typedef struct {
const char *name;
int count;
} country_t;
country_t countrylist[] = {
{ .name = "Laotian / Lao"},
{ .name = "Afghanistan"},
{ .name = "Albania"},
...
{ .name = "Zambia"},
{ .name = "Zimbabwe"}
};
The remaining fields (here: count) in the struct are automatically initialized to 0 if not all fields are specified.
Then you can compare like this:
if(!strcmp(countrylist[i].name, s[j]))
{
countrylist[i].count++;
} | unknown | |
d7899 | train | You need to use Recursive CTE
;WITH DATA
AS (SELECT *
FROM (VALUES ('ALI','ABU'),
('JOSH','LIM'),
('JAMES','KAREN'),
('LIM','JERRY'),
('JERRY','GEM')) TC(EMP_ID, EMP_L1)),
REC_CTE
AS (SELECT EMP_ID,
EMP_L1,
Cast(EMP_L1 AS VARCHAR(8000)) AS PARENT,
LEVEL = 1
FROM DATA
UNION ALL
SELECT D.EMP_ID,
D.EMP_L1,
Cast(RC.PARENT + '.' + D.EMP_L1 AS VARCHAR(8000)),
LEVEL = LEVEL + 1
FROM DATA D
JOIN REC_CTE RC
ON RC.EMP_ID = D.EMP_L1)
SELECT TOP 1 WITH TIES EMP_ID,
EMP_L1 = COALESCE(Parsename(PARENT, 1), ''),
EMP_L2 = COALESCE(Parsename(PARENT, 2), ''),
EMP_L3 = COALESCE(Parsename(PARENT, 3), ''),
EMP_L4 = COALESCE(Parsename(PARENT, 4), '')
FROM REC_CTE
ORDER BY Row_number()OVER(PARTITION BY EMP_ID ORDER BY LEVEL DESC)
OPTION (MAXRECURSION 0)
Result :
ββββββββββ¦βββββββββ¦βββββββββ¦βββββββββ¦βββββββββ
β EMP_ID β EMP_L1 β EMP_L2 β EMP_L3 β EMP_L4 β
β βββββββββ¬βββββββββ¬βββββββββ¬βββββββββ¬βββββββββ£
β ALI β ABU β β β β
β JAMES β KAREN β β β β
β JERRY β GEM β β β β
β JOSH β LIM β JERRY β GEM β β
β LIM β JERRY β GEM β β β
ββββββββββ©βββββββββ©βββββββββ©βββββββββ©βββββββββ
Note : This considers there can be maximum of 4 levels. To split the data into different columns I have used PARSENAME function which will not work if you more then 4 levels.
If you dont want to split the parents into different columns remove the PARSENAME and select the PARENT column alone. | unknown | |
d7900 | train | Have you tried thingForm.bindFromRequest() instead of thingForm.bind()? I am using exactly same thing where I make an ajax post with json data and it is working fine for me. It doesn't look like it has anything to do with @JsonProperty().
Are you sure if you want to have class Thing static ? I am assuming you have public getter/setters for your form properties. | unknown |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.