_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d5101 | train | No, that can't be done with the sort function, you need to create a new array by iterating through your original array with nested foreach loops.
$newArr = array();
foreach($arr as $month => items) {
foreach($items as $data) {
$newArr[$month][$data["category"]][] = $data;
}
}
A: You don't want to sort but just to rename keys. PHP Arrays do not support to rename keys directly, so you need to create a new array first that is build with the new keys while maintaining the existing values.
At the end you can replace the original array with the new one:
$rekeyed = array();
foreach($array as $monthYear => &$value)
{
$r = sscanf($monthYear, '%s %d', $month, $year);
if ($r != 2) throw new Exception(sprintf('Invalid Key "%s".', $monthYear));
$categories = array();
foreach($value as &$item)
{
$category =& $item['category'];
unset($item['category']);
$categories[$category][] =& $item;
}
unset($item);
$value =& $categories;
unset($categories);
$rekeyed[$year][$month] =& $value;
}
unset($value);
$array =& $rekeyed;
unset($rekeyed);
print_r($array);
Output:
Array
(
[2011] => Array
(
[Oct] => Array
(
[Windows] => Array
(
[0] => Array
(
[title] => CAD Drawing Updates
[file] => /gm-June2010-driver.pdf
)
)
)
[Sep] => Array
(
[Windows] => Array
(
[0] => Array
(
[title] => title
[file] => /gm-June2010-driver.pdf
)
)
[Walling] => Array
(
[0] => Array
(
[title] => edges
[file] => /gm-June2010-driver.pdf
)
)
)
)
)
Demo
A: I think the function you should be looking at is uasort.
http://www.php.net/manual/en/function.uasort.php
First do a sort on the main array, the for each element in the array, do a usort on the child array. | unknown | |
d5102 | train | I think I found the solution, this error seems to come from a conflict between several scopes. After removing unnecessary scopes, it is working!
"oauthScopes": [
"https://www.googleapis.com/auth/gmail.addons.execute",
"https://mail.google.com/",
"https://www.googleapis.com/auth/script.external_request",
"https://www.googleapis.com/auth/gmail.addons.current.action.compose",
"https://www.googleapis.com/auth/script.locale"
] | unknown | |
d5103 | train | You want to combine a singleton with a facade. Sort of a service locator. i.e. create a singleton that got the same methods as your interface and then assign the interface to the facade as the singleton.
I've blogged about it.
A: C# does not support static inheritance or static interface implementation. static variables are just a form of a Singleton either way you look at it - just go with a Singleton or better use a DI container to inject the logger dependency. | unknown | |
d5104 | train | *
*You need to use jQuery to achieve this result. Download it, paste to js folder and add it to program/base.html
<script src="{% static 'js/jquery-3.5.1.min.js' %}"></script>
*I'd like to recommend you to add a js block into base.html
somewhere at the bottom of the file
{% block js %}{% endblock js %}
*Then, do this:
<block js>
<script>
$("#submit-btn").submit(function(event) {
// prevent default action, so no page refreshing
event.preventDefault();
var form = $(this);
var posting = $.post( form.attr('action'), form.serialize() );
posting.done(function(data) {
// done
});
posting.fail(function(data) {
// fail
});
});
</script>
<endblock>
...
<form action="{% url 'data-submit' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Exercise Measurements</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" id="submit-btn" type="submit">Save</button>
</div>
</form>
A: You have Program in Exercise so use it get program id looking at your DataForm you have exercise field if am not wrong is foreign-key
from django.shortcuts import redirect, reverse
def add_data(request):
page=request.GET.get('page')
page='?page={}'.format(page) if page else ''
if request.method == "POST":
form = DataForm(request.POST)
if form.is_valid():
data=form.save()
return redirect(reverse('program-detail', kwargs={'pk':data.exercise.program.pk})+ page)
For redirecting to same page you check and pass page parmameter in url in form action like
<form action="{% url 'data-submit' %}{%if request.GET.page%}?page={{request.GET.page}}{%endif%}" method="POST" enctype="multipart/form-data">{% csrf_token %} | unknown | |
d5105 | train | The statment FROM ubuntu:14.04 means use the ubuntu image as a base image.
The ubuntu image is not an OS. This image "mimics" an Ubuntu OS, in the sense that it has a very similar filesystem structure to an Ubuntu os and has many tools available that are typically found on Ubuntu.
The main and fundamental difference is that the Docker Ubuntu image does not have it own linux kernel. It uses the kernel of the host machine where the container is running.
Moreover, the size difference between the Docker image (73MB) and an Ubuntu iso(around 1Gb) is very significant.
A: It seems you have a misunderstanding of the docker concept.
What you are doing is pulling an image with the operating system of Ubuntu 14 and creating an instance of it (a container) that has nginx installed on it.
This does not make your os change it gives you a workspace not unlike a vm to run what you want. | unknown | |
d5106 | train | You can use $index = array_search("mark", $commands) which will return the index of the first occurrence of the command "mark" and then you can use $commands[$index + 1] to get the next command in the array.
You will also need to check if $index != null as otherwise it may return the first item in your $commands array because null is interpreted as 0
A: Here is a demonstration with a battery of test cases to fully express how it works and identify fringe cases: (Demo Link)
*note, array_search() returns false when the needle is not found.
$commands = array("mark", "ignore", "pick", "random");
$attempts = array("mark", "ignore", "pick", "random", "bonk");
foreach($attempts as $attempt){
echo "$attempt => ";
$index=array_search($attempt,$commands);
// vv---increment the value
if($index===false || !isset($commands[++$index])){ // not found or found last element
$index=0; // use first element
}
echo $commands[$index],"\n";
}
The "or" (||) condition will "short circuit", so if $index is false it will exit the condition without calling the second expression (isset()).
Output:
mark => ignore
ignore => pick
pick => random
random => mark
bonk => mark
A: Just did some double checking you're going to want to assert first that your array contains the value of mark first. array_search will return a false otherwise, and that easily can be translated into 0.
Supporting Documentation :
PHP in_array
PHP array_search
$commands = array("mark", "ignore", "pick", "random");
//checks if $command contains mark,
//gets first index as per documentation
//Or sets index to -1, ie No such value exists.
$index = in_array("mark",$commands) ? array_search("mark",$commands):-1;
//gets the next command if it exists
$nextCommand = $index!=-1? $commands[++$index]:"Unable to Find Command: mark"; | unknown | |
d5107 | train | List<Widget> widgetList = new List<Widget>();
widgetList.add(child);
needs to be
final widgetList = [child]; | unknown | |
d5108 | train | Search for the following pattern:
<b class="b3">([^\s-\.]*?[ΟΟΟ
ΟΞ―Ο]+?[^\s-\.]*?)<\/b>
And replace it with that:
[[$1]]
[ΟΟΟ
ΟΞ―Ο] can be extended with any greek character you want to have at least in between the tags. | unknown | |
d5109 | train | If you pack py files into zip and add it using sc.addPyFile you should import modules using import client, import connector, etc. | unknown | |
d5110 | train | Try AlarmManager running Service. I wouldn't recommend sending request each minute thou, unless it's happening only when user manually triggered this.
A: public class MyActivity extends Activity {
Timer t ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = new Timer();
t.schedule(new TimerTask() {
public void run() {
//Your code will be here
}
}, 1000);
}
}
A: TimerTask doAsynchronousTask;
final Handler handler = new Handler();
Timer timer = new Timer();
doAsynchronousTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
if(isOnline){// check net connection
//what u want to do....
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 10000);// execute in every 10 s
A: The most easy method is to loop a Handler:
private Handler iSender = new Handler() {
@Override
public void handleMessage(final Message msg) {
//Do your code here
iSender.sendEmptyMessageDelayed(0, 60*1000);
}
};
To start the loop call this sentence:
iSender.sendEmptyMessage(0); | unknown | |
d5111 | train | I don't have access to these command so I am having to guess a little here, but it looks like your command
Set-AdfsRelyingPartyTrust -TargetName "PsTest" -SamlEndpoint $EP,$EP1
accepts an array for the -samlEndpoint parameter.
What I would do it work with the arrays like so.
$EP = New-AdfsSamlEndpoint -Binding "POST" -Protocol "SAMLAssertionConsumer" -Uri "https://test.com" -Index 1
$EndPoints = @(Get-ADFSRelyingPartyTrust -Name "X" | Select-Object -ExpandProperty SamlEndpoints)
$Endpoints += $EP
Set-AdfsRelyingPartyTrust -TargetName "PsTest" -SamlEndpoint $EndPoints | unknown | |
d5112 | train | You can just strip out the characters using strip.
>>> keys=['\u202cABCD', '\u202cXYZ\u202c']
>>> for key in keys:
... print(key)
...
ABCD
XYZβ¬
>>> newkeys=[key.strip('\u202c') for key in keys]
>>> print(keys)
['\u202cABCD', '\u202cXYZ\u202c']
>>> print(newkeys)
['ABCD', 'XYZ']
>>>
Tried 1 of your methods, it does work for me:
>>> keys
['\u202cABCD', '\u202cXYZ\u202c']
>>> newkeys=[]
>>> for key in keys:
... newkeys += [key.replace('\u202c', '')]
...
>>> newkeys
['ABCD', 'XYZ']
>>> | unknown | |
d5113 | train | The spring-integration tag has links to lots of resources. | unknown | |
d5114 | train | That padding at the bottom is actually caused by the box-shadow styling tied to the "elevation" property of Paper (which Card is based on). Setting the elevation to 0 gets rid of it:
<Card className={classes.card} elevation={0}>
However that also gets rid of the raised look of the card. The correct way to deal with this is to specify the image in a CardMedia element rather than using a separate img tag inside a CardContent element.
<CardMedia
className={classes.mainPic}
image="http://images1.fanpop.com/images/image_uploads/Golden-Gate-Bridge-san-francisco-1020074_1024_768.jpg"
/>
Here's a CodeSandbox showing this:
You can also see this approach used in this demo:
https://material-ui.com/demos/cards/#ui-controls
A: See if this is what you want. I changed mainPic and content.
This syntax containerStyle={{ paddingBottom: 0 }} does not seem correct even gets the alert in the browser. Maybe you want to change the styleor classes={{root}} of the api CardActionArea.
mainPic: {
width: 300,
marginBottom: 0,
padding: 0,
borderRadius: '0 0 4px 4px',
},
content: {
height: 225,
padding: "0 !important",
'&:last-child': {
paddingBottom: "0 !important",
},
} | unknown | |
d5115 | train | From what I understand, you want a dictionary that is capable of returning the keys of dictionaries within dictionaries if the value the key's are associated with match a certain condition.
class SubclassedDictionary(dict):
def __init__(self, new_dict, condition=None, *args, **kwargs):
super(SubclassedDictionary, self).__init__(new_dict, *args, **kwargs)
self.paths = []
self.get_paths(condition)
def _get_paths_recursive(self, condition, iterable, parent_path=[]):
path = []
for key, value in iterable.iteritems():
# If we find an iterable, recursively obtain new paths.
if isinstance(value, (dict, list, set, tuple)):
# Make sure to remember where we have been (parent_path + [key])
recursed_path = self._get_paths_recursive(condition, value, parent_path + [key])
if recursed_path:
self.paths.append(parent_path + recursed_path)
elif condition(value) is True:
self.paths.append(parent_path + [key])
def get_paths(self, condition=None):
# Condition MUST be a function that returns a bool!
self.paths = []
if condition is not None:
return self._get_paths_recursive(condition, self)
def my_condition(value):
try:
return int(value) > 100
except ValueError:
return False
my_dict = SubclassedDictionary({"id": {"value1": 144,
"value2": "steve",
"more": {"id": 114}},
"attributes": "random"},
condition=my_condition)
print my_dict.paths # Returns [['id', 'value1'], ['id', 'more', 'id']]
There's a few benefits to this implementation. One is that you can change your condition whenever you want. In your question it sounded like this may be a feature that you were interested in. If you want a different condition you can easily write a new function and pass it into the constructor of the class, or simply call get_paths() with your new condition.
When developing a recursive algorithm there are 3 things you should take into account.
1) What is my stopping condition? In this case your literal condition is not actually your stopping condition. The recursion stops when there are no longer elements to iterate through.
2) Create a non-recursive function This is important for two reasons (I'll get to the second later). The first reason is that it is a safe way to encapsulate functionality that you don't want consumers to use. In this case the _get_paths_recursive() has extra parameters that if a consumer got a hold of could ruin your paths attribute.
3) Do as much error handling before recursion (Second reason behind two functions) The other benefit to a second function is that you can do non-recursive operations. More often than not, when you are writing a recursive algorithm you are going to have to do something before you start recursing. In this case I make sure the condition parameter is valid (I could add more checking to make sure its a function that returns a bool, and accepts one parameter). I also reset the paths attribute so you don't end up with a crazy amount of paths if get_paths() is called more than once.
A: The minimal change is something like:
class SubclassedDictionary(dict):
def __init__(self, *args, **kwargs):
self.paths = [] # note instance, not class, attribute
self.update(*args, **kwargs) # use the free update to set keys
def update(self, *args, **kwargs):
temp = args[0]
for key, value in temp.items():
if isinstance(value, int):
if value > 100:
self.paths.append([key]) # note adding a list to the list
# recursively handle nested dictionaries
elif isinstance(value, dict):
for path in SubclassedDictionary(value).paths:
self.paths.append([key]+path)
super(SubclassedDictionary, self).update(*args, **kwargs)
Which gives the output you're looking for:
>>> SubclassedDictionary(dictionary).paths
[['v2'], ['value1'], ['nested', 'nested_value']]
However, a neater method might be to make paths a method, and create nested SubclassedDictionary instances instead of dictionaries, which also allows you to specify the rule when calling rather than hard-coding it. For example:
class SubclassedDictionary(dict):
def __init__(self, *args, **kwargs):
self.update(*args, **kwargs) # use the free update to set keys
def update(self, *args, **kwargs):
temp = args[0]
for key, value in temp.items():
if isinstance(value, dict):
temp[key] = SubclassedDictionary(value)
super(SubclassedDictionary, self).update(*args, **kwargs)
def paths(self, rule):
matching_paths = []
for key, value in self.items():
if isinstance(value, SubclassedDictionary):
for path in value.paths(rule):
matching_paths.append([key]+path)
elif rule(value):
matching_paths.append([key])
return matching_paths
In use, to get the paths of all integers larger than 100:
>>> SubclassedDictionary(dictionary).paths(lambda val: isinstance(val, int) and val > 100)
[['v2'], ['value1'], ['nested', 'nested_value']]
One downside is that this recreates the path list every time it's called.
It's worth noting that you don't currently handle the kwargs correctly (so neither does my code!); have a look at e.g. Overriding dict.update() method in subclass to prevent overwriting dict keys where I've provided an answer that shows how to implement an interface that matches the basic dict's. Another issue that your current code has is that it doesn't deal with keys subsequently being removed from the dictionary; my first snippet doesn't either, but as the second rebuilds the path list each time it's not a problem there. | unknown | |
d5116 | train | JSTL tags like <c:if> runs during view build time and the result is JSF components only. JSF components runs during view render time and the result is HTML only. They do not run in sync. JSTL tags runs from top to bottom first and then JSF components runs from top to bottom.
In your case, when JSTL tags runs, there's no means of #{item} anywhere, because it's been definied by a JSF component, so it'll for JSTL always be evaluated as if it is null. You need to use JSF components instead. In your particular case a <h:panelGroup rendered> should do it:
<ui:repeat var="item" value="#{userTypeController.permissionItems}">
<h:panelGroup rendered="#{userTypeController.permissionItemsUserType.contains(item)}">
<h:selectBooleanCheckbox value="#{true}"/>
<h:outputText value="#{item.getAction()}" />
</h:panelGroup>
<h:panelGroup rendered="#{!userTypeController.permissionItemsUserType.contains(item)}">
<h:selectBooleanCheckbox value="#{false}"/>
<h:outputText value="#{item.getAction()}" />
</h:panelGroup>
</ui:repeat>
See also:
*
*JSTL in JSF2 Facelets... makes sense? | unknown | |
d5117 | train | NSDictionary is a class cluster (see the "Class Cluster" section in The Cocoa Fundamentals Guide), meaning that the actual implementation is hidden from you, the API user. In fact, the Foundation framework will choose the appropriate implementation at run time based on amount of data etc. In addition, NSDictionary can take any id as a key, not just NSString (of course, the -hash of the key object must be constant).
Thus, closest analog is probably Map<Object,Object>.
A: For practical usage:
HashMap<String, Object> would be the way to go for a simple, non-parallel dictionary.
However, if you need something that is thread-safe (atomic), you'd have to use
HashTable<String, Object>
which is thread safe, but - notably - does not accept null as a valid value or key.
A: I'm admittedly an Android newbie, but to me ContentValues seems to be the closest thing to NSDictionary. | unknown | |
d5118 | train | Use a label (e.g, mylabel:) to let the assembler know the address of the string you want to print, and then reference it with la pseudoinstruction:
.data
.asciiz "c"
mylabel:
.asciiz "hello world\n"
.globl main
.text
main:
la $a0, mylabel
addi $v0, $0, 4 # set command to print
syscall
Otherwise you should know the location where your string if located.
If you want to know how the assembler translates la, you can look at the code generated and translate it again yourself (it should be an lui followed by an ori). Mars simulator lets you see how the la is translated. | unknown | |
d5119 | train | To answer your questions:
Why it is complaining as ALWAYS TRUE condition?
Your FirebaseFirestore object is initialized as lateinit var listenerReg : FirebaseFirestore, which means you've marked your listenerReg variable as non-null and to be initialized later. lateinit is used to mark the variable as not yet initialized, but basically promising that it will be initialized when first referenced in code. Kotlin will throw an error at runtime if trying to access this variable and it's not initialized.
If you want to make it nullable, you'd need to initialize it like this:
var listenerReg : FirebaseFirestore? = null
Then you could have your stop method looking something like this:
fun stopSnapshot() {
if (listenerReg != null) {
listenerReg.remove()
listenerReg.terminate()
listenerRef = null
}
}
But I have two more condition to stop listen:
1 - after 10 minutes
There are many ways to set certain timeouts on Android. The most straightforward way would be to post a handler that will invoke stopSnapshot() method, e.g.:
Handler().postDelayed({
//Do something after 10mins
stopSnapshot();
}, 1000 * 60 * 10)
2 - if I get a specific returned value
Just call stopSnapshot() when you receive this value.
Note: I assumed all the Firestore calls are correct. I don't have the API and this usage on top of my head. Hope my answer helps. | unknown | |
d5120 | train | The current version of testhat::skip_on_cran just check a system variable:
testthat::skip_on_cran
function ()
{
if (identical(Sys.getenv("NOT_CRAN"), "true")) {
return(invisible(TRUE))
}
skip("On CRAN")
}
On my site, the devtools::check does not set this environment variable even with cran = TRUE so all tests are run. That is, the question does not seem to make sense with the present version of testthat. | unknown | |
d5121 | train | Creating migrations is done by running the command Add-Migration AddedServiceTechReason.
This assumes that you have already enabled migrations using the Enable-Migrations command.
To apply the current migration to the database, you'd run the Update-Database. This command will apply all pending migrations.
The point of Code-First migrations is that you make the changes you want to your Entity(ies), and then add a new migration using the Add-Migration command. It will then create a class that inherits DbMigration, with the Up() and Down() methods filled with the changes you have made to your entity/entities.
As per @SteveGreenes comment: It does pick up all changes to your entities, so you don't need to run it once per table/entity.
If you want to customize the generated migration files, look under the section "Customizing Migrations" in the article listed.
All these commands are run in the package manager console.
View -> Other windows -> Package Manager Console.
Here's a great article from blogs.msdn.com that explains it in detail. | unknown | |
d5122 | train | Yes, you can use LIKE:
DECLARE @InputString VARCHAR(100) = 'johnDoeMaxAlexPaul';
SELECT *
FROM dbo.YourTable
WHERE @InputString LIKE '%' + names + '%';
Here is a live demo of this, and the results are:
βββββββββββ
β names β
β ββββββββββ£
β johnDoe β
β Max β
βββββββββββ | unknown | |
d5123 | train | I found a solution which is not very nice :
*
*HTML file : in the select tag I added #typeField
*TS file : I changed the onChange method like below :
app.component.ts
import {Component} from 'angular2/core';
import {Types} from './types';
@Component({
selector: 'my-app',
templateUrl:'./app/app.component.html'
})
export class AppComponent {
field:any = {};
types:Array<string> = Types;
onChange(event:Event, newValue:any) {
this.field.type = newValue;
console.log(this.field.type);
}
}
app.component.html
<h1>My First Angular 2 App</h1>
<div class="form-group">
<label class="col-sm-2 control-label"> Select </label>
<div class="col-sm-4">
<select class="form-control"
[(ngModel)]="field.type"
#typeField
(change)="onChange($event, typeField.value)"
title="Type">
<option *ngFor="#t of types">{{ t }}</option>
</select>
</div>
<hr/>
<label class="col-sm-2 control-label"> Input </label>
<div class="col-sm-4">
<input type="text"
class="form-control input-sm"
[(ngModel)]="field.type"
placeholder="type">
</div>
</div> | unknown | |
d5124 | train | The problem that you are having is your selector for the content of the Qtip. You have $(this).next('div:hidden'), but it appears that your text is actually in a <p> tag.
EDIT: Just saw the part about not editing the HTML, you'll just have to revise your selector to choose the next <p> tag. Something like this $(this).parent().next('p')[0].textContent, fiddle
EDIT 2: Ideally, I would edit the HTML and do this:
Looking through the Qtip2 documentation, the author offers the solution of putting your desired text content into an attribute of the target element. Here is a fiddle demonstrating this.
The relevant HTML:
<a href="http://dacc.fredrixdesign.com/global-imports-bmw-2/"><img width="50" height="50" src="http://dacc.fredrixdesign.com/wp-content/uploads/bmw-150x150.jpg" class="attachment-50x50 wp-post-image" alt="DACC Sponsor" qtip-content="Hello, I'm text!"/></a>
The qTip code:
$('.lcp_catlist a img').each(function () {
$(this).qtip({
content: $(this).next('div:hidden')
});
}); | unknown | |
d5125 | train | iText by default tries to flush pages (i.e. write their contents to the PdfWriter target stream and free them in memory) early which is shortly after you started the next page. To such a flushed page you obviously cannot add your page x of y header anymore.
There are some ways around this. For example, if you have enough resources available and don't need that aggressive, early flushing, you can switch it of by using a different Document constructor, the one with an extra boolean parameter immediateFlush, and setting this parameter to false.
Thus, instead of
new Document(pdfDoc)
or
new Document(pdfDoc, pageSize)
use
new Document(pdfDoc, pageSize, false)
This is a related answer. | unknown | |
d5126 | train | You need to wrap id in quotes and getElementById (not ID)
http://jsfiddle.net/q8x9oupn/3/
A: Take a look at the function document.getElementById.
Returns a reference to the element by its ID; the ID is a string which
can be used to identify the element
So, your correct code would be:
document.getElementById('unique-key-here')
Source
A: *
*'getElementByID' is supposed to be 'getElementById' ('Id' instead of 'ID')
<button onClick="document.getElementById('arbitraryIdentification').innerHTML = 'this text just replaced the original text'">
</button> | unknown | |
d5127 | train | For the Same Domain Issue, I set the X-Frame-Option to *, This way it worked in IE and Firefox as it explicitly understood the option. However in Chrome it did not understand the * option so bypassed it all together, which did the trick. | unknown | |
d5128 | train | I found the answer. One has to use a CharacterEncodingFilter
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class CharacterEncodingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException { }
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
servletRequest.setCharacterEncoding("UTF-8");
servletResponse.setContentType("text/html; charset=UTF-8");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() { }
}
and then add the following lines to the web.xml in the WEB-INF folder:
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>your.package.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> | unknown | |
d5129 | train | If you want an in-graph tree structure as an index, you need to use the RTree index (which is the default in Neo4j Spatial). If you want a geohash index, there will be no tree in the graph because geohashes are being stored as strings in a lucene index for string prefix searches. String prefix searches are a common way of searching geohash based indexes. | unknown | |
d5130 | train | You can do it the exact same way yaml.Unmarshal does it, by taking in a value to unmarshal into:
func GetYamlData(i interface{}) {
yaml.Unmarshal(Filepath, i)
}
Example usage:
func main () {
var car Car
var motorcycle Motorcycle
var bus Bus
GetYamlData(&car)
GetYamlData(&motorcycle)
GetYamlData(&bus)
} | unknown | |
d5131 | train | As per discussion on chat. i think below query will help you to get required result.
with data as ( SELECT ticket_holds.id, ticket_holds.created_at, orders.user_id, users.id, charges.payment_method
FROM ticket_holds
LEFT JOIN order_items ON order_items.id = ticket_holds.order_item_id
LEFT JOIN orders ON orders.id = order_items.order_id
LEFT JOIN users ON users.id = orders.user_id
LEFT JOIN charges on charges.order_id = orders.id
where charges.payment_method is null
)
select * from data d1
where d1.created_at = (select max(created_at) from data d2
where d1.users_id = d2.user_id
)
There are few points while writing an sub query in where clause. Join your table carefully as in your case you are not utilizing any column for joining. | unknown | |
d5132 | train | This did it, if anyone ever runs across the same problem.
$("#bottomContent").on('focus', "#StartDate", function(){
var today = new Date("January 1, 2013");
var datelimit = new Date();
datelimit.setDate(today.getDate() +14);
$(this).glDatePicker({
showAlways: false,
allowMonthSelect: true,
allowYearSelect: true,
prevArrow:'<',
nextArrow:'>',
selectedDate:today,
selectableDateRange: [{
from: today,
to: datelimit
}, ],
onClick: function (target, cell, date, data) {
target.val((date.getMonth() +1) + '/' + date.getDate() + '/' + date.getFullYear());
$('#AllDates').prop('checked', false);
if (data != null) {
alert(data.message + '\n' + date);
}
}
}).glDatePicker(true);
var to = $('#EndDate').glDatePicker({
showAlways: false,
prevArrow:'<',
nextArrow:'>',
selectedDate:today,
onClick: function (target, cell, date, data) {
target.val((date.getMonth() +1) + '/' + date.getDate() + '/' + date.getFullYear());
$('#AllDates').prop('checked', false);
if (data != null) {
alert(data.message + '\n' + date);
}
}
}).glDatePicker(true);
$("#bottomContent").on('focus', "#EndDate", function(){
var dateFrom = new Date($("#StartDate").val());
var toLimit = new Date();
//toLimit.setDate(dateFrom.getDate());
to.options.selectableDateRange = [{
from: dateFrom,
to: toLimit
}, ],
to.options.showAlways = false;
to.render();
});
}); | unknown | |
d5133 | train | No fix, but the reason is I'm pushing too much data from the server to the client. Once I ran adb logcat, I got this:
java.lang.OutOfMemoryError: Failed to allocate a 2470012 byte allocation with 48508 free bytes and 47KB until OOM.
Turns out I'm pushing my images over and over to the client until it breaks. iOS can handle it but RN can't.
Link to StackOverflow related thread: Android:java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM | unknown | |
d5134 | train | It looks like ure.dll has been unloaded, and a call to NlsAnsiToUnicodeMultiByteToWideChar() referring to it is failing. You could run .symfix before !analyze -v to confirm that.
Is that the DLL you're importing? If not, you have memory corruption. Otherwise, the bug is probably in that DLL. Are you using P/Invoke to import it?
Yup, the unloaded DLL information has been corrupted. As you might guess, it's .NET's culture.dll, and Windbg is reading the 'cult' part of that as the timestamp and checksum. Try restarting and doing the following:
.symfix
sxe ud
g
and when the breakpoint hits:
kb
(That's telling Windbg to run until the DLL is unloaded, and then dump the stack)
Run for a bit to let the module unload, and execute the following command. Then let Windbg run until you get the exception, and do this command again to compare:
db ntdll!RtlpUnloadEventTrace
(That's the beginning of the unloaded module table, which is getting corrupted.) | unknown | |
d5135 | train | "fs.s3.consistent": "false" should be true for emrfs consistent view to work | unknown | |
d5136 | train | There are multiple problems in your code:
*
*Function is_isogram() is defined as returning a char, it should instead return a string, hence type char *.
*is_isogram() attempts to modify the string pointed to by its argument. Since it is called with a string literal from main, this has undefined behavior, potentially a program crash.
*You allocate memory for alphabet, but you reset this pointer to phrase in the sorting loop.
*The comparison bet == 'abb\0' does not do what you think it does. bet should be a char * and you should use strcmp() to compare the string values.
Here is a modified version:
#include <ctype.h>
#include <string.h>
#include <stdio.h>
char *is_isogram(const char *phrase) {
char *alphabet;
int count1, count2, n;
if (phrase == NULL)
return NULL;
alphabet = strdup(phrase);
n = strlen(alphabet);
for (count1 = 0; count1 < n; count1++)
alphabet[count1] = tolower((unsigned char)alphabet[count1]);
for (count1 = 0; count1 < n - 1; count1++) {
for (count2 = count1 + 1; count2 < n; count2++) {
if (alphabet[count1] > alphabet[count2]) {
char temp = alphabet[count1];
alphabet[count1] = alphabet[count2];
alphabet[count2] = temp;
}
}
}
return alphabet;
}
int main(void) {
char *bet = is_isogram("bab");
if (strcmp(bet, "abb") == 0) {
return 0;
} else {
return -1;
}
} | unknown | |
d5137 | train | Awt Clipboard and MIME types
InsideClipboard shows that the content's MIME type is application/spark editor
You should be able to create a MIME type DataFlavor by using the constructor DataFlavor(String mimeType, String humanReadableFormat) in which case the class representation will be an InputStream from which you can extract bytes in a classic manner...
However, this clipboard implementation is very strict on the mime type definition and you cannot use spaces in the format id, which is too bad because your editor seems to put a space there :(
Possible solution, if you have access to JavaFX
JavaFX's clipboard management is more lenient and tolerates various "Format Names" (as InsideClipboard calls them) in the clipboard, not just no-space type/subtype mime formats like in awt.
For example, using LibreOffice Draw 4.2 and copying a Rectangle shape, awt only sees a application/x-java-rawimage format whereas JavaFX sees all the same formats as InsideClipboard :
[application/x-java-rawimage], [PNG], [Star Object Descriptor (XML)], [cf3], [Windows Bitmap], [GDIMetaFile], [cf17], [Star Embed Source (XML)], [Drawing Format]
You can then get the raw data from the JavaFX clipboard in a java.nio.ByteBuffer
//with awt
DataFlavor[] availableDataFlavors = Toolkit.getDefaultToolkit().getSystemClipboard().getAvailableDataFlavors();
System.out.println("Awt detected flavors : "+availableDataFlavors.length);
for (DataFlavor f : availableDataFlavors) {
System.out.println(f);
}
//with JavaFX (called from JavaFX thread, eg start method in a javaFX Application
Set<DataFormat> contentTypes = Clipboard.getSystemClipboard().getContentTypes();
System.out.println("JavaFX detected flavors : " + contentTypes.size());
for (DataFormat s : contentTypes) {
System.out.println(s);
}
//let's attempt to extract bytes from the clipboard containing data from the game editor
// (note : some types will be automatically mapped to Java classes, and unknown types to a ByteBuffer)
// another reproducable example is type "Drawing Format" with a Rectangle shape copied from LibreOffice Draw 4.2
DataFormat df = DataFormat.lookupMimeType("application/spark editor");
if (df != null) {
Object content = Clipboard.getSystemClipboard().getContent(df);
if (content instanceof ByteBuffer) {
ByteBuffer buffer = (ByteBuffer) content;
System.err.println(new String(buffer.array(), "UTF-8"));
} else
System.err.println(content);
} | unknown | |
d5138 | train | Use TemplateHaskell to derive the ToJSON instance instead of Generic. The TH functions optionally take an Options which has the omitNothingFields option.
A: There is the Options datatype with an omitNothingFields field for Generics as well so you don't have to use TemplateHaskell, however there's currently (v0.11.2.0) a bug that makes it generate invalid JSON under certain circumstances, e.g. several record fields. It has been fixed but is in master.
You can also handwrite instances if you prefer, for your example:
instance ToJSON Person where
toJSON (Person name shoeSize favoriteColor favoriteFood) = object fields
where
consMay attr = maybe id ((:) . (attr .=))
conss = consMay "shoeSize" shoeSize
. consMay "favoriteColor" favoriteColor
. consMay "favoriteFood" favoriteFood
fields = conss ["name" .= name] | unknown | |
d5139 | train | This seems like a silly trigger. Why are you fetching the last update id using a subquery? It should be available through new:
DELIMITER //
CREATE TRIGGER quantity AFTER INSERT ON sale_items
FOR EACH ROW
BEGIN
update products
set quantity = quantity - 1
where id = new.product_id
END//
DELIMITER ;
A: Use proper Delimiter in your trigger , the correct code is:
DELIMITER //
CREATE TRIGGER quantity AFTER INSERT ON sale_items
FOR EACH ROW
BEGIN
update products set quantity = quantity - 1
where id = new.product_id ;
END//
DELIMITER ; | unknown | |
d5140 | train | But in contrast to this, in case of Spring boot, the Queue is configured at the sender side only, including the exchange binding.
That is not correct. What is leading you to that conclusion?
Messages are sent to an exchange with a routing key; the producer knows nothing about the queue(s) that are bound to the exchange. | unknown | |
d5141 | train | I willing to recommend. refer a this article:
Communicating between ActionScript and JavaScript in a web browser | unknown | |
d5142 | train | Are there technical reasons that the key names should not be repeated?
No. Seems perfectly reasonable to me.
e.g. if I was serialising a Scala/Java object, that object could look like:
class Delivery {
val parcelId : String
val source : Address
val destination : Address
}
and the field names of the Address object would be the same here.
A: There is nothing wrong with having duplicate property keys which are part of different objects in JSON.
Your JSON example is perfectly valid.
This is only an issue when they are at the same level.
For example two source objects:
{
"parcelId": 123,
"source": {
"street": "123 Main Street",
"city": "Anytown",
"state": "New York"
},
"source": {
"street": "456 Avenue B",
"city": "Elsewhere",
"state": "New Jersey"
}
}
Or two street properties inside one object:
"source": {
"street": "456 Avenue B",
"street": "Elsewhere",
"state": "New Jersey"
}
A: No. This would be confusing if you had delivery.street and then a different delivery.street. But you don't. You have delivery.source.street and delivery.destination.street. Basically the key street is addressing a completely different object now. | unknown | |
d5143 | train | Phantom JS something act weirdly. Check if you have a overlay of custom element over html element. if so try to click on custom element and not on actual html element.
if it doesn't work try to click using Javascript, that is you best bet. | unknown | |
d5144 | train | I am guessing you want a list of names in one cell. Assuming you have a Employee model that represents the sources of power (change to whatever yours is), just find and map the ids:
Employee.where(id: health.source_of_power).pluck(:name).join(',')
Or, if you have first and last:
Employee.where(id: health.source_of_power).pluck(:first, :last).map {|t| t.join(' ')}.join(', ')
You could get more efficient if you had an indexed hash of employees ahead of time. Then you aren't running a query per row:
employees_by_id = Employee.all.index_by(&:id)
@healths.each do |health|
sources_of_power = employees_by_id.values_at(health.source_of_power).map(&:name)
sheet.add_row [...,sources_of_power,...]
end
You could use scopes and relations on the health object if they were there. Your info is a bit vague. | unknown | |
d5145 | train | Try Google Accessibility Developer Tools Extension for Chrome. It runs an accessibility audit on individual pages, making assertions based on WCAG 2.0.
If you have a Rails project, you can run the assertions from the Google Extension as part of an Rspec integration test suite using capybara-accessible, a rubygem that defines a Selenium based webdriver for Capybara and makes accessibility assertions on page loads. That way you can automate testing across your site and also get failures in CI.
A: Try Wave, which is free to use. But not sure if it has full functionality. Check it out yourself and let me know if its the right one for you.
A: As Felipe said, no automated testing should be relied upon. Specifically if you need to test for Section 508, it states that you have to test with AT. WAVE and Deque WorldSpace does not satisfy this requirement. WAVE is a fine tool to catch low hanging fruit. Maybe the Google Plug-in does as well, but would not rely upon it due to how Chrome handles and reports things to MSAA and other APIs.
I have heard numbers thrown around how well automated testers are. Personally, I set them around the 50% mark, particially due to the "full functionality" aspect that Felipe mentions in Mohammad's answer. In terms of Section 508, this phrase is called "equivalent facilitation", which is covered in 1194.31, which no automated tester can cover. Subpart 1194.31 is the functional standards, which apply to all activities if Section 508 is applicable. The same goes with 1194.41.
FelipeAls said:
[Section 508] outdated and W3C/WAI WCAG 2.0 is a way better resource for improving accessibility nowadays (but of course if you must be compliant with 508, then also test for 508)
While I will say Section 508 is rough around the edges, I wouldn't say it is useless as some market it as. In my experience people pushing this, have limited experience actually dealing with Section 508, or they work behind a product that does testing. Their biggest arguement is usually "heh look, if Section 508 is so good, why doesn't it require headings (<h1>)?" Well, Section 508 was derived from WCAG 1.0, which didn't have it either, so that argument is weak in my opinion. Also, remember how I said people don't realise that 1194.31 is applicable? Let's look at 1194.31(a):
(a) At least one mode of operation and information retrieval that does not require user vision shall be provided, or support for assistive technology used by people who are blind or visually impaired shall be provided.
You can read that as: code a page so that AT can find specific parts of/on a page. What's a good way to allow people to jump around? Headings, and now WAI-ARIA Landmarks.
Section 508 is also being worked on to adopt WCAG 2.0. | unknown | |
d5146 | train | I don't see any problem with your application's logic.
However, you forgot to set Spinner's onItemSelected:
spinner1.setOnItemSelectedListener( new response_1());
spinner2.setOnItemSelectedListener( new response_2());
spinner3.setOnItemSelectedListener( new response_3()); | unknown | |
d5147 | train | You do not state what precisely does not work. However, the main problems is probably in the fact that you are using BrowseFilter = browseFilter.item. The nodes in the tree are either leaves (sometimes called items), or branches. Your code only asks for the leafs, under the root of the tree. There may be no items under the root whatsoever, and you need to obtain the branches as well, and then dwelve deeper into the branches, recursively.
Start by changing your code to use BrowseFilter = browseFilter.all. This should give you all nodes under the root. Then, call the Browse recursively for the branches (just branches, not items) you receive, using the item ID of each branch as the starting point for the new browse. | unknown | |
d5148 | train | Ok. The issue was related to intermittant connectivity loss. All fixed now | unknown | |
d5149 | train | try this:
SELECT TOP 1 models.color, COUNT(orders.number) FROM models
INNER JOIN orders ON (orders.number=models.number)
GROUP BY models.color
ORDER BY 2 desc
A: All you need is to get rid of limit and use Top 1 instead:
SELECT Top 1 models.color FROM models
INNER JOIN orders ON (orders.number =models.number)
group by color
order by count(color) Desc
However, there is a caveat for Top n, in MS Access, Top n will return matches, so if several items have the same count, all will be returned. If this does not suit, you can work around this by ordering by a unique id as well:
order by count(color) desc, OrderID
Note also that number is a reserved word. | unknown | |
d5150 | train | Currently you are passing the values from the Clock column to be plotted on the x-axis and since these are strings, matplotlib interprets them as a categorical variable. If you are okay with this, then each of the x-ticks will be spaced equally apart regardless of their value (but we can sort the DataFrame before passing it), and then to get the desired tick labels you can take the portion of the string before the colon symbol (for example '20' from the string '20:30') and add the string ' hours ago' to that string to get '20 hours ago'. Then pass each of these strings as labels to the plt.xticks method, along with the original ticks in the Clock column.
import matplotlib.pyplot as plt
import pandas as pd
## recreate the data with times unsorted
df = pd.DataFrame({
'ID':[260,127,7,10,8],
'Time':['21 hours','21 hours','5 hours','6 hours','6 hours'],
'Clock':['20:30','20:30','12:30','11:30','11:30',]
})
df_sorted = df.sort_values(by='Clock',ascending=False)
plt.scatter(df_sorted['Clock'], df_sorted['ID'])
## avoid plotting duplicate clock ticks over itself
df_clock_ticks = df_sorted.drop_duplicates(subset='Clock')
## take the number of hours before the colon, and then add hours ago
plt.xticks(ticks=df_clock_ticks['Clock'], labels=df_clock_ticks['Clock'].str.split('\:').str[0] + ' hours ago')
plt.show() | unknown | |
d5151 | train | Times is a Mac font (AAT is Apple Advanced Typography). My preferred technique with stubborn fonts is to change the file ending to .zip, unzip the file to OOXML, then use a text editor like NotePad++ to run a find and replace on all files.
Find: typeface="Times"
Replace: typeface="Arial"
Then rezip and rename back to .pptx. Make a copy of the file to experiment. This method also works great on changing PowerPoint language settings.
A: Both 'Replace font' and 'OOOXML transfer' didn't work for me.
For people with Mac OS: open the pptx file with Keynote. A dialog asks to replace missing fonts. Simply replace the ones causing trouble. Then export to Powerpoint.
It should work. | unknown | |
d5152 | train | Rather than thinking about tests/method of your class, you should consider it as one test per expected behavior of the class. In your example, you have two different things that should happen
*
*if the parameter is one, throw an exception
*return true for other values
So you would need the two tests because there are two different things are supposed to happen.
Your tests help specify what it is that your code is supposed to DO, not what your code is supposed to look like. A method may result in different things happening depending on the parameters undo which it is run. | unknown | |
d5153 | train | You have to create predicate dynamically:
private IQueryable<T> GetQueryById(TKey id)
{
IQueryable<T> query = _dbset; //DbSet<T>
var keyNames = _context.Model
.FindRuntimeEntityType(typeof(T))
.FindPrimaryKey()
.Properties
.Select(x => x.Name)
.ToList();
if (keyNames.Count == 1)
{
var keyExpression = Expression.Constant(id);
var entityParam = Expression.Parameter(typeof(T), "e");
var body = Expression.Equal(Expression.PropertyOrField(entityParam, keyNames[0]), keyExpression);
var predicate = Expression.Lambda<Func<T, bool>>(body, entityParam);
query = query.Where(predicate);
}
else
// better to throw exception
throw new Exception($"Cannot find entity key.");
return query;
} | unknown | |
d5154 | train | You were almost there, just add the MIN(Number) field.
SELECT ID
, NAME
, MIN(NUMBER)
, MIN(IDN)
FROM ATable
GROUP BY
ID
, NAME
In response to comment
Following would get you the records with the MIN(IDN), regardless what the number for that specific record is.
SELECT t.*
FROM ATable t
INNER JOIN (
SELECT ID, IDN = MIN(IDN)
FROM ATable
GROUP BY ID
) tmin ON tmin.ID = t.ID
AND tmin.IDN = t.IDN
A: DECLARE @TABLE table (ID int, [NAME] varchar(100),NUMBER int ,IDN int)
insert into @TABLE SELECT 1,'dsad',500600,12
insert into @TABLE SELECT 1,'dsad',600700, 13
insert into @TABLE SELECT 2,'kkkk',111222, 56
insert into @TABLE SELECT 2,'kkkk',333232, 57
select t.ID, t.[Name], t.Number, t.IDN
from (
select [NAME],min(IDN) as minIDN
from @TABLE group by [NAME]
) as x inner join @TABLE as t on t.[Name]=x.[Name] and t.IDN = x.minIDN;
A: Version that only uses a left join and no subqueries, with SQlite3 and a shell script since I don't have anything other at hand ATM:
#!/bin/sh
rm -f test.sqlite
sqlite3 test.sqlite << AAA
CREATE TABLE test (id int, name text, number int, idn int);
INSERT INTO test VALUES(1,'dsad',500600,12);
INSERT INTO test VALUES(1,'dsad',600700,13);
INSERT INTO test VALUES(2,'kkkk',111222,56);
INSERT INTO test VALUES(2,'kkkk',333232,57);
INSERT INTO test VALUES(1,'dsad',600700,9);
INSERT INTO test VALUES(2,'kkkk',333232,59);
INSERT INTO test VALUES(2,'cccc',333232,59);
SELECT a.* FROM test a
LEFT JOIN test b ON
a.id=b.id AND
a.name=b.name
AND a.idn > b.idn
WHERE b.id IS NULL;
AAA
# Result:
# 1|dsad|600700|9
# 2|cccc|333232|59
# 2|kkkk|111222|56
Can anyone comment on where the performance is better? I think that matters, too! | unknown | |
d5155 | train | use this
self.navigationItem.title = @"The title"; | unknown | |
d5156 | train | You can do it with using position field in CSS
HTML:
<div class="para align-center">SCHEDULE 1 <span class="align-right">[r.32]</span>
</div>
<div class="para align-center">PART I</div>
CSS:
.para {
text-indent: 0em;
margin-bottom: 0.85em;
}
.align-center {
text-align: center;
}
div{
position: relative;
}
div.align-center span.align-right {
float: right;
}
div span.align-right{
position: absolute;
right: 0;
}
Please look at the demo code
DEMO
A: you can remove .para + .align-right remove +
Css:
.para {
text-indent: 0em;
margin-bottom: 0.85em;
}
.align-center {
text-align: center;
}
div.align-center span.align-right {
float:right;
margin-left:-38px;
}
DEMO | unknown | |
d5157 | train | In your example there is no functional difference because you're always returning a constant value. However if the value could change, e.g.
public string SomeProperty => DateTime.Now.ToString();
vs
public string SomeProperty { get; } = DateTime.Now.ToString();
The first would execute the expression each time the property was called. The second would return the same value every time the property was accessed since the value is set at initialization.
In pre-C#6 syntax the equivalent code for each would be
public string SomeProperty
{
get { return DateTime.Now.ToString();}
}
vs
private string _SomeProperty = DateTime.Now.ToString();
public string SomeProperty
{
get {return _SomeProperty;}
} | unknown | |
d5158 | train | I finally solved it. I connected my account and it worked.
ramonmorcillo@Ramons-MacBook-Pro bin % ./ngrok authtoken MY _AUTH_TOKEN
Authtoken saved to configuration file: /Users/ramonmorcillo/.ngrok2/ngrok.yml
ramonmorcillo@Ramons-MacBook-Pro bin % ./ngrok help
NAME:
ngrok - tunnel local ports to public URLs and inspect traffic
DESCRIPTION:
ngrok exposes local networked services behinds NATs and firewalls to the
public internet over a secure tunnel. Share local websites, build/test
webhook consumers and self-host personal services.
... | unknown | |
d5159 | train | Sorry about the breaking changes in the latest beta. The new API allows more flexibility by associating the Action event to the rendered card. When you call RenderAdaptiveCard(...) you get a RenderedAdaptiveCard object back. This object has the OnAction event | unknown | |
d5160 | train | The final keyword applied to a field has one of two effects:
*
*on a primitive, it prevents the value of the primitive from being changed (an int can't change value)
*on an object, it prevents the "value of the variable", that is, the reference to the object, from being changed. That is to say that, if you have a final HashMap<String,String> a, you will only be able to set it once, and you won't be able to do this.a=new HashMap<String,String>(); again, but nothing keeps you from doing this.a.put("a","b"),s since that doesn't modify the reference, only the content of the object.
A: The official reason is that it is defined by the Java Language Specification 8.3.1.2:
A blank final instance variable must be definitely assigned at the end of every constructor of the class in which it is declared; otherwise a compile-time error occurs.
A blank final is a final variable whose declaration lacks an initializer (i.e. what you describe).
A: The final modifier prevents your from changeing the variables value, hence you have to initialize it where you declare it.
A: Because final prevents you from modifying variables, but it has to be initialized at some point, and the constructors is the right place to do so.
In your case, it would be called a blank final because it is not initialized when declared.
A: The value of a final variable can only be set once. The constructor is the only place in the code for a class that you can guarantee this will hold true; the constructor is only ever called once for an object but other methods can be called any number of times.
A: A final variable must be initialized at the declaration or in a constructor.
If it has not been initialized when the constructor returns, it may never be initialized, and may remain an uninitialized variable. The compiler cannot prove it will be initialized, and thus throws an error.
This Wikipedia excerpt explains it well:
A final variable can only be initialized once, either via an initializer or an assignment statement. It does not need to be initialized at the point of declaration: this is called a "blank final" variable. A blank final instance variable of a class must be definitely assigned at the end of every constructor of the class in which it is declared; similarly, a blank final static variable must be definitely assigned in a static initializer of the class in which it is declared: otherwise, a compile-time error occurs in both cases. (Note: If the variable is a reference, this means that the variable cannot be re-bound to reference another object. But the object that it references is still mutable, if it was originally mutable.)
A: Final modifier does not allow to change your variable value. So you need to assign a value to it at some place and constructor is the place you have to do this in this case.
A: The language specification contains specific guarantees about the properties of final variables and fields, and one of them is that a properly constructed object (i.e. one whose constructor finished successfully) must have all its final instance fields initialized and visible to all threads. Thus, the compiler analyzes code paths and requires you to initialize those fields.
A: If an instance variable is declared with final keyword, it means it can not be modified later, which makes it a constant. That is why we have to initialize the variable with final keyword.Initialization must be done explicitly because JVM doesnt provide default value to final instance variable.Final instance variable must be initialized either at the time of declaration like:
class Test{
final int num = 10;
}
or it must be declared inside an instance block like:
class Test{
final int x;
{
x=10;
}
}
or
it must be declared BEFORE constructor COMPLETION like:
class Test{
final int x;
Test(){
x=10;
}
}
Keep in mind that we can initialize it inside a consructor block because initialization must be done before constructor completion.
A: The moment the constructor completes execution, the object is 'open for business' - it can be used, its variables can be accessed.
The final keyword on a variable guarantees that its value will never change. This means, if the value is ever read, you can be sure that the variable will always have that value.
Since the variable can be accessed (read) at anytime after the execution of the constructor, it means it must never change after the constructor has executed - just it case it has been read.
Thus, it must, by then, have been set. | unknown | |
d5161 | train | You can't just create peerConnection, dataChannel and start using it right away.
And btw you don't have 2 peers here...
*
*You'll need to create peerConnections object in the 2 peers
*Transfer SDP's
*get ice candidates
*and only after that the dataChannel is open and then you can send information on top of it
I suggest start by reading this, it will give you knowledge of the basic concepts
And then continue to this awesome code lab by Sam Dutton.
Update to answer mhenry's request:
Here's the entirety of setting up data channel in one class: https://gist.github.com/shacharz/9661930
Follow the comments, you'll just need to:
*
*Add signaling, sending SDP's ice candidates to the other peer (targetId)
*If you'de like to handle all the connection lost and stuff like that by a higher level logic.
*Make sure that when receiving an sdp you call the "Handlmessage" method
*Use the class with its public methods: SetupCall, Send, Close
A: I wrote the following code this morning that uses RTCPeerConnection and RTCDataChannel in a single page. The order in which these functions are declared is important.
var localPeerConnection, remotePeerConnection, sendChannel, receiveChannel;
localPeerConnection = new RTCPeerConnection(null, {
optional: [{
RtpDataChannels: true
}]
});
localPeerConnection.onicecandidate = function(event) {
if (event.candidate) {
remotePeerConnection.addIceCandidate(event.candidate);
}
};
sendChannel = localPeerConnection.createDataChannel("CHANNEL_NAME", {
reliable: false
});
sendChannel.onopen = function(event) {
var readyState = sendChannel.readyState;
if (readyState == "open") {
sendChannel.send("Hello");
}
};
remotePeerConnection = new RTCPeerConnection(null, {
optional: [{
RtpDataChannels: true
}]
});
remotePeerConnection.onicecandidate = function(event) {
if (event.candidate) {
localPeerConnection.addIceCandidate(event.candidate);
}
};
remotePeerConnection.ondatachannel = function(event) {
receiveChannel = event.channel;
receiveChannel.onmessage = function(event) {
alert(event.data);
};
};
localPeerConnection.createOffer(function(desc) {
localPeerConnection.setLocalDescription(desc);
remotePeerConnection.setRemoteDescription(desc);
remotePeerConnection.createAnswer(function(desc) {
remotePeerConnection.setLocalDescription(desc);
localPeerConnection.setRemoteDescription(desc);
});
}); | unknown | |
d5162 | train | This is not an answer/solution to the problem. Since i cannot comment yet, had to put it in the Answer section. It could be delay in assigning the compute resources. Please check the details.
You can check the details by hovering mouse pointer between Name and Type beside Copy. | unknown | |
d5163 | train | I think you should set the model to the table
table.setModel(tableModel); //add this to your code
Ok, so from what i see ,you are using Netbeans and creating JFrame. If you are inserting your table from the design than there is no need for you to create another table in the constructor.Just simply:
public NewJFrame() {
initComponents();
DefaultTableModel tableModel = new DefaultTableModel();
tableModel.addColumn("Type");
tableModel.addColumn("Folder");
String[] row = {"Datum1","Datum2"};
tableModel.addRow(row);
jTable1.setModel(tableModel);// where jTable1 has been created and instantiated automatically by netbeans when you draged and dropt it to your frame , from the design.
}
A: Radu Soigan is right, the JTable and TableModel are separate objects which need to be linked together using the setModel(tableModel) method as the table doesn't know where the data to display is at. This is also the same for custom table models, always remember to set it to the JTable after setting up the model. | unknown | |
d5164 | train | Just remove the curly braces and use a plain let:
main = do
bytes <- loadFile "...."
let d = processData bytes
printf (extractFoo d address1)
printf (extractFoo d address2)
I renamed your data to d since data is a keyword in Haskell. | unknown | |
d5165 | train | 'Aa' in 'ABC' will return False. The in operator in this context well check if the exact full substring (not any individual characters) is present.
In your case, you need to check each character individually, or convert the case to use a single character.
You can use:
s = input('Enter string: ')
if 'A' in s[-3:].upper():
print('Group A')
elif 'BBB' == s[-3:].upper():
print('Group B')
else:
print('Group C')
Or better, slice and convert the case only once:
s = input('Enter string: ')[-3:].upper()
if 'A' in s:
print('Group A')
elif 'BBB' == s:
print('Group B')
else:
print('Group C')
``
A: It looks like you may think you're using Regex, to actually use it:
import re
s = input('Enter string: ')
if re.match('[Aa]', s):
print('Group A')
... | unknown | |
d5166 | train | I found a solution that may help you to disable some dates , in my case , I needed to disable unavailability events, so I used selectable="ignoreEvents"
`<BigCalendar
selectable="ignoreEvents"
localizer={localizer}
events={events}
views={allViews}
step={60}
showMultiDayTimes
defaultDate={new Date()}
defaultView={BigCalendar.Views.WEEK}
style={{height: "90vh" }}
resources={resourceMap}
resourceIdAccessor="resourceId"
resourceTitleAccessor="resourceTitle"
onSelectSlot={this.handleSelect}
eventPropGetter={(this.eventStyleGetter)}
/>`
use eventPropGetter to style you events | unknown | |
d5167 | train | Looks like you need a lambda function, similar to your previous example
server.on("/Lg1", [](){ l1.toggleLight(); }); | unknown | |
d5168 | train | You can perform a manipulation of the xml string in your controller with a little regex to eliminate the newlines and whitespace.
Here is a little java app to show the regex in work against your xml string.
public class StripXmlWhitespace {
public static void main (String [] args) {
String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
" <Esign AuthMode=\"1\" aspId=\"ASPRBLBMUMTEST043\" ekycId=\"448988431774\" ekycIdType=\"A\" ekycMode=\"U\" organizationFlag=\"N\" preVerified=\"n\" responseSigType=\"pkcs7\" responseUrl=\"http://10.80.49.41\" sc=\"Y\" ts=\"2018-01-19T11:42:55\" txn=\"UKC:eSign:6539:20180119114250963\" ver=\"2.0\">\n" +
" <Docs>\n" +
" <InputHash docInfo=\"Signing pdf\" hashAlgorithm=\"SHA256\" id=\"1\">30e3ed7f512da50206b8720d52457309c87f4edfee85d08f937aef3f955fb7af</InputHash>\n" +
" </Docs>\n" +
" <Signature xmlns=\"http://www.w3.org/2000/09/xmldsig#\">\n" +
" <SignedInfo>\n" +
" <CanonicalizationMethod Algorithm=\"http://www.w3.org/TR/2001/REC-xml-c14n-20010315\"/>\n" +
" <SignatureMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#rsa-sha1\"/>\n" +
" <Reference URI=\"\">\n" +
" <Transforms>\n" +
" <Transform Algorithm=\"http://www.w3.org/2000/09/xmldsig#enveloped-signature\"/>\n" +
" </Transforms>\n" +
" <DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\"/>\n" +
" <DigestValue>kQEB9r4dd5hhdaPxc4sjPMG3SGM=</DigestValue>\n" +
" </Reference>\n" +
" </SignedInfo>\n" +
" <SignatureValue>MSgEXK2+GpwnRBr3vLNncqc9FOY0oDhjlhfyihOjrUPFZAL8eBms6jXdhoWGlrypaF6hE70ZltDQbQTArrk/mfCmoVvna7yEJN9gDh6gAHbh9Zj4BEBdWhd85DKbAdtSy8zYTKIeIjhFBzOItUAhSN7lFrEFVrTLV5wO38hswD7LlaY4ZBSNMWbpHPx+Io6ukdP8b4n95dqoB9iiqKxg3nK0RslhLRcPoe4B2AsdoiZ42iY/tZ4disOzyOCyCdE8nRxipJbP9HZS3psCSCar3CPSigXiNk6fY7+bDEFbJrfoqhHBk1hasx2m0TbxZVeOIPSUPRYpekHCm0sm4RvZhA==</SignatureValue>\n" +
" <KeyInfo>\n" +
" <X509Data>\n" +
" <X509SubjectName>CN=AAA Bank Test,OU=AAA Bank IT Dept,O=AAA Bank,L=Delhi,ST=Delhi,C=91</X509SubjectName>\n" +
" <X509Certificate>MIIDkTCCAnmgAwIBAgIEZNl4CjANBgkqhkiG9w0BAQsFADB5MQswCQYDVQQGEwI5MTETMBEGA1UECBMKTWFoYXJhc3RyYTEPMA0GA1UEBxMGTXVtYmFpMREwDwYDVQQKEwhSYmwgQmFuazEZMBcGA1UECxMQUkJMIEJhbmsgSVQgRGVwdDEWMBQGA1UEAxMNUmJsIEJhbmsgVGVzdDAeFw0xNzAzMDIxNDA4MTBaFw0xODAyMjUxNDA4MTBaMHkxCzAJBgNVBAYTAjkxMRMwEQYDVQQIEwpNYWhhcmFzdHJhMQ8wDQYDVQQHEwZNdW1iYWkxETAPBgNVBAoTCFJibCBCYW5rMRkwFwYDVQQLExBSQkwgQmFuayBJVCBEZXB0MRYwFAYDVQQDEw1SYmwgQmFuayBUZXN0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsjsF71lv96Y+2DbuSgk1U/Bp3P+jPpKp9GpwiVuIAf4SsBc1bqR3x4JSnY4COdUlq2IkHYSGnufGkPS6tH4edoFpZrSBAiTo1D0WQQ4KoRWBzn9xptMGsJBoV7dcSovjjD1HhUJGNnfoxjBh3AmIe8ZySWhuouEA8cRtFcHoWunpSB1FOJreIZ1P/ZnJ7C4gu+E1ccXjkFPqCGI9RcdUSE72K+ovtI/yWIUPwXdj3O/k30iX2owxUVFKnCmIDFnKDJ/b96RDzlIB9FiH5IVQm4mcU6HiQKqknDI3bPKlwvfFfB+YI69vjRQf3dvsca2nZQsYT3iSgkxBwoiugsD59QIDAQABoyEwHzAdBgNVHQ4EFgQUwFYILDVGVtIJgYveFqZ9YRrRq4AwDQYJKoZIhvcNAQELBQADggEBAKygyzVE1sOaBxuj4IjGDmo2y5UOhPOzklRocZbsqycEApcBn5m/dVauvewqw7An1vrkvjTYbTUCjUKghNW/MdtiWbKKRDy3fA8DyEACcYuK0PpaaXMTJFjIjKxXko6Rmmp6CKFcmERgetiwrFreMfFjvCv9H1fk7FSR87d/17l/LsmAndFIvpZTF3Ruz4lZsoL2qWtBF+wnVjFW+yqf6nXDqE/Swxhiq7dZ+Dl0ilgEsh3Q1WOO/S/TBDkeURIHfIkc886p5M4u5iQdkO1fndptUhBNbaM1idMOW/5QUWFeIEChdSo3mrVVTWyvhQEkYls0GYJUSVSdaITcyE3xkJA=</X509Certificate>\n" +
" </X509Data>\n" +
" </KeyInfo>\n" +
" </Signature>\n" +
" </Esign>";
String output = xmlString.replaceAll(">\\s+<", "><");
System.out.println(xmlString);
System.out.println(output);
}
}
All you need in your controller is the regex.
xml = xmlString.replaceAll(">\\s+<", "><");
Essentially unformat the xml before you send it bind it to the view. I hope that helps. | unknown | |
d5169 | train | Dont pay too much attention to SQL INJECTION until you get your code running. Get it working, then secure it. Try set a variable to
var sqlText = "SELECT * FROM Student where Gender = '" + textBox1.Text + "' ";
And then hit that in the debugger to check your full query statement. Make sure you have not got any sillies in there like an extra space.
See a full example of filling a data table here
Fix your SQL INJECTION vulnerability using parameters
A: No error with Query seems binding issue with DataGrid.
My case is same, I use SQL, DataTable, DataGrid.
And would you try this?
DataTable DataTab = new DataTable("Student");
DaSql = new SqlDataAdapter("SELECT * FROM Student where Gender = '" + textBox1.Text + "' ", conSql);
DaSql.Fill(DataTab);
DataGridQueryResult.ItemsSource = DataTab.DefaultView;
And need to check DataGrid settings are correct in Window Designer including AutoGeneratingColumns= True.
I always use ItemsSource with good results. | unknown | |
d5170 | train | The only way the context of an Activity can be null is if you are passing around an instance of your Activity that you instantiated yourself, which you should never do. Would have to see more of your code to know where you are doing that.
A: So, I resolved the problem. It was easy.
How said Tenfour04:
The only way the context of an Activity can be null is if you are passing around an instance of your Activity that you instantiated yourself, which you should never do...
It is true.
Solution:
*
*should send context to FirestoreCRUD class:
FirestoreUtil(this).addNewUserToFirestore(user)
*FirestoreCRUD class receivers straight to Interface:
class FirestoreUtil(var onResultSuccessListener: OnResultSuccessListener) {}
*And call the Interface method in AuthenticationActivity class from FirestoreCRUD class:
onResultSuccessListener!!.onResultSuccess(true)
And then my activity doesn't restart and everything runs smoothly!
I hope this helps somebody. | unknown | |
d5171 | train | This is something I just thought of, check it out see what you think. So we use :after and create a line under the text. This only works if the parent has a width (for centering).
HTML:
<div>Test</div>
CSS:
div {
width: 30px;
}
div:hover:after {
content: "";
display: block;
width: 5px;
border-bottom: 1px solid;
margin: 0 auto;
}
DEMO
Updated CSS:
div {
display: inline-block;
}
Not sure why I didnt think of this but you can just use inline-block to get it to center without the parent having a width.
DEMO HERE
Here is a link using the same method, just incase you got confused.
DEMO HERE
So I have now be told I should even point out the most obvious thing so here is an update just for the people that don't know width can be a percentage.
width: 70%;
Changed the width from 5px to 70% so it will expand with the width of the text.
DEMO HERE
A: Edit:
Ruddy's solution has the same result and is more elegant so based on that, I used it recently with addition of transition, making it a bit more eye catching and I thought it would be useful to share here:
a {
display: inline-block;
text-decoration:none
}
a:after {
content: "";
display: block;
width: 0;
border-bottom: 1px solid;
margin: 0 auto;
transition:all 0.3s linear 0s;
}
a:hover:after {
width: 90%;
}
jsfiddle link
(Original answer below)
Check this i just came up with, playing in the fiddle:
<a class="bordered" href="#">I am a link, hover to see</a>
a.bordered {
text-decoration:none;
position: relative;
z-index : 1;
display:inline-block;
}
a.bordered:hover:before {
content : "";
position: absolute;
left : 50%;
bottom : 0;
height : 1px;
width : 80%;
border-bottom:1px solid grey;
margin-left:-40%;
}
Depending on the percentages, you may play with a.bordered:hover:before margin and left position.
A: Simply use this class:
.link:hover {
background-image:url("YOUR-SMALL-LINE-BOTTOM.png")
}
like this, the line will appear when you hover over the element. And you can specify in the image, how small or big the line has to be.
A: Try creating another Div for border. And adjust the width of that div according to your choice. I hope this will help.
A: what about this?
a {text-decoration:none;position:relative;}
a:hover:before {content:"_";position:absolute;bottom:-5px;left:50%;width:10px;margin:0 0 0 -5px;}
check this fiddle for more: http://jsfiddle.net/h7Xb5/
A: You can try using ::after pseudo element:
a {
position: relative;
text-decoration: none;
}
a:hover::after {
content: "";
position: absolute;
left: 25%;
right: 25%;
bottom: 0;
border: 1px solid black;
}
<a href='#'>Demo Link</a>
A: use underline or if u want the line to be much shorter try scalar vector graphics(svg) with this you can have custom lines.
<svg id="line "height="40" width="40">
<line x1="0" y1="0" x2="700" y2="20" style="stroke:rgb(125,0,0);stroke-width:2" /> | unknown | |
d5172 | train | Here's a checklist
*
*What server are you running? Does it support php?
*Is PHP enabled?
*Is your file named with the extension .php?
*When you use View Source can you see the code in the php tags? If so PHP is not enabled
As a test try saving this as info.php
<?php
phpinfo();
?>
and see if it displays information about your server
A: Make sure the file that contains that code is a PHP file - ends in '.php'.
A: You might want to enable your error reporting in .htacess file in public_html folder and try to diagnose the issue depending upon the error message.
A: The code seems fine, certainly it should do what you intend.
Probably what happened is that you named the file with something like example.html, so you have to check the extension. It must look like example.php. With the extension .php at the end of the file you are telling the webserver that this file contains php code in it. That way the <?php echo "Hello World"; ?> is going to be interpreted and do you intend it to do.
A: If you don't see the html tags in the source, it means there is a PHP error. Check your view source, and if nothing is shown, check your error logs. | unknown | |
d5173 | train | use this code to destroy CK editor:
try {
CKEDITOR.instances['textareaid'].destroy(true);
} catch (e) { }
CKEDITOR.replace('textareaid');
A: I have been able to come up with a solution for this in CKEditor 4.4.4.
In ckeditor.js (minified), line 784:
a.clearCustomData();
should be changed to:
if (a) {a.clearCustomData();}
Also on line 784:
(d=a.removeCustomData("onResize"))&&d.removeListener();a.remove()
should be changed to:
if (a){(d=a.removeCustomData("onResize"));if (d){d.removeListener();}a.remove()}
This appeared to fix the issue for me, I will also file a bug report with ckeditor so they can fix it as well.
A: The fix is here https://github.com/ckeditor/ckeditor-dev/pull/200 within ckEditor it will check for the existence of the iframe before clearCustomData is invoked. The reason it happens for you is that when the modal closes the iframe is removed before you are able to call destroy on the editor instance.
Try/catch is the best workaround for now. | unknown | |
d5174 | train | Answered my own question!
The Mailgun Api documentation specified api.mailgun.com/v3/YOURDOMAIN
However, if you just use api.mailgun.com everything works fine! | unknown | |
d5175 | train | You can reposition with GameObject.transform.position = (new position here).
A: For the resizing, you can do this
var players = existingPlayerTokensOnLandingSquare.Count + 1;
currentPlayer.transform.localScale = new Vector3(currentPlayer.transform.localScale.x / players,
currentPlayer.transform.localScale.y / players,
currentPlayer.transform.localScale.z / players);
Don't know about the repositioning, or can't think about that now. Hope someone else can answer that one. | unknown | |
d5176 | train | You might want something like that to reload scripts:
<script class="persistent" type="text/javascript">
function reloadScripts()
{ [].forEach.call(document.querySelectorAll('script:not(.persistent)'), function(oldScript)
{
var newScript = document.createElement('script');
newScript.text = oldScript.text;
for(var i=0; i<oldScript.attributes.length; i++)
newScript.setAttribute(oldScript.attributes[i].name, oldScript.attributes[i].value);
oldScript.parentElement.replaceChild(newScript, oldScript);
});
}
// test
setInterval(reloadScripts, 5000);
</script>
As far as I know, there's no other way to reset a script than completely remove the old one and create another one with the same attributes and content. Not even clone the node would reset the script, at least in Firefox.
You said you want to reset timers. Do you mean clearTimeout() and clearInterval()? The methods Window.prototype.setTimeout() and Window.prototype.setInterval() both return an ID wich is to pass to a subsequent call of clearTimeout(). Unfortunately there is no builtin to clear any active timer.
I've wrote some code to register all timer IDs. The simple TODO-task to implement a wrapper callback for setTimeout is open yet. The functionality isn't faulty, but excessive calls to setTimeout could mess up the array.
Be aware that extending prototypes of host objects can cause undefined behavior since exposing host prototypes and internal behavior is not part of specification of W3C. Browsers could change this future. The alternative is to put the code directly into window object, however, then it's not absolutely sure that other scripts will call this modified methods. Both decisions are not an optimal choice.
(function()
{ // missing in older browsers, e.g. IE<9
if(!Array.prototype.indexOf)
Object.defineProperty(Array.prototype, 'indexOf', {value: function(needle, fromIndex)
{ // TODO: assert fromIndex undefined or integer >-1
for(var i=fromIndex || 0; i < this.length && id !== window.setTimeout.allIds[i];) i++;
return i < this.length ? i : -1;
}});
if(!Array.prototype.remove)
Object.defineProperty(Array.prototype, 'remove', { value: function(needle)
{ var i = this.indexOf(needle);
return -1 === i ? void(0) : this.splice(i, 1)[0];
}});
// Warning: Extensions to prototypes of host objects like Window can cause errors
// since the expose and behavior of host prototypes are not obligatory in
// W3C specs.
// You can extend a specific window/frame itself, however, other scripts
// could get around when they call window.prototype's methods directly.
try
{
var
oldST = setTimeout,
oldSI = setInterval,
oldCT = clearTimeout,
oldCI = clearInterval
;
Object.defineProperties(Window.prototype,
{
// TODO: write a wrapper that removes the ID from the list when callback is executed
'setTimeout':
{ value: function(callback, delay)
{
return window.setTimeout.allIds[window.setTimeout.allIds.length]
= window.setTimeout.oldFunction.call(this, callback, delay);
}
},
'setInterval':
{ value: function(callback, interval)
{
return window.setInterval.allIds[this.setInterval.allIds.length]
= window.setInterval.oldFunction.call(this, callback, interval);
}
},
'clearTimeout':
{ value: function(id)
{ debugger;
window.clearTimeout.oldFunction.call(this, id);
window.setTimeout.allIds.remove(id);
}
},
'clearInterval':
{ value: function(id)
{
window.clearInterval.oldFunction.call(this, id);
window.setInterval.allIds.remove(id);
}
},
'clearTimeoutAll' : { value: function() { while(this.setTimeout .allIds.length) this.clearTimeout (this.setTimeout .allIds[0]); } },
'clearIntervalAll': { value: function() { while(this.setInterval.allIds.length) this.clearInterval(this.setInterval.allIds[0]); } },
'clearAllTimers' : { value: function() { this.clearIntervalAll(); this.clearTimeoutAll(); } }
});
window.setTimeout .allIds = [];
window.setInterval .allIds = [];
window.setTimeout .oldFunction = oldST;
window.setInterval .oldFunction = oldSI;
window.clearTimeout .oldFunction = oldCT;
window.clearInterval.oldFunction = oldCI;
}
catch(e){ console.log('Something went wrong while extending host object Window.prototype.\n', e); }
})();
This puts a wrapper method around each of the native methods. It will call the native functions and track the returned IDs in an array in the Function objects of the methods. Remember to implement the TODOs. | unknown | |
d5177 | train | I would rather use apache rewrite engine (or any webserver rewrite process) :
# .htaccess file
RewriteCond %{HTTP_HOST} ^yourdomin\.com$
RewriteRule (.*) http://sub.yourdomin.com/$1 [R=301,L]
A: You can get the hostname with parse_url. Then you break it down with explode():
function hasSubdomain($url) {
$parsed = parse_url($url);
$exploded = explode('.', $parsed["host"]);
return (count($exploded) > 2);
}
On google you can find really easily how to redirect someone. | unknown | |
d5178 | train | If you want to be sure, the only way is to do it yourself. For any given compiler version, you can try out several source-formulations and check the generated core/assembly/llvm byte-code/whatever whether it does what you want. But that could break with each new compiler version.
If you write
fun n = a `seq` b `seq` c `seq` (a, f b, g c)
where
l = map h [1..n]
a = sum l
b = inline f0 $ l
c = inline g0 $ l
or the deepseq version thereof, the compiler might be able to merge the computations of a, b and c to be performed in parallel (not in the concurrency sense) during a single traversal of l, but for the time being, I'm rather convinced that GHC doesn't, and I'd be surprised if JHC or UHC did. And for that the structure of computing b and c needs to be simple enough.
The only way to obtain the desired result portably across compilers and compiler versions is to do it yourself. For the next few years, at least.
Depending on f0 and g0, it might be as simple as doing a strict left fold with appropriate accumulator type and combining function, like the famous average
data P = P {-# UNPACK #-} !Int {-# UNPACK #-} !Double
average :: [Double] -> Double
average = ratio . foldl' count (P 0 0)
where
ratio (P n s) = s / fromIntegral n
count (P n s) x = P (n+1) (s+x)
but if the structure of f0 and/or g0 doesn't fit, say one's a left fold and the other a right fold, it may be impossible to do the computation in one traversal. In such cases, the choice is between recreating l and storing l. Storing l is easy to achieve with explicit sharing (where l = map h [1..n]), but recreating it may be difficult to achieve if the compiler does some common subexpression elimination (unfortunately, GHC does have a tendency to share lists of that form, even though it does little CSE). For GHC, the flags fno-cse and -fno-full-laziness can help avoiding unwanted sharing. | unknown | |
d5179 | train | To answer my own question: After working on this upgrade for some time and running into a few dead ends, for me the following order of steps has turned out best:
*
*Upgrade JSF implementation (in my case: from MyFaces 1.1 to MyFaces 2.2.12)
*Replace JSP files with Facelets and comment out all occurences of tags from unsupported tag libraries (some functionality will be lost until the migration is completed, but this way I have to migrate those taglibs just once - to use them in Facelets - and not twice (once for use in JSPs with JSF 2, and then for use in Facelets))
*Replace and update unsupported and outdated tag libs | unknown | |
d5180 | train | Firt, however, be sure you have proper index then
In your iSiteNumber
You are using multiple subselect for in clause, this force the db engine for repeated access to data ..
for the others part each OR clause mean a repeated access to date
could be that you can rewrite you query avoiding these tecnique
eg instead of the not in for where bPrimarySite = 'true'
( SELECT top 1 iUserID
FROM CustomerSitePermissions where iUserID not in
(SELECT iUserID
FROM CustomerSitePermissions WHERE bPrimarySite = 'true'
)
)
you could use a inner join for the inverted logical query or a simplified query eg:
( SELECT top 1 iUserID
FROM CustomerSitePermissions where
bPrimarySite = 'false'
)
and you could try to rewrite you query for avoid the upper subselect for an IN clause and use a inner join .. if is possible.
These suggestion can be useful or not depending by the real logic and result you really need | unknown | |
d5181 | train | I updated your fiddle with a fix for the first tab with the form: http://jsfiddle.net/E7u9X/1/
. Basically, what you can do is to focus on the first "tabbable" element in a tab after the last one gets blurred, like so:
$('.form input').last().blur(function(){
$('.form input').first().focus();
});
(This is just an example, the first active element could be any other element)
A: Elements with overflow: hidden still have scrolling, just no scroll bars. This can be useful at times and annoying at others. This is why your position left is at zero, but your view of the element has changed. Set scrollLeft to zero when you change "pages", should do the trick. | unknown | |
d5182 | train | You're looking for the command project. You can use it in a "*.do" file this way :
project open MyProject.mpf
project compileall
For all others modelsim commands, you can look at the Modelsim Command Reference Manual. Project command is described in page 220. | unknown | |
d5183 | train | You can initialize them using sequence unpacking (tuple unpacking in this case)
X, Y = [], []
because it's equivalent to
(X, Y) = ([], [])
You can also use a semicolon to join lines in your example:
X = []; Y = []
A: You can use tuple unpacking (or multiple assignment):
X, Y = [], [] | unknown | |
d5184 | train | You didn't post working code; you can't have undefined vars.
Anyway, the problem is that even though you have overridden the constructors, you have not overridden the builders in the companion object. Add this and it will work the way you want:
object Client {
def apply(clientNode: NodeSeq) = new Client(clientNode)
def apply(clientList: List[String]) = new Client(clientList)
}
(if you're using the REPL, be sure to use :paste to enter this along with the case class so you add to the default companion object instead of replacing it).
But a deeper problem is that this is not the way you should be solving the problem. You should define a trait that contains the data you want:
trait ClientData {
def firstName: String
def lastName: String
/* ... */
}
and inherit from it twice, once for each way to parse it:
class ClientFromList(cl: List[String]) extends ClientData {
val firstName = cl.head
. . .
}
or you could turn the NodeSeq into a list and parse it there, or various other things. This way you avoid exposing a bunch of vars which are probably not meant to be changed later.
A: Auxiliary constructors are for simple one-liners and aren't suitable in this case. More idiomatic way would be to define factory methods in a companion object:
case class Client(firstName: String,
lastName: String,
products: List[String] = Nil)
object Client {
import scala.xml.NodeSeq
def fromList(list: List[String]): Option[Client] =
list match {
case List(firstName, lastName) =>
Some(Client(firstName, lastName))
case _ => None
}
def fromXml(nodeSeq: NodeSeq): Option[Client] = {
def option(label: String) =
(nodeSeq \\ label).headOption.map(_.text)
def listOption(label: String) =
(nodeSeq \\ label).headOption.map {
_.map(_.text).toList
}
for {
firstName <- option("firstname")
lastName <- option("lastname")
products <- listOption("products")
} yield Client(firstName, lastName, products)
}
}
I also took the liberty of improving your code by eliminating mutability and making it generally more runtime safe. | unknown | |
d5185 | train | Your best bet is probably to not use a slide gesture, instead use a UIScrollView with a contentSize.width smaller than its frame.size.width (to show the previous/next pages), with pagingEnabled = YES and clipsToBounds = NO. | unknown | |
d5186 | train | To get an enumeration case's name as a String, you can use init(describing:) on String:
enum Foo: Int {
case A
case B
case C
}
let s = String(describing: Foo.A)
print(s) // "A"
You can bake this into the enum:
enum Foo: Int {
case A
case B
case C
var asString: String { return String(describing: self) }
}
let s = Foo.A.asString
print(s) // "A"
A: Pre-requisite: you have an enumeration type with an underlying RawValue; i.e., an enumeration conforming to RawRepresentable.
The C# method Enum.GetName Method (Type,βObject) is described as follows:
Enum.GetName Method (Type,βObject)
public static string GetName(
Type enumType,
object value
)
Parameters
enumType
*
*Type: System.Type
*An enumeration type.
value
*
*Type: System.Object
*The value of a particular enumerated constant in terms of its underlying type.
Return Value
- Type: System.String
- A string containing the name of the enumerated constant in enumType whose value is value; or null if no such constant is
found.
"Translated" into Swift, this method takes an enum type as first argument, and a value of the underlying type of the enum as its second one; where the latter would (for the pre-requisites of RawRepresentable conformance) translate into a value of the RawValue type of the enum in Swift.
Finally, the return type System.String (with possible null return) would translate to an optional String return type in Swift (String?).
Knitting these observations together, you could implement your similar getName method (for finding String representation of your cases represented as YourEnum.RawValue instances at runtime) by combining the init?(rawValue:) blueprinted in RawRepresentable with the init(describing:) initializer of String:
func getName<T: RawRepresentable>(_ _: T.Type, rawValue: T.RawValue) -> String? {
if let enumCase = T(rawValue: rawValue) {
return String(describing: enumCase)
}
return nil
}
/* example setup */
enum Rank: Int {
case n2 = 2,n3,n4,n5,n6,n7,n8,n9,n10,J,Q,K,A
}
/* example usage */
let someRawValue = 7
if let caseName = getName(Rank.self, rawValue: someRawValue) {
print(caseName) // n7
}
This is contrived and coerced "translation" however, as Swift enum:s are quite different (and more powerful) than those of C#. You would generally have an actual instance instance of the enum (e.g. Rank.n7) rather than one of its RawValue (e.g. 7), in which case you could simply use the init(describing:) initializer of String directly as described in the answer of @AlexanderMomchliov. | unknown | |
d5187 | train | The question is where the red squiggly line is coming from. Are you using the erlang-ls extension? If so, you probably need to configure include_dirs in an erlang_ls.config file in the root of your project.
include_dirs:
- "path/to/include" | unknown | |
d5188 | train | The proper way doing this is sending FIN value to the server side.
How ever in android you do not have the option to be involved in this level, so you can implement by your self using C, or use one of the methods you mention in your question.
A: Using HttpUriRequest#about is the right way in my opinion. This will cause immediate termination of the underlying connection and its eviction from the connection pool. Newer versions of HttpClient (4.2 and newer) intercept SocketExceptions caused by premature request termination by the user. The problem is that Google ships a fork of HttpClient based on an extremely outdated version (pre-beta1). If you are not able or willing to use a newer version of HttpClient your only option is to catch and discard SocketException in your code.
A: Use this
client.getConnectionManager().closeExpiredConnections();
client.getConnectionManager().shutdown();
Now you can decide where would you like to write these 2 lines in code.. It will close the connection using the DefaultHttpClient object that you created.
Let me know if this helps you.
A: Try to cancel the task when you want to interrupt the connection:
task.cancel(true);
This will cancel the task and the threads running in it.
Check this for reference:
public final boolean cancel (boolean mayInterruptIfRunning)
Since: API Level 3
Attempts to cancel execution of this task. This attempt will fail if the task has already completed, already been cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when cancel is called, this task should never run. If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task.
Calling this method will result in onCancelled(Object) being invoked on the UI thread after doInBackground(Object[]) returns. Calling this method guarantees that onPostExecute(Object) is never invoked. After invoking this method, you should check the value returned by isCancelled() periodically from doInBackground(Object[]) to finish the task as early as possible.
Parameters
mayInterruptIfRunning true if the thread executing this task should be interrupted; otherwise, in-progress tasks are allowed to complete.
Returns
false if the task could not be cancelled, typically because it has already completed normally; true otherwise | unknown | |
d5189 | train | Pass in you're @Routs parameter to a table valued function that will split the list into a table and then loop through the table and if the value is a negative number execute stored procedure or whatever you want or do nothing if its not negative.
--table function to split parameter by comma
ALTER FUNCTION [dbo].[SplitListOfInts] (@list nvarchar(MAX))
RETURNS @tbl TABLE (number int NOT NULL) AS
BEGIN
DECLARE @pos int,
@nextpos int,
@valuelen int
if len(rtrim(@list)) > 0
begin
SELECT @pos = 0, @nextpos = 1
WHILE @nextpos > 0
BEGIN
SELECT @nextpos = charindex(',', @list, @pos + 1)
SELECT @valuelen = CASE WHEN @nextpos > 0
THEN @nextpos
ELSE len(@list) + 1
END - @pos - 1
INSERT @tbl (number)
VALUES (convert(int, substring(@list, @pos + 1, @valuelen)))
SELECT @pos = @nextpos
END
end
RETURN
END
-- stored procedure that calls that split function and uses @routs parameter
CREATE TABLE #values(nbrValue int)
INSERT INTO #values(nbrValue
EXEC [dbo].[SplitListOfInts] @routs
--if you don't care about non-negatives delete them here
DELETE FROM #values
where nbrValue >= 0
DECLARE @i int
DECLARE @countrows = (SELECT COUNT(nbrValue) FROM #values)
WHILE @countrows >0
SET @i = (SELECT TOP 1 nbrValue FROM #values)
...do what you want
DELETE FROM #values where nbrValue=@i
set @countrows = (SELECT COUNT(nbrValue) FROM #values)
END | unknown | |
d5190 | train | Set httpBody to your data from dictionary
let trimmedUrl = urlStr.trimmingCharacters(in: CharacterSet(charactersIn: "")).replacingOccurrences(of: " ", with: "%20")
let url = URL(string: trimmedUrl)!
let dic:[String:Any] = ["address_id" : "4064", "customer_id" : "3239", "language_id" : "1", "products" : [ [ "option" : "", "product_id" : "1576", "quantity" : "2" ], [ "option" : "", "product_id" : "1573", "quantity" : "1" ], [ "option" : "", "product_id" : "1575", "quantity" : "1" ] ], "set_currency" : "EUR" ]
let data = try? JSONSerialization.data(withJSONObject: dic)
var req = URLRequest(url: url)
req.httpBody = data
self.webView.load(req)
A: Firstly you need to make sure that the url string is valid, try printing it
print(urlStr)
The post parameters are not url params usually, but http body parameters, thus need to be added to the body of the request. You need to know what format the server is expecting. Modern apis use JSON so you'd need to format your dictionary to json (however the dictionary you posted is actually not a swift dictionary, so it looks ok.).
let urlStr = "https://test.com/index.php?route=checkout/checkout_mobile"
let trimmedUrl = urlStr.trimmingCharacters(in: CharacterSet(charactersIn: "")).replacingOccurrences(of: " ", with: "%20")
let url = URL(string: trimmedUrl)
let request = URLRequest(url: url)
request.httpBody = Data(cartDict.utf8)
self.webView.load(request)
A: From the comments
when i convert this String (urlStr) to URLRequest it returns nil
If this is your question or it maybe useful for others in future.
extension URL {
public var queryParameters: [String: Any]? {
guard let components = URLComponents(url: self, resolvingAgainstBaseURL: true), let queryItems = components.queryItems else { return nil }
return queryItems.reduce(into: [String: String]()) { (result, item) in
result[item.name] = item.value
}
}
}
In your WKNavigationDelegate methods on redirection
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard let url = navigationAction.request.url else {
decisionHandler(.allow)
return
}
if url.absoluteString.lowercased().range(of: "redirection/url/you/expected/to/intercept") != nil {
var parameters: [String: Any]?
if let requestBody = navigationAction.request.httpBody {
//If your data is JSON
let requestJSON = try? JSONSerialization.jsonObject(with: requestBody, options: [])
if requestJSON = requestJSON as? [String: Any] {
parameters = requestJSON
}else {
//If your data is utf8 encoded string
let queryUrl = URL(string: url.absoluteString + "?" + String(decoding: requestBody, as: UTF8.self))
parameters = queryUrl?.queryParameters
}
}
//Your post payload in parameters
//Handle it the way you want.
}
decisionHandler(.allow)
} | unknown | |
d5191 | train | On the line with substr, you have a string of whitespace followed by a literal tab character, and on the line with skip you have the same string followed by four spaces. These are incompatible; one robust, flexible way to get this right is to line things in a block up with exact the same string of whitespace at the beginning of each line.
The real rule, though, since you asked, is that tabs increase the indentation level to the next multiple of eight, and all other characters increase the indentation level by one. Different lines in a block must be at the same indentation level. do, where, let, and of introduce blocks (I may be forgetting a few). | unknown | |
d5192 | train | You can configure a 'format' hook to change the way that the text value is formatted before it gets displayed.
For example to add a percentage sign to the text you could do something like:
$(".dial").knob({
'format' : function (value) {
return value + '%';
}
});
The value that gets passed in is the number, and whatever the function returns is what gets displayed. | unknown | |
d5193 | train | You can try this:
var button_id = $(e.target).closest('div').attr('id');
var id = button_id.substring(12);
var idArray = [];
if (idArray.indexOf(id) === -1) {
ajaxCall = $.ajax({
method: 'POST',
url: 'update_like.php',
data: {id:id},
success: function(){
//
idArray.push(id);
},
error: function(){
//
}
});
}
On server side you can try this:
Assuming ID to be a comma separated list.
UPDATE posts
SET likes = likes+1
WHERE id = '$id'
AND FIND_IN_SET('$id', listofuserid) = 0 | unknown | |
d5194 | train | On line 44: await i.deferUpdate({ fetchReply: true }); It makes the error because the interaction has already been replied to. The error should go away when you remove this line. You also should replace await interaction.editReply with interaction.followUp on line 51, 60, 71, 80, 90, 96 and 106. And yup I answer your question again. | unknown | |
d5195 | train | Looking at your code you didn't put your player array to use.
However, I would suggest a more object oriented approach.
public class PlayerScoreModel
{
public int Score{get;set;}
public string Name {get;set;}
}
Store the player and scores in a List<PlayerScoreModel>.
And when the last user and score has been entered.. simply iterate through the list.
do {
Console.Write("Player name and score: ", index + 1);
string playerScore = Console.ReadLine();
if (playerScore == "")
break;
string[] splitStrings = playerScore.Split();
PlayerScoreModel playerScoreModel = new PlayerScoreModel() ;
playerScoreModel.Name = splitStrings[0];
playerScoreModel.Score = int.Parse(splitStrings[1]);
playerScoreModels.Add(playerScoreModel) ;
} while (somecondition);
foreach(var playerScoreModel in playerScoreModels)
{
Console.WriteLine(playerScoreModel.Name +" " playerScoreModel.Score) ;
}
Provide error checking as necessary. | unknown | |
d5196 | train | Try this:
SELECT DATEPART(week,'18-nov-2012') | unknown | |
d5197 | train | Here is a way to filter using the dplyr package (since there is no data provided I used the iris dataset) :
suppressPackageStartupMessages( library(dplyr) )
iris <- iris %>%
as_tibble() %>%
mutate(Species = as.character(Species))
iris %>%
filter(Species %in% c("setosa", "virginica") &
Sepal.Length %>% between(4.5, 5)
)
#> # A tibble: 25 x 5
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> <dbl> <dbl> <dbl> <dbl> <chr>
#> 1 4.9 3 1.4 0.2 setosa
#> 2 4.7 3.2 1.3 0.2 setosa
#> 3 4.6 3.1 1.5 0.2 setosa
#> 4 5 3.6 1.4 0.2 setosa
#> 5 4.6 3.4 1.4 0.3 setosa
#> 6 5 3.4 1.5 0.2 setosa
#> 7 4.9 3.1 1.5 0.1 setosa
#> 8 4.8 3.4 1.6 0.2 setosa
#> 9 4.8 3 1.4 0.1 setosa
#> 10 4.6 3.6 1 0.2 setosa
#> # ... with 15 more rows
You can then store the result in an object when you are satisfied (it should work with dates too). | unknown | |
d5198 | train | In the UserSerializer you are declaring some of the model fields again such as email etc. By doing that the behavior of the field is not copied from how it was defined on the model. It works as if that behavior has been overridden.
You can drop email = serializers.EmailField() and then the default behaviour would kick in and you will get to see the error message corresponding to unique field.
In the same fashion you could drop other fields too which are just replicas of the fields on the model. | unknown | |
d5199 | train | In Facelets 1.x you can create a tag file for this purpose.
Here's a basic kickoff example. Create /WEB-INF/tags/some.xhtml:
<ui:composition
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
>
<h:outputText value="#{foo}" />
</ui:composition>
Define it in /WEB-INF/my.taglib.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE facelet-taglib PUBLIC
"-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN"
"http://java.sun.com/dtd/facelet-taglib_1_0.dtd">
<facelet-taglib>
<namespace>http://example.com/jsf/facelets</namespace>
<tag>
<tag-name>some</tag-name>
<source>/WEB-INF/tags/some.xhtml</source>
</tag>
</facelet-taglib>
Register it in /WEB-INF/web.xml:
<context-param>
<param-name>facelets.LIBRARIES</param-name>
<param-value>/WEB-INF/my.taglib.xml</param-value>
</context-param>
(note, when you have multiple, use semicolon ; to separate them)
Finally just declare it in your main page templates.
<ui:composition
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:my="http://example.com/jsf/facelets"
>
<my:some foo="value1" />
<my:some foo="value2" />
<my:some foo="value3" />
</ui:composition>
A more advanced example can be found here: How to make a grid of JSF composite component? Note: JSF 2.0 targeted, but with minor changes based on above example it works as good on Facelets 1.x. | unknown | |
d5200 | train | Self response. Mentioning column that I want to order by in SELECT clause and aliasing it did the trick:
SELECT
m.*, COUNT(*) as cnt
FROM
products_description pd,
products p
left outer join manufacturers m on p.manufacturers_id = m.manufacturers_id,
products_to_categories p2c
WHERE
p.products_carrot = '0' and
p.products_status = '1' and
p.products_id = p2c.products_id and
pd.products_id = p2c.products_id and
pd.language_id = '4' and
p2c.categories_id = '42'
GROUP BY p.manufacturers_id
ORDER BY cnt | 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.