_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d5001 | train | This should work:
location / {
# try to serve file directly, fallback to rewrite
try_files $uri @rewriteapp;
}
location @rewriteapp {
# rewrite all to app.php
rewrite ^(.*)$ /index.php/$1 last;
}
location ~ ^/index\.php(/|$) {
try_files @heroku-fcgi @heroku-fcgi;
internal;
}
A: Try to follow the instructions in the documentation: http://docs.phalconphp.com/fr/latest/reference/nginx.html
server {
listen 80;
server_name localhost.dev;
index index.php index.html index.htm;
set $root_path '/var/www/phalcon/public';
root $root_path;
try_files $uri $uri/ @rewrite;
location @rewrite {
rewrite ^/(.*)$ /index.php?_url=/$1;
}
location ~ \.php {
fastcgi_pass unix:/run/php-fpm/php-fpm.sock;
fastcgi_index /index.php;
include /etc/nginx/fastcgi_params;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
location ~* ^/(css|img|js|flv|swf|download)/(.+)$ {
root $root_path;
}
location ~ /\.ht {
deny all;
}
} | unknown | |
d5002 | train | It's better do this kind of thing on web-server level rather than in app code.
For IIS, you need to change file Web.config by adding a rewrite rules.
I was not able to test it, but you should add something like that:
<rewrite>
<rules>
<rule name="Redirect to www" patternSyntax="Wildcard" stopProcessing="true">
<match url="*" />
<conditions>
<add input="{HTTP_HOST}" pattern="example.com" />
</conditions>
<action type="Redirect" url="http://www.example.com/{R:0}" />
</rule>
<rule name="HTTP Redirect to HTTPS" enabled="true" stopProcessing="true">
<match url="(.*)" ignoreCase="false" />
<conditions>
<add input="{HTTPS}" pattern="off" />
</conditions>
<action type="Redirect" url="https://www.example.com/{R:1}" appendQueryString="true" redirectType="Permanent" />
</rule>
</rules>
A: The issue was with the DNS on our domain provider. | unknown | |
d5003 | train | Lets start with your other question
If my data on disk is guaranteed to be pre-sorted by the key which will be used for a group aggregation or reduce, is there any way for Spark to take advantage of that?
It depends. If operation you apply can benefit from map-side aggregation then you can gain quite a lot by having presorted data without any further intervention in your code. Data sharing the same key should located on the same partitions and can be aggregated locally before shuffle.
Unfortunately it won't help much in this particular scenario. Even if you enable map side aggregation (groupBy(Key) doesn't use is so you'll need custom implementation) or aggregate over feature vectors (you'll find some examples in my answer to How to define a custom aggregation function to sum a column of Vectors?) there is not much to gain. You can save some work here and there but you still have to transfer all indices between nodes.
If you want to gain more you'll have to do a little bit more work. I can see two basic ways you can leverage existing order:
*
*Use custom Hadoop input format to yield only complete records (label, id, all features) instead of reading data line by line. If your data has fixed number of lines per id you could even try to use NLineInputFormat and apply mapPartitions to aggregate records afterwards.
This is definitely more verbose solution but requires no additional shuffling in Spark.
*Read data as usual but use custom partitioner for groupBy. As far as I can tell using rangePartitioner should work just fine but to be sure you can try following procedure:
*
*use mapPartitionsWithIndex to find minimum / maximum id per partition.
*create partitioner which keeps minimum <= ids < maximum on the current (i-th) partition and pushes maximum to the partition i + 1
*use this partitioner for groupBy(Key)
It is probably more friendly solution but requires at least some shuffling. If expected number of records to move is low (<< #records-per-partition) you can even handle this without shuffle using mapPartitions and broadcast* although having partitioned can be more useful and cheaper to get in practice.
* You can use an approach similar to this: https://stackoverflow.com/a/33072089/1560062 | unknown | |
d5004 | train | You should accept the unique_ptr from the get-go:
class SomeClass
{
std::vector<std::unique_ptr<MyObject>> myObjects;
public:
// tells the world you 0wNz this object
void takeOwnership(std::unique_ptr<MyObject> myObject)
{
myObjects.push_back(std::move(myObject));
}
};
This way you make it clear you take ownership and you also help other programmers to avoid using raw pointers.
Further reading: CppCoreGuidelines R.32
A: The move is redundant.
Myself, I'd do this:
void takeOwnership(std::unique_ptr<MyObject> nowItsReallyMyObject)
{
myObjects.emplace_back(std::move(nowItsReallyMyObject));
}
because I would want to move the unique_ptr ownership semantics as far "out" as possible.
I might write this utility function:
template<class T>
std::unique_ptr<T> wrap_in_unique( T* t ) {
return std::unique_ptr<T>(t);
}
so callers can:
foo.takeOwnership(wrap_in_unique(some_ptr));
but even better, then can push the borders of unique_ptr semantics out as far as they reasonably can.
I might even do:
template<class T>
std::unique_ptr<T> wrap_in_unique( T*&& t ) {
auto* tmp = t;
t = 0;
return std::unique_ptr<T>(tmp);
}
template<class T>
std::unique_ptr<T> wrap_in_unique( std::unique_ptr<T> t ) {
return std::move(t);
}
which lets callers transition their T* into unique_ptrs easier. All of their T*->unique_ptr<T> is now wrapped in a std::move, and zeros the source pointer.
So if they had
struct I_am_legacy {
T* I_own_this = 0;
void GiveMyStuffTo( SomeClass& sc ) {
sc.takeOwnership( wrap_in_unique(std::move(I_own_this)) );
}
};
the code can be transformed into:
struct I_am_legacy {
std::unique_ptr<T> I_own_this;
void GiveMyStuffTo( SomeClass& sc ) {
sc.takeOwnership( wrap_in_unique(std::move(I_own_this)) );
}
};
and it still compiles and works the same. (Other interaction with I_own_this may have to change, but part of it will already be unique_ptr compatible). | unknown | |
d5005 | train | Yes , It is possible. You can add dagger for ongoing project and use it. | unknown | |
d5006 | train | You was on the right path. In your case, you would need to add the the following entries in the registry:
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\3.8]
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\3.8\InstallPath]
@="C:\\python38\\"
"ExecutablePath"="C:\\Python38\\python.exe"
"WindowedExecutablePath"="C:\\Python38\\pythonw.exe"
Also answered in py launcher does not find my Python 2.7 | unknown | |
d5007 | train | I was also facing issues in initiating safari browser on mac machine, and below solution helped me
if (browserType.equals("safari")) {
// System.setProperty("webdriver.safari.driver", workingDir +
// "//driver//SafariDriverServer.exe");
System.setProperty("webdriver.safari.driver",
"/driver/SafariDriver.safariextz");
System.setProperty("webdriver.safari.noinstall", "true");
DesiredCapabilities desiredCapabilities = DesiredCapabilities
.safari();
SafariOptions safariOptions = new SafariOptions();
safariOptions.setUseCleanSession(true);
safariOptions.getUseCleanSession();
safariOptions.setUseCleanSession(true);
desiredCapabilities.setCapability(SafariOptions.CAPABILITY,
safariOptions);
// deleteCookies();
driver = new EventFiringWebDriver(new SafariDriver());
ThreadDriver.set(driver);
// driver.manage().window().setSize(new Dimension(1024, 850));
getDriver().manage().timeouts().implicitlyWait(3,
TimeUnit.SECONDS);
wait = new WebDriverWait(driver, 30);
} | unknown | |
d5008 | train | You need to explicitly set the tags to .* | unknown | |
d5009 | train | Just put
adapter.imageLoader.stopThread();
to "Cancel" button click handler
A: You can write your own custom class which extends the Java Thread class. There you implement a public stop-method which stop the thread itself. When you create and start your thread you hold a reference to it and call the public stop-method in the OnClickEventHandler of the cancel button. | unknown | |
d5010 | train | When a requests ends, the readyState is 4, but the status may be a value other than 200. If the status is 0, that indicates a network error or CORS failure (for cross-origin servers). If it is some other value (like 404), that means the script reached the server, but the server didn't handle the request successfully (either because the URL path used wasn't meaningful, or a server-side error occurred, etc.)
ping.onreadystatechange = function(){
document.body.innerHTML += "<br>" + ping.readyState;
if(ping.readyState == 4){
if(ping.status == 200){
result = ping.getAllResponseHeaders();
document.body.innerHTML += "<br>" + result + "<br>";
} else if(ping.status == 0) {
document.getElementById("foobar").innerHTML = "Ping is not successful! Could not get any response from the server, due to a network failure, CORS error, or offline server.";
} else {
result = ping.getAllResponseHeaders();
document.getElementById("foobar").innerHTML = "We got a response from the server, but it was status code " + ping.status;
}
}
} | unknown | |
d5011 | train | There are no tasks in your python role. Please have a look at the role structure.
If roles/x/tasks/main.yml exists, tasks listed therein will be added to the play
Tasks file (main.yml) should be placed in the tasks subdirectory of the role, not in the main role's directory.
And this has nothing to do with how you described the problem (installing Python or Pip). Even if you replaced the tasks with a single debug task which displays Hello world by default, it would not run. | unknown | |
d5012 | train | There is no direct way for manipulating with INI files in .NET.
Also INI files consist of key/value pairs, for example like this:
[Month]
Jan = 1
Feb = 2
Mar = 3
In case you can use the appropriate INI structure then I can suggest you to use my library to accomplish INI files processing:
https://github.com/MarioZ/MadMilkman.Ini
Here is how you would achieve your task for the above provided INI content:
Dim ini As New IniFile
ini.Load("path to your INI file")
For Each key In ini.Sections("Month").Keys
' Jan, Feb and Mar
Me.ComboBox1.Items.Add(key.Name)
' 1, 2 and 3
Me.ComboBox2.Items.Add(key.Value)
Next | unknown | |
d5013 | train | Please read this,
1. Download FMDB files.
2. Add into your project.
3. Read path into your viewController.m
Follow the instruction on the website, if problem then feel free to contact.
link : https://github.com/ccgus/fmdb
A: Well, you can go with any sqlite wrappers written in objective-c.
I will suggest FMDB because it is very widely used and easy to learn as well. | unknown | |
d5014 | train | By analyzing your requirements you can get a better idea of the data structures to use. Since you need to map keys (account/company) to values (name/rep) I would start with a HashMap. Since you want to condense the values to remove duplicates you'll probably want to use a Set.
I would have a Map<Key, Data> with
public class Key {
private String account;
private String companyName;
//Getters/Setters/equals/hashcode
}
public class Data {
private Key key;
private Set<String> names = new HashSet<>();
private Set<String> reps = new Hashset<>();
public void addName(String name) {
names.add(name);
}
public void addRep(String rep) {
reps.add(rep);
}
//Additional getters/setters/equals/hashcode
}
Once you have your data structures in place, you can do the following to populate the data from your CSV and output it to its own CSV (in pseudocode)
Loop each line in CSV
Build Key from account/company
Try to get data from Map
If Data not found
Create new data with Key and put key -> data mapping in map
add name and rep to data
Loop values in map
Output to CSV
A: Well, I probably would create a class, let's say "Account", with the attributes "accountName", "fullName", "customerSystemName", "salesRep". Then I would define an empty ArrayList of type Account and then loop over the read lines. And for every read line I just would create a new object of this class, set the corresponding attributes and add the object to the list. But before creating the object I would iterate overe the already existing objects in the list to see whether there is one which already has this company name - and if this is the case, then, instead of creating the new object, just reset the salesRep attribute of the old one by adding the new value, separated by comma.
I hope this helps :) | unknown | |
d5015 | train | I agree with the comment from Habib.
The oracle .NET Package uses connection pooling. Even if you open up multiple connections, it will manage them accordingly so that you don't have to keep it open.
That means that your code can be simplified, into something like this pseudo-code:
using(OracleConnection conn = MakeConnection())
{
//do stuff with connection
//not necessary, but I always manually close connection. Doesn't hurt.
conn.Close();
}
If you're uncertain of connection issues even in that small of an execution, you can wrap it in a try-catch block like so:
try
{
using(OracleConnection conn = MakeConnection())
{
//do stuff with connection
//not necessary, but I always manually close connection. Doesn't hurt.
conn.Close();
}
}
catch(OracleException ex)
{
//handle exception.
}
OracleException looks to be the main exception with the .NET oracle package. Please note that there may be others you want to catch more specifically.
A: It would be easier to instantiate the connection on the fly when the query is being made. I don't think a simple try/catch would help you here because even if you reinitialized the connection in the catch block, you would have to somehow re-execute your query.
I don't recommend this but you could use a Retry class that reinitializes the connection if an exception is caught....
public class Retry
{
public static void Do(Action action, TimeSpan retryInterval, int retryCount = 3)
{
Do<object>(() =>
{
action();
return null;
},
retryInterval, retryCount);
}
public static T Do<T>(Func<T> action, TimeSpan retryInterval, int retryCount = 3)
{
var exceptions = new List<Exception>();
for (int retry = 0; retry < retryCount; retry++)
{
try
{
if (retry > 0)
Thread.Sleep(retryInterval);
return action();
}
catch (ConnectionException ex)
{
// ***Handle the reconnection in here***
exceptions.Add(ex);
}
}
throw new AggregateException(exceptions);
}
}
Then you can call your query like
Retry.Do(() => MyQueryMethod, TimeSpan.FromSeconds(5));
I got the basis for this Retry code from SO a long time ago, don't recall the thread but it isn't my original code. I have used it quite a bit for some things though. | unknown | |
d5016 | train | You need to use quo_name. This works:
f1 <- function(df, x, y) {
x <- enquo(x)
y <- enquo(y)
df %>%
mutate(
!!quo_name(x) := (!!x)^2,
!!quo_name(y) := (!!y)+1)
}
dat <- data.frame(a=1:10, b=10:1)
f1(dat, x=a, y=b) | unknown | |
d5017 | train | Not sure if I understand you right, but if it is a plain vanilla String with XML data which you want to display as-is in the JSF page, then the first logical step would be to escape the HTML entities so that it's not been parsed as HTML. You can use h:outputText for this, it by default escapes HTML entities (which is controllable by the 'escape' attribute by the way):
<h:outputText value="#{bean.xmlString}" />
Or if it is formatted and you want to preserve the formatting, then apply the CSS white-space:pre property on the parent HTML element.
Or if you want to add syntax highlighting (colors and so on), then consider a Javascript library which does the task. Googling "javascript xml syntax highlighting" should yield enough results. | unknown | |
d5018 | train | Here is the query:
SELECT * FROM Table1 AS t1
JOIN table3 as t3 ON t1.ID_table1 = t3.ID_table1
JOIN table2 as t2 ON t1.ID_table1 = t2.ID_table1
JOIN table4 as t4 ON t2.ID_table2 = t4.ID_table2 | unknown | |
d5019 | train | Figured it out myself, finally.
The Short Answer
It appears that a new feature introduced in EbeanORM 6.4.1 breaks something. This is the feature in question: https://github.com/ebean-orm/avaje-ebeanorm/issues/390.
Downgrading (see below) to 6.3.1 resolves the issue.
The Long Answer
I had been using EbeanORM 6.3.1 when I first got things working. I upgraded to 6.4.1, seeing that it had been released a couple days ago. I noticed that things broke shortly after (no automated tests yet). I downgraded to 6.3.1 again, but this didn't fix things so I assumed it was a red herring.
Unbeknownst to me, SBT/Ivy was evicting 6.3.1 in favour of 6.4.1, even though I was explicitly depending on 6.3.1. avaje-ebeanorm-spring, which I'm also using, depends on avaje-ebeanorm with version specifier [6,7). So, for some reason, SBT/Ivy decided that 6.4.1 was the best resolution of these two version requirements (WTF.... ).
I figured this out with this excellent plugin: https://github.com/jrudolph/sbt-dependency-graph.
To force SBT to give me 6.3.1, I modified my dependencies to add the exclude:
"org.avaje.ebeanorm" % "avaje-ebeanorm" % "6.3.1",
"org.avaje.ebeanorm" % "avaje-ebeanorm-spring" % "4.5.3" exclude("org.avaje.ebeanorm", "avaje-ebeanorm") | unknown | |
d5020 | train | You cannot disable a list cause its not a interactive element can use ngClass to apply a specific class when disabled to make it appear disabled:
<li ng-class="{'disabled':condition}"ng-click="getRadius(5)">item</li>
You can use ng-if to remove those items completely from the list:
<li ng-if="!condition" ng-click="getRadius(5)">item</li>
<li ng-if="condition" >item</li>
A: If you use button tag as trigger instead of li, you can use ng-disabled directive to permit click by a condition. For example:
<ul class="cf" id="filter">
<li><button ng-click="getRadius(5)" ng-disabled="current!=5">5 km</button></li>
<li><button ng-click="getRadius(10)" ng-disabled="current!=10">10 km</button></li>
<li><button ng-click="getRadius(25)" ng-disabled="current!=25">25 km</button></li>
<li><button ng-click="getRadius(50)" ng-disabled="current!=50">50 km</button></li>
<li><button ng-click="getRadius(100)" ng-disabled="current!=100">100 km</button></li>
</ul>
If you want, you can customize button style and you can show it like a standart text element.
.cf button {
border: none;
background: none;
}
A: // template
<ul class="cf" id="filter">
<li ng-click="!clickLi[5] && getRadius(5)" class="current"><a href="#">5 km</a></li>
<li ng-click="!clickLi[10] && getRadius(10)"><a href="#">10 km</a></li>
<li ng-click="!clickLi[25] && getRadius(25)"><a href="#">25 km</a></li>
<li ng-click="!clickLi[50] && getRadius(50)"><a href="#">50 km</a></li>
<li ng-click="!clickLi[100] && getRadius(100)"><a href="#">100 km</a></li>
</ul>
// controller
function MyController($scope) {
$scope.clickLi = {
5: true
};
$scope.getRadius = function(li_id) {
$scope.clickLi[li_id] = true;
console.log(li_id);
};
}
A demo on JSFiddle.
A: Possible workaround:
If you need a single selection you can add variable into the scope specifying which row is selected and generate your list with the ng-repeat, then you can add lazy checking on ng-click if current $index is equal to selected index, you can use the same condition to apply current class with ng-class.
For example:
app.js
$scope.selected = 0;
$scope.distances = [5, 10, 25, 50, 100];
app.html
<ul class="cf" id="filter">
<li ng-repeat = "distance in distances" ng-click="($index == selected) || getRadius(distance)" ng-class="{'current':($index == selected)}"><a href="#">{{distance}} km</a></li>
</ul> | unknown | |
d5021 | train | The reason for this is because the context of this varies depending on how the function is called, not what the function was originally attached to.
One relatively easy way to do this is to bind _anEvent to the instance of the class.
constructor() {
this._customAtt = "hello";
this._anEvent = this._anEvent.bind(this);
}
This will ensure that this is always the instance of myClass within the _anEvent function. | unknown | |
d5022 | train | Typically you will use a return statement. When you call return any code below it will not get executed. Although, if your functions isIt() or isItReally() are asynchronous functions then you will be running into trouble as those are used in a synchronous fashion. | unknown | |
d5023 | train | Since bullet points are part of the list items I don't think you will be able to align them. Why not try something like having a top column with 3 divs and place your validationsummary control in the middle one. Try this
HTML Code
<div id="container" class="container">
<div id="top" class="top">
<div id="topLeft" class="topLeft">
</div>
<div id="topMiddle" class="topMiddle">
<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
</div>
<div id="topRight" class="topRight">
</div>
</div>
<div id="bottom" class="bottom">
<div id="bottomLeft" class="bottomLeft">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="input value" ControlToValidate="TextBox1" Text="*"></asp:RequiredFieldValidator><br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Need come input for this" ControlToValidate="TextBox2" Text="*"></asp:RequiredFieldValidator><br />
<asp:Button ID="Button1" runat="server" Text="Button" />
</div>
<div id="bottomRight" class="bottomRight">
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="please input text" ControlToValidate="TextBox3" Text="*"></asp:RequiredFieldValidator><br />
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="Where is the text?" ControlToValidate="TextBox4" Text="*"></asp:RequiredFieldValidator><br />
<asp:Button ID="Button2" runat="server" Text="Button" />
</div>
</div>
</div>
CSS
.container
{
display: block;
width:800px;
margin:0px;
padding:0px;
}
.top
{
display:inline-block;
width:800px;
}
.bottom
{
display:inline-block;
}
.topMiddle
{
display:inline;
background-color:Yellow;
float:left;
width:300px;
}
.topLeft
{
display:inline;
float:left;
width:250px;
}
.topRight
{
display:inline;
float:left;
width:250px;
}
.bottomLeft
{
display:inline;
width:400px;
float:left;
background-color:Orange;
}
.bottomRight
{
display:inline;
width:400px;
float:left;
background-color:Lime;
}
A: Try using this one....
<style>
.validator ul li { text-align:left; }
</style>
Edit
Set padding left or margin left to ul as you want...
.validator ul { padding-left: 100px; }
A: Hey you may define your parent text-align left center right
according to your design | unknown | |
d5024 | train | This variable is readed in your configuration file. Then it's used in the wrapper around Nunjucks (in View/index.js).
You can find more information about Nunjucks Cache in the documentation of loaders. | unknown | |
d5025 | train | Uses of belongsTo in CakePhp
class Deposit extends AppModel {
public $useTable = 'deposits';
public $validate = array();
public function __construct($id = false, $table = null, $ds = null) {
parent::__construct($id, $table, $ds);
}
public function getDepositAmount() {
$this->belongsTo('User')
->setForeignKey('user_id');
// your find query here
}
}
Please read doc first for better understanding CakePhp Doc | unknown | |
d5026 | train | Some logic, Numpy and list comprehensions are sufficient here.
I will break it down step by step, you can make it slimmer and prettier afterwards:
import numpy as np
my_val = 15
block_size = 4
total_groups = 3
d1 = [3, 12, 5, 5, 5, 4, 11]
d2 = np.cumsum(d1)
d3 = d2 % my_val == 0 #find where sum of elements is 15 or multiple
split_points= [i+1 for i, x in enumerate(d3) if x] # find index where cumsum == my_val
#### Option 1
split_array = np.split(d1, split_points, axis=0)
padded_arrays = [np.pad(array, (0, block_size - len(array)), mode='constant') for array in split_array] #pad arrays
padded_d1 = np.concatenate(padded_arrays[:total_groups]) #put them together, discard extra group if present
#### Option 2
split_points = [el for el in split_points if el <len(d1)] #make sure we are not splitting on the last element of d1
split_array = np.split(d1, split_points, axis=0)
padded_arrays = [np.pad(array, (0, block_size - len(array)), mode='constant') for array in split_array] #pad arrays
padded_d1 = np.concatenate(padded_arrays) | unknown | |
d5027 | train | Notice you are checking if $_GET["edit_me"] == "true" (string true) in the PHP page but that would mean that you should be sending edit_me: "true" in your ajax. Change your $_GET to:
# This will just check the key is filled
if(!empty($_GET["edit_me"]))
Then fix the SQL injection (you can Google that) and then send back instead of that javascript alert string you are doing:
die(json_encode(['success'=>(mysqli_query($con, $query))]));
This would send back to the ajax response {"success":true}if it worked. Since you are not specifically expecting json, you can parse the response:
// I changed the param here from data to response
success: function(response) {
// Parse the response
var data = JSON.parse(response);
// Alert either way
alert((data.success == true)? "Updated" : "Not Updated");
// Do whatever this is
setTimeout( function ( ) {
alert( 'Data has been Deleted From Database' );
},600 );
} | unknown | |
d5028 | train | devise_scope :user do
root 'devise/sessions#new' end should solve the issue.
Setting devise
/sessions#new as root is not a good idea.The devise/session#new redirect to '/' if the user is signed in.This will cause a redirect loop if the user is already signed in .Its better if there is some consultation hub controller as root which checks whether the user is signed in and redirect to devise/session#new if he is not. | unknown | |
d5029 | train | You need to adjust the query. This query works for me.
client.query("SHOW TABLES FROM DB") DB being your database.
In your connection string you are specifying a database to connect to, so I don't believe you will be able to run SHOW DATABASES. Try removing the DB from the connection string. | unknown | |
d5030 | train | Calling Bitmap.LockBits() followed by Bitmap.UnlockBits() does nothing.
The behavior you observe is because of loading a JPEG image, and then saving it again. JPEG uses a lossy algorithm. So what happens:
*
*You load the JPEG from disk
*The JPEG data gets decoded into individual pixels with color information, i.e. a bitmap
*You save the bitmap again in the JPEG format, resulting in a different file than #1
You also potentially lose metadata that was present in the JPEG file in doing so. So yes, the file is different and probably smaller, because every time you do this, you lose some pixel data or metadata.
Lockbits/Unlockbits are used to allow the program to manipulate the image data in memory. Nothing more, nothing less. See also the documentation for those methods.
A: Use the LockBits method to lock an existing bitmap in system memory so that it can be changed programmatically. You can change the color of an image with the SetPixel method, although the LockBits method offers better performance for large-scale changes.
A Rectangle structure that specifies the portion of the Bitmap to lock.
Example:
private void LockUnlockBitsExample(PaintEventArgs e)
{
// Create a new bitmap.
Bitmap bmp = new Bitmap("c:\\fakePhoto.jpg");
// Lock the bitmap's bits.
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
System.Drawing.Imaging.BitmapData bmpData =
bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
bmp.PixelFormat);
// Get the address of the first line.
IntPtr ptr = bmpData.Scan0;
// Declare an array to hold the bytes of the bitmap.
int bytes = Math.Abs(bmpData.Stride) * bmp.Height;
byte[] rgbValues = new byte[bytes];
// Copy the RGB values into the array.
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
// Set every third value to 255. A 24bpp bitmap will look red.
for (int counter = 2; counter < rgbValues.Length; counter += 3)
rgbValues[counter] = 255;
// Copy the RGB values back to the bitmap
System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);
// Unlock the bits.
bmp.UnlockBits(bmpData);
// Draw the modified image.
e.Graphics.DrawImage(bmp, 0, 150);
} | unknown | |
d5031 | train | I think you are mistaking some concepts. If I got it right you need a CDN for an Apache server on EC2. In that case you want Cloudfront with EC2 as origin . https://aws.amazon.com/cloudfront/getting-started/EC2/ | unknown | |
d5032 | train | I Tried with the curl commands which worked for me :
curl --request POST 'http://10.226.45.6/cgi-bin/auto_dispatch.cgi HTTP/1.1' --data 'taskid=111&submit=submit'
curl --request POST 'http://10.226.45.6/cgi-bin/auto_free.cgi HTTP/1.1' --data 'submit=submit' | unknown | |
d5033 | train | I recreated your set of tables with
A location_label table
create table location_label(location_id int, location_label varchar);
insert into location_label values(1, 'Home');
insert into location_label values(2, 'Office');
insert into location_label values(3, 'Garage');
insert into location_label values(4, 'Bar');
A stock_location_type table
create table stock_location_type (stock_location_type_id int, inventory_location_cd varchar);
insert into stock_location_type values(1, 'base location');
insert into stock_location_type values(2, 'Not base location');
A location table
create table location (stock_catalogue_id int, base_location_id int, related_location_id int, stock_location_type_id int);
insert into location values(1,1,2,1);
insert into location values(1,2,1,2);
insert into location values(1,3,3,1);
insert into location values(2,4,3,1);
insert into location values(2,3,1,1);
insert into location values(2,2,4,2);
If I understand your statement correctly you are trying to join location and location_label tables based on the inventory_location_cd column using either base_location_id or location_id.
If this is what you're trying to achieve, the following query should do it. By moving the join condition in the proper place
select L.stock_catalogue_id,
SLT.inventory_location_cd,
location_id "Current Location Id",
location_label "Current Location Name"
from location L join stock_location_type SLT
on L.stock_location_type_id = SLT.stock_location_type_id
left outer join location_label
on (
case when
inventory_location_cd = 'base location'
then base_location_id
else related_location_id
end) = location_id
;
result is
stock_catalogue_id | inventory_location_cd | Current Location Id | Current Location Name
--------------------+-----------------------+---------------------+-----------------------
1 | base location | 1 | Home
1 | Not base location | 1 | Home
1 | base location | 3 | Garage
2 | base location | 3 | Garage
2 | base location | 4 | Bar
2 | Not base location | 4 | Bar
(6 rows)
if you need to aggregate it up by stock_catalogue_id and inventory_location_cd, that can be achieved with
select L.stock_catalogue_id,
SLT.inventory_location_cd,
string_agg(location_id::text, ',') "Current Location Id",
string_agg(location_label::text, ',') "Current Location Name"
from location L join stock_location_type SLT
on L.stock_location_type_id = SLT.stock_location_type_id
left outer join location_label
on (case when inventory_location_cd = 'base location' then base_location_id else related_location_id end) = location_id
group by L.stock_catalogue_id,
SLT.inventory_location_cd;
with the result being
stock_catalogue_id | inventory_location_cd | Current Location Id | Current Location Name
--------------------+-----------------------+---------------------+-----------------------
1 | base location | 1,3 | Home,Garage
1 | Not base location | 1 | Home
2 | base location | 3,4 | Garage,Bar
2 | Not base location | 4 | Bar
(4 rows)
A: You can use the string_agg function to aggregate the values in a comma-separated string. So your sub-queries needs to be rewritten to
select string_agg(related_location_id, ', ') from location_label where base_location_id = location_id
and
select string_agg(base_location_id, ', ') from location_label where related_location_id = location_id | unknown | |
d5034 | train | in v21\styles.xml
remove
<item name="android:statusBarColor">@android:color/transparent</item>
A: Try add android:fitsSystemWindows="true" to android.support.design.widget.AppBarLayout or @style/AppTheme.PopupOverlay style
A: This works for me to get a white overlay on device status bar (problem after update in question)
I changed:
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
to
<item name="android:windowDrawsSystemBarBackgrounds">false</item>
in my styles.xml file
A: try making android:layout_height="?attr/actionBarSize" for android.support.v7.widget.Toolbar | unknown | |
d5035 | train | Use the this.onclick instead of $(this).attr('onclick'). It will be a function type and you can simply set the a.onclick = img.onclick.
Ideally however the image would have a click handler and would be bound unobtrusively.
var someFunction = function(){};
$('img').click(someFunction);
Then you could use the same function on the a
$('a').click(someFuncion); | unknown | |
d5036 | train | $(document).ready(function(){
$('#data1').on('change','[id^=title],[id^=url]',function(){
var index = $(this).attr('id').replace('title',"").replace('url',"");
var title = $("#title" + index).val();
var url = $("#url" + index).val();
var hid = $("#hid" + index).val();
// you can put in here in sequence all the fields you have
$.post('library/edit.php',{title:title, url:url, hid : hid},function(res){
alert ("updated !");
});
});
});
so by this answer if any text box whoes id starts with title changes.
the function passed in will be invoked.
indezx variable will store the index of the group of the elements that are changing. and then is being callculated by removing title from title1 or title2
A: I think the answer you have it right here:
I wrote that code to call to php file on change of textbox.
That script (jQuery I guess) it must be associatte with the $('#xxx1').onchange() right? (or similar)
If you modify the function, add a class to the input field (also in the php) and each time you call the function, start listening again.. I think you can call any function you may want.
Example (guessing your code)
HTML
<div id="data1" class="dynamicDiv">
<input name="title1" type="text" id="title1" />
<input name="url1" type="text" id="url1" />
</div>
jQuery
// enable the function on document ready
$(document).ready(function(){
startListening('.dynamicDiv');
});
// each time an ajax call is completed,
// run the function again to map new objects
$(document).ajaxComplete(function(){
startListening('.dynamicDiv');
});
// and finally the function
function startListening(obj){
$(obj).onchange(function(){
// ajax call
// function call
// or whatever...
});
}
PHP
// some code....
// some code....
// remember here to add "dynamicDiv" as a class in the object
return object;
A: Since your elements are dynamically generated you need to use event delegation, then you can use [id^="value"] to select the appropriate elements based on the first part of their id attribute
$(document).ready(function(){
$(document).on('change','[id^="data"]',function(){
var title = $(this).find('[id^="title"]').val();
var url = $(this).find('[id^="url"]').val();
var hidden = $(this).find('[id^="hid"]').val();
$.post('library/edit.php',{title:title, url:url, hid:hidden},function(res){
alert ("updated !");
});
});
});
Note: I suggest you bind to the closest parent of your data divs that is present at page load instead of binding to the document | unknown | |
d5037 | train | Sounds like you're better off with OSGi ... The HK2 (which would surprise me if it was still 100k) was an attempt to not depend on OSGi directly for Glassfish. I do not think it has a well maintained API.
Since OSGi is a well defined and maintained API, that it runs on Glassfish, and that you also get portability to other environments seems to indicate that the choice for OSGi is smarter. The easiest way to get started is http://bndtools.org/
A: If you want to do Glassfish module development I can recommend you following tutorials and one example taken from the Glassfish trunk. Just have a look there how they do it. I tried it once, but since HK2 is not really OSGi as Peter already mentioned, I let it be after some time :) But maybe you can take advantages of these information now ;)
*
*http://kalali.me/glassfish-modularity-system-how-extend-glassfish-cli-and-web-administration-console-part-2-developing-sample-modules/
*http://java.net/projects/glassfish-samples/sources/svn/show/trunk/v3/plugin/adminconsole/console-sample-ip/ | unknown | |
d5038 | train | No, this has nothing to do with destructuring and No, you cannot use array literals in a switch statement since distinct objects never compare equal.
What you can do in your case is to map your two booleans to an integer score:
switch (clean * 2 + tall) {
case 3:
console.log("Perfect");
break;
case 2:
console.log("Ok");
break;
case 1:
console.log("Not so good");
break;
case 0:
console.log("Terrible");
}
or the equivalent array lookup:
console.log(["Terrible", "Not so good", "Ok", "Perfect"][clean * 2 + tall]);
You might even want to make the bitwise magic more obvious:
switch (tall << 1 | clean << 0) {
case true << 1 | true << 0:
console.log("Perfect");
break;
case false << 1 | true << 0:
console.log("Ok");
break;
case true << 1 | false << 0:
console.log("Not so good");
break;
case false << 1 | false << 0:
console.log("Terrible");
break;
}
You can also call a helper function score(a, b) { return a << 1 | b << 0 } in both the switch and the cases.
A: Indeed, you can only use literals in a switch statement and you can't use primitive objects as keys in an array, so you can't do a mapping like:
{[true,true]: 'Perfect'
...}
Too bad. I wonder if there are languages where you can have a list/array as dictionary key.
I still might be tempted to do something like this which I think is quite readable (though it might get rejected in a code review!):
function hashKey([tall, clean]) {
return `${tall}_${clean}`
}
let valMap = {
'true_true': 'Perfect',
'false_true': 'Ok',
'true_false': 'Not so good',
'false_false': 'Terrible'
}
console.log(valMap[hashKey([true, true ])])
A: Can do something like the following:
const tall = true;
const clean = false;
switch (true) {
case tall && clean:
console.log("Perfect");
break;
case !tall && clean:
console.log("Ok");
break;
case tall && !clean:
console.log("Not so good");
break;
default:
console.log("Terrible");
} | unknown | |
d5039 | train | The meaning of short-circuiting here is that evaluation will stop as soon as the boolean outcome is established.
perl -E "@x=qw/a b c d/; for (qw/b w/) { say qq($_ - ), $_ ~~ @x ? q(ja) : q(nein) }"
For the input b, Perl won't look at the elements following b in @x. The grep built-in, on the other hand, to which the document you quote makes reference, will process the entire list even though all that's needed might be a boolean.
perl -E "@x=qw/a b c/; for (qw/b d/) { say qq($_ - ), scalar grep $_, @x ? q(ja) : q(nein) }"
A: Yes, in the sense that when one of the arguments is an Array or a Hash, ~~ will only check elements until it can be sure of the result.
For instance, in sub x { ... }; my %h; ...; %h ~~ \&x, the smart match returns true only if x returns true for all the keys of %h; if one call returns false, the match can return false at once without checking the rest of the keys. This is similar to the && operator.
On the other hand, in /foo/ ~~ %h, the smart match can return true if it finds just one key that matches the regular expression; this is similar to ||. | unknown | |
d5040 | train | In Java, this would be something like:
public static <T> void printList(List<T> list)
The (Of T) after PrintList is the equivalent to the <T> before void in the Java version. In other words, it's declaring the type parameter for the generic method.
A: Adding to what Jon Skeet said, this sub appears to be able to take any type of list. If PrintList(Of T) was just PrintList, then you would be stuck specifying what type of List you want to use for your parameter. You could no longer have 2 calls to this sub taking two different types of lists without overloading the sub.
What I mean by 2 different types of lists is:
List(of string)
List(of integer) | unknown | |
d5041 | train | This is an issue connected to the change from PROJ4 to PROJ6 in rgdal/sp. For you the issue is a bit deeper because the camtrapR package is not yet updated to deal with PROJ6.You can read more about the transition to PROJ6 here.
Without going too deep into it the solution for you would be to downgrade to an older version of sp and rgdal.
For sp (< 1.4-2) and rgdal (< 1.5-8).
EDIT: Since you can define the PROJ String yourself you can also first try: "+init=epsg:4326". This might still work. | unknown | |
d5042 | train | If you want to gain an insight in what your OpenMP program is doing, you should use a OpenMP-task-aware performance analysis tool. For example Score-P can record all task operations in either a trace with full timing information or a summary profile. There are then several other tools to analyse and visualize the recorded information.
Take a look at this paper for more information for performance analysis of task-based OpenMP applications.
A: There's no good way of counting the number of OpenMP tasks, as OpenMP does not offer any way to actually query how many tasks have been created thus far. The OpenMP runtime system may or may not keep track of this number, so it would unfair (and would have performance implications) if such a number would be kept in a runtime that is otherwise not interested in this number.
The following is a terrible hack! Be sure you absolutely want to do this!
Having said the above, you can do the count manually. Assuming that your code is deterministically creating the same number of tasks for each execution, you can do this:
int tasks_created;
void quicksort(int* A,int left,int right)
{
int i,last;
if(left>=right)
return;
swap(A,left,(left+right)/2);
last=left;
for(i=left+1;i<=right;i++)
if(A[i] < A[left])
swap(A,++last,i);
swap(A,left,last);
#pragma omp task
{
#pragma omp atomic
tasks_created++
quicksort(A,left,last-1);
}
quicksort(A,last+1,right);
#pragma omp taskwait
}
I'm saying that this is a terrible hack, because
*
*it requires you to find all the task-creating statements to modify them with the atomic construct and the increment
*it does not work well for some task-generating directives, e.g., taskloop
*it may horribly slow down execution, so that you cannot leave the modification in for production (that's the part abut determinism, you need run once with the count and then remove the counting for production)
Another way...
If you are using a reasonably new implementation of OpenMP that already supports the new OpenMP tools interfaces of OpenMP 5.0, you can write a small tool that hooks into the OpenMP events for task-creation. Then you can do the count in the tool and attach it to our execution through the OpenMP tools mechanism. | unknown | |
d5043 | train | The "random" file is determined before the server is started. In order to do this for every request you need to call randomfile(...) in the request-callback:
const app = http.createServer( (req,res) => {
const location = './zdj' + '/' + (randomfile(files))
const data = fs.readFileSync(location, "utf8");
const splittext = data.split("||")
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({"test1": splittext[0], "test2": splittext[1], "test3": splittext[2]}));
});
Note:
1.) you should use let/const instead of var nowadays (see this for more info)
2.) readFileSync blocks, you should consider using a non-blocking read-operation, e.g. fs.promises.readFile() | unknown | |
d5044 | train | relation manyToMany on the same entity I have an Entity that has two relation manyToMany with itself and I don't want to use Cascade.MERGE because I need to do some data checks to validate the data:
@Entity("device")
public class Device {
...
@ManyToMany(mappedBy = "parents", targetEntity = Device.class, fetch = FetchType.LAZY)
public Set<Device> getChildren() {
return this.children;
}
@Override
@ManyToMany(targetEntity = Device.class, fetch = FetchType.LAZY)
@JoinTable(name = "dem_hierarchy", joinColumns = {
@JoinColumn(name = "CHILDREN_UUID", referencedColumnName = "UUID")},
inverseJoinColumns = {
@JoinColumn(name = "DEM_DEVICE_UUID", referencedColumnName = "UUID")})
public Set<Device> getParents() {
return parents;
}
...
}
When I save a tree like this:
Device grandGrandPa = new Device();
grandGrandPa.setName("TEST" + counter + "_grandGrandPa");
Device grandPa = new Device();
grandPa.setName("TEST" + counter + "_grandPa");
grandGrandPa.addChild(grandPa);
Device daddy = new Device();
daddy.setName("TEST" + counter + "_daddy");
grandPa.addChild(daddy);
Device son = new Device();
son.setName("TEST" + counter + "_son");
daddy.addChild(son);
grandGrandPa = deviceService.register(grandGrandPa);
The register method is recursive and it descends the tree using the children column. When its the turn of the "grandPa" to be saved the weblogic return an exception:
Caused by: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing
I cannot understand why this happens. It gives me this error when in code there are some queries on parent Device: first turn it is empty, second turn it has one value.
I'm using weblogic 12.1.3 and hibernate 4.0.0, as database Oracle 11g.
A:
It gives me this error when in code there are some queries on parent Device
By default, Hibernate will flush pending changes to the database before attempting to execute a query. At that stage, all entities referenced in all relationships should have been persisted, or else an exception will be thrown.
Also, since mappedBy is declared on the children end, the parents is the owning side of the relationship. Because of that, Hibernate will ignore children completely at persist time and look for transient entities in parents instead. Your persisting logic should therefore be reversed - save parents first, children last (alternatively, you could simply declare children the owning side). | unknown | |
d5045 | train | Please try the following and let me know if it works :
Select dropdown = new Select(driver.findElement("Use the correct selector");
WebElement option = dropdown.getFirstSelectedOption();
String content = option.getText();
System.out.println("selected Value " + content); | unknown | |
d5046 | train | I believe this is essentially a duplicate of this other Stack Overflow question:
Is it possible to use arrow keys in OCaml interpreter?
The stock version of the OCaml interpreter doesn't interpret special keys like arrow keys. So it will just echo their control codes (as Ben Graham points out). To get the kind of behavior you probably want (editing the input, going back to previous lines, etc.) you need to wrap the OCaml interpreter with a line editing facility. See the other question linked above for some suggestions.
This doesn't explain why you see different "modes" of behavior, but I still think this is how you want to think about your problem.
A: You should use Utop. Utop is a OCaml interpreter which offers auto-completion (like bash) and a history of command. Of course, all problems with arrow keys disappears.
You'll need to compile Zed and Lambda-Term to compile Utop. | unknown | |
d5047 | train | Ben Alman has a nice scrollbarWidth plugin that works nicely.
var content = $('#content').css( 'width', 'auto' ),
container = content.parent();
if ( content.height() > container.height() ) {
content.width( content.width() - $.scrollbarWidth() );
} | unknown | |
d5048 | train | We could use new group_split to split the dataframe based on groups (am) and then use map_df to create a new model for each group and get the prediction values based on that.
library(tidyverse)
mtcars %>%
group_split(am) %>%
map_df(~{
model <- glm(vs~mpg, family = "binomial", data = .)
data.frame(newdata,am = .$am[1], pr_1 = predict(model,newdata, type = "response"))
})
# mpg am pr_1
#1 10 0 0.0000831661
#2 11 0 0.0002519053
#3 12 0 0.0007627457
#4 13 0 0.0023071316
#5 14 0 0.0069567757
#6 15 0 0.0207818241
#7 16 0 0.0604097519
#8 17 0 0.1630222293
#9 18 0 0.3710934960
#10 19 0 0.6412638468
#..... | unknown | |
d5049 | train | To ensure text alignment in vb.net textbox/Messagebox string, use-
*
*MonoSpace font
https://learn.microsoft.com/en-us/dotnet/api/system.drawing.fontfamily.genericmonospace?view=dotnet-plat-ext-6.0
C# .NET multiline TextBox with same-width characters
*Add padding to each text piece to position it in desired location. | unknown | |
d5050 | train | You can use Geany. It has "Color chooser" button - select your hex code and click on it and you will see the color and will be able to change it.
A: You can create an HTML file with your favorite text editor and simply load it up your browser. Try this:
<style>
.PRIMARY1 { color: #7CACDF }
.PRIMARY2 { color: #A5C6E9 }
...
</style>
<div class="PRIMARY1">PRIMARY1</div>
<div class="PRIMARY2">PRIMARY2</div>
...
You can even automatically generate this with some clever find & replace or Excel formulas. | unknown | |
d5051 | train | As pointed by Chris, the parameters you passed in std::replace are not the correct ones. std::replace expects iterators for its first two parameters but you are passing references.
You can use begin() and end() to get the iterators:
std::replace(grid.at(possRow).begin(), grid.at(possRow).end(), ".", symbol.c_str()); | unknown | |
d5052 | train | As mentioned in Async-signal-safe access to __thread variables from dlopen()ed libraries? you provided (emphasis is mine):
The __thread variables generally fit the bill (at least on Linux/x86),
when the variable is in the main executable, or in a directly-linked DSO.
But when the DSO is dlopen()ed (and does not use initial-exec TLS model),
the first access to TLS variable from a given thread triggers a call to
malloc...
In other words, it only requires one access to that thread specific variable to bring it to life and make it available in signal handlers. E.g.:
*
*Block the signals you are interested in in the parent thread before creating a child thread.
*Unblock those interesting signals in the parent thread after the call to pthread_create.
*In the child thread initialize your __thread variable and unblock those interesting signals.
I normally store the write end of a unix pipe in that tread-specific variable and the signal handler writes the signal number into that pipe. The read end of the pipe is registered with select/epoll in that same thread, so that I can handle signals outside of the signal context. E.g.:
__thread int signal_pipe; // initialized at thread start
extern "C" void signal_handler(int signo, siginfo_t*, void*)
{
unsigned char signo_byte = static_cast<unsigned>(signo); // truncate
::write(signal_pipe, &signo_byte, 1); // standard unix self pipe trick
} | unknown | |
d5053 | train | I managed to create a relatively simple solution using the HtmlUnit headless browser. In my case i had to download a PDF file from a website which required SAML authentication.
import com.gargoylesoftware.htmlunit.UnexpectedPage;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.*;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
...
private static byte[] samlAuthenticateAndDownloadFile(String url, String username, String password) throws Exception {
byte[] fileBytes;
try (final WebClient webClient = new WebClient()) {
final HtmlPage loginPage = webClient.getPage(url);
final HtmlForm loginForm = loginPage.getForms().get(0);
final HtmlSubmitInput button = loginForm.getInputByName("login");
final HtmlTextInput usernameField = loginForm.getInputByName("username");
final HtmlPasswordInput passwordField = loginForm.getInputByName("password");
usernameField.setValueAttribute(username);
passwordField.setValueAttribute(password);
final UnexpectedPage pdfPage = button.click();
InputStream inputStream = pdfPage.getInputStream();
fileBytes = IOUtils.toByteArray(inputStream);
}
return fileBytes;
} | unknown | |
d5054 | train | If they are static Strings (that you may or may not want to translate later on) you would probably be best saving them as a String array in a resource.xml file:
(The filename can be anything_you_like.xml)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="food_names">
<item>apple</item>
<item>orange</item>
<item>pizza</item>
<item>blah</item>
<item>blah</item>
</string-array>
<string-array name="food_descriptions">
<item>green, doctor friendly</item>
<item>round, hurts eyes</item>
<item>flat, cheezy, liked by turtles</item>
<item>blah</item>
<item>blah</item>
</string-array>
</resources>
You need to locate the file inside your values folder and you then get the option to do all the fancy folder variations like values-v14, values-v16 and values-en, values-es, values-fr and so on, and so on...
You can later access this String[] from your code to grab the appropriate version for the user's API and language with:
String[] foodNames = context.getResources().getStringArray(R.array.food_names);
String[] foodDescriptions = context.getResources().getStringArray(R.array.food_descriptions);
static final String FOOD_FORMAT = "%s :: $s";
for (int i=0; i<foodNames.length; i++) {
System.out.println(
String.format(FOOD_FORMAT,
foodNames[i],
foodDescriptions[i]
)
);
}
A: indivisible's answer is acceptable to your case. But considering that your content may change and may be more detailed, you should stick to an SQLite database. You only will need a simple table insert your data. Having an if else chain is not the cleanest way and definitely is not friendly when you think about scalability. But if you really want to use the second approach, use a switch, instead of an if else chain.
If in the future, you want to add other elements to your data, just change your database as you like and that is it. | unknown | |
d5055 | train | check out the "squeel" method, new in 0.9.0. It was added to support exactly this sort of thing. It just gives you an easy way to write a block of Squeel DSL without actually attaching it to a "where", "join", etc.
You also might want to consider encapsulating this logic in a sifter for your model.
class User < ActiveRecord::Base
sifter :my_sifter do |growth_range, min_rating, email_start|
growth.in(growth_range) & rating.gt(min_rating) & email.matches("#{email_start}%")
end
end
User.where{sift :my_sifter, 0..200, 50, 'vany'}
A: I resolved my problem using Arel. I think (I just changed MetaWhere code to Arel) that it is just the same as MetaWhere.
t = User.arel_table
email_starts_with = "vany%"
sql = t[:rating].gt(50)
sql = t[:growth].in(0..200)
sql = sql.and(t[:email].matches(email_starts_with))
User.where(sql).to_sql
=> "SELECT \"users\".* FROM \"users\" WHERE (\"users\".\"growth\" BETWEEN 0 AND 200 AND \"users\".\"email\" ILIKE 'vany%')"
Thanks everybody for help! | unknown | |
d5056 | train | The 2 is the exploration constant. The larger it is, the more the algorithm favors exploration over exploitation.
Also beware that this formula makes sense only when the payoffs are in [0,1] range, otherwise a large payoff (say 1000) will nullify the influence of the "exploration" part of the formula, effectively making it exploitation-only. | unknown | |
d5057 | train | When you view the page's source code from what path is it trying to load your style?
Try this - <link rel="stylesheet" href="{% static "style.css" %}" />
Also I would change MEDIA_ROOT and STATIC_ROOT to MEDIA_ROOT = os.path.join(BASE_DIR, 'media') and STATIC_ROOT = os.path.join(BASE_DIR, 'static'). This way both paths are being built by the system and it's harder to mess up. | unknown | |
d5058 | train | To refere model by dynamic name you can isolate scope (scope: true) and use $parent reference to outer scope:
.directive('dynamicmodel', function($templateRequest, $compile) {
return {
replace: true,
restrict: 'E',
scope: true,
link: function(scope, element, attrs) {
scope.name = attrs.comm;
$templateRequest("template.html").then(function(html) {
element.replaceWith($compile(html)(scope));
});
}
};
});
and then in template use scope.comm:
<input type="text" ng-model="$parent[name].subject" />
Demo: http://plnkr.co/edit/B4HgvxuT1jZJ2H3U9UO9?p=info | unknown | |
d5059 | train | maybe it cant find the corresponding record for
$q = MedicineDrugform::model()->findbypk($a); | unknown | |
d5060 | train | Reimplement the method acceptNavigationRequest of QWebEnginePage :
class MyQWebEnginePage : public QWebEnginePage
{
Q_OBJECT
public:
MyQWebEnginePage(QObject* parent = 0) : QWebEnginePage(parent){}
bool acceptNavigationRequest(const QUrl & url, QWebEnginePage::NavigationType type, bool)
{
if (type == QWebEnginePage::NavigationTypeLinkClicked)
{
// retrieve the url here
return false;
}
return true;
}
}; | unknown | |
d5061 | train | To solve this, please change the following line of code:
databaseReference=FirebaseDatabase.getInstance().getReference("Client");
to
databaseReference=FirebaseDatabase.getInstance().getReference();
There is no need to get a reference of the Client node since you are using a call to .child("Client") in your query.
Edit:
To solve the error you get now according to your comment, plase change the type of your id property in your Users class from String to long and the getter and setter like this:
public class Users {
String email;
long id;
String password;
String username;
public Users() {
}
public Users(String email, long id, String password, String username) {
this.email = email;
this.id = id;
this.password = password;
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
} | unknown | |
d5062 | train | As suggested by @hcwhsa, you should rewrite your cook method as follows:
import os
def cook(food):
// make something with food...
os.rename(food, food + '.png') // e.g.: rename 'finished_cake' to 'finished_cake.png'
A: I ended up using string slicing to remove the file extensions, which allowed me to insert additional information before then replacing the file extension, code is as follows:
food.save (food[0:-4]+ '_X.png')
Essentially, using slicing you'd be able to completely rewrite the file name, so having a similar effect to os.rename.
Thanks for all of your help! | unknown | |
d5063 | train | make an ajax call to the server and let your server page kills/ends the session
HTML
<a href="#" id="aKill" > Kill Session</a>
Script
$(function(){
$("#aKill").click(function(){
$.post("serverpage.php",function(data){
// if you want you can show some message to user here
});
});
and in your serverpage.php, Execute the PHP script to terminate the session.
A: Create a separate file to clear the session only. clearsession.php
session_start();
session_destroy();
Now, make a simple request
$("#aKill").click(function(){
$.get("clearsession.php");
}
A: The below covers the basics more or less.
The Function:
function destroySession(){
var theForm = $("#yourForm");
//we don't need any ajax frame.
theForm.each(function(){ this.reset() });
$.ajax({
url: 'destroysession.php',
type: 'post',
data: 'sure=1', //send a value to make sure we want to destroy it.
success: function(data);
alert(data);
}
});
}
The PHP (destroysession.php):
<?php
//whatever logic is necessary
if(!empty($_POST['sure'])){
$sure = $_POST['sure'];
if($sure == 1){
//logic to destroy session
echo 'Session Destroyed!';
}else if($sure != 1){
//logic to perform if we're being injected.
echo 'That value is incorrect. What are you doing over there?';
}
}else{
//logic to perform if we're being injected.
echo 'That value is incorrect. What are you doing over there?';
}
?>
The HTML:
<input type='button' value='reset' onclick='destroySession()'> | unknown | |
d5064 | train | You cannot change the values of arguments, as they are passed by reference
in bash functions.
The best you can do is to pass the arguments you want to process, and return
the ones not processed yet.
Something in the lines of:
process_arguments() {
# process the arguments
echo "original arguments : $@"
local new_arguments=(a c)
echo ${new_arguments[@])
}
new_arguments=$(process_arguments a b c)
set -- $new_arguments
If you don't want the trouble of a "subshell", you can use a global var:
arguments=""
process_arguments() {
# process the arguments
echo "original arguments : $@"
local new_arguments=(a c)
arguments="${new_arguments[@]}"
}
process_arguments a b c # no subshell
set -- $arguments
As suggested by @ruakh, you can also use arguments as an array, like this:
arguments=()
process_arguments() {
# process the arguments
echo "original arguments : $@"
local new_arguments=(a c)
arguments=( "${new_arguments[@]}" )
}
process_arguments a b c # no subshell
set -- "${arguments[@]}"
A: This is a matter of scope: Functions each have their own parameter array, independently of the script:
$ cat test.bash
#!/usr/bin/env bash
f() {
printf '%s\n' "Function arguments:" "$@"
}
printf '%s\n' "Script arguments:" "$@"
f 'a b' 'c d'
$ chmod u+x test.bash
$ ./test.bash 'foo bar' baz
Script arguments:
foo bar
baz
Function arguments:
a b
c d
So when you set the parameter array, that only applies within the current scope. If you want to change the script parameter array, you need to set it outside of any function. Hacks like set -- $(f) are not going to work in general, because it can't handle whitespace in arguments.
A general solution gets much uglier: you'd need to printf '%s\0' "$parameter" in the function and while IFS= read -r -d'' -u9 in the script to put the returned values into an array, and then set -- "${arguments[@]}".
I hope this is possible to do reliably some other way, but that's all I got.
A: vfalcao's approach is good, though the code in that answer wouldn't handle whitespaces accurately.
Here is the code based on the same idea that does handle whitespaces well:
wrapper() {
# filter args
args=()
for arg; do
if [[ $arg = arg1 ]]; then
# process arg1
elif [[ $arg = arg2 ]]; then
# process arg2
elif ...
# process other args
else
args+=("$arg")
fi
# call function with filtered args
wrapped_function "$args[@]"
done
}
wrapper "$@"
An example implementation here: base-wrapper | unknown | |
d5065 | train | Your problem:
when you are doing the below:
.mat-side-nav{
width: auto !important
}
This is kind of hard coding the width to take whatever it contains.
Solution:
Find the class which is active while its open and set the width: auto, for that class. | unknown | |
d5066 | train | Try adding to composer.json in the section requires "psr/container": "2.0.2 as 1.1.2","symfony/http-foundation": "6.0.3 as 5.4.3" and after that in the terminal 'composer requires botman/botman --with-all-dependencies
A: try composer require botman/botman composer require mpociot/botman package is abandoned | unknown | |
d5067 | train | The former is a declaration of a new, immutable variable. The latter is how you re-assign the value of a reference cell. | unknown | |
d5068 | train | The problem is not in this piece of code. In some other part of the program, and I suspect it is the place where the values from the textboxes are accepted and fed into the formula - in that place there should be a function or code snippet that is rounding the value of $TritPrice. Check the place where the $_POST values are being fetched and also check if any javascript code is doing a parseInt behind the scenes.
A: EVE-Online ftw.
with that out of the way, it's possible that your precision value in your config is set too low? Not sure why it would be unless you changed it manually. Or you have a function that is running somewhere that is truncating your variable when you call it from that function/var
However, can you please paste the rest of the code where you instantiate $TritPrice please? | unknown | |
d5069 | train | As you know, Elm uses a "virtual DOM". Your program outputs lightweight objects that describe the DOM structure you want, and the virtual DOM implementation "diffs" the current and new structure, adding, modifying, and removing elements/attributes/properties as required.
Of course, there is a small performance penalty to using a virtual DOM over directly manipulating the DOM, but the difference doesn't matter in most web applications. If you find that your application has poor performance in the view function, there are several ways to improve performance, such as Html.Lazy
Many other popular libraries use a virtual DOM, such as React, Angular, and Vue. Usually, it's easier to render your application with a virtual DOM (rather than "manually" manipulating the DOM), so many of the popular frameworks implement one. | unknown | |
d5070 | train | Change this:
<f:ajax execute="selectedCategory" render="selectedFrom"/>
To this:
<f:ajax execute="selectedCategory" render="selectedFrom selectedTo"/>
A: I added ajax listener as below so indicate that category change is being invoked so that getFromList will set selectedFrom to new item from its list instead of one being posted. Then getToList will find correct category and from unit to query its to list.
<f:ajax execute="selectedCategory" render="selectedFrom"></f:ajax>
to
<f:ajax listener="#{converterBean.categoryChanged}" execute="selectedCategory" render="selectedFrom selectedTo"></f:ajax> | unknown | |
d5071 | train | You can attach the event outside the loop where you can match the value between the selected value and the object property name:
let citiesWithInfo = {"New York": 'The biggest city in the world.',
"Los Angeles": 'Home of the Hollywood sign.',
"Maui": 'A city on the beautiful island of Hawaii.',
"Vancover": 'It\'s a city where it rains alot. And I mean alot.',
"Miami": 'The samba city of the world.'
};
const cityWithInfoPrompt = document.querySelector('#cities-with-info');
const entries = Object.entries(citiesWithInfo);
for(const [city, info] of entries) {
let optionCity = document.createElement("option");
optionCity.textContent = city;
optionCity.value = city;
cityWithInfoPrompt.appendChild(optionCity);
}
cityWithInfoPrompt.addEventListener('change', function(){
let currentCity = this.options[this.selectedIndex].value;
document.querySelector(".info").textContent = citiesWithInfo[currentCity];
});
// On page load
// Create event
var event = new Event('change');
// Dispatch the event
cityWithInfoPrompt.dispatchEvent(event);
<body>
<select name="cities-with-info" id="cities-with-info"></select>
<p>Info: <span class="info"></span></p>
<script src="eventTarget.js"></script>
</body>
Solution using Arrow Function (() => {}) and Event.target
let citiesWithInfo = {"New York": 'The biggest city in the world.',
"Los Angeles": 'Home of the Hollywood sign.',
"Maui": 'A city on the beautiful island of Hawaii.',
"Vancover": 'It\'s a city where it rains alot. And I mean alot.',
"Miami": 'The samba city of the world.'
};
const cityWithInfoPrompt = document.querySelector('#cities-with-info');
const entries = Object.entries(citiesWithInfo);
for(const [city, info] of entries) {
let optionCity = document.createElement("option");
optionCity.textContent = city;
optionCity.value = city;
cityWithInfoPrompt.appendChild(optionCity);
}
cityWithInfoPrompt.addEventListener('change', () => {
let currentCity = event.target.value;
document.querySelector(".info").textContent = citiesWithInfo[currentCity];
});
// On page load
// Create event
var event = new Event('change');
// Dispatch the event
cityWithInfoPrompt.dispatchEvent(event);
<body>
<select name="cities-with-info" id="cities-with-info"></select>
<p>Info: <span class="info"></span></p>
<script src="eventTarget.js"></script>
</body>
A: I used this code for the addEventListener to get the info from the object to the info HTML tag.
cityWithInfoPrompt.addEventListener("change", (e) => {
let selectedCity = e.target.value
for(const [city, info] of entries) {
if(selectedCity == city) {
document.querySelector(".info").textContent = info;
}
}
}); | unknown | |
d5072 | train | I can see how you might end up chasing your tail on this sort of problem.
Instead of multiple controllers, consider have one EventController for all the routes along with individual ProblemHelper and MaintainenceHelper objects. The helper objects would have your add/see/modify methods and could extend a CommonHelper class.
Your controller would check the entity type, instantiate the helper and pass control over to it. | unknown | |
d5073 | train | You need to bind your paths to your data, so you can call valueLine with the correct data for the path when zooming.
Use d3 data and enter functions when adding a new path:
// choose all .line objects and append a path which is not already binded
// by comparing its data to the current key
svg.selectAll(".line").data([d], function (d) {
return d.key;
})
.enter().append("path")
.attr("class", "line")
Then when you zoom, change the d attribute path by calling valueLine with the path's correct values:
svg.selectAll('path.line')
.transition().duration(500)
.attr('d', function(d) {
return valueline(d.values)
});
Plunker | unknown | |
d5074 | train | The first thing you should do is take a step back. There should be no need to call asynchronous code from within a MeasureOverride in the first place.
Asynchronous code generally implies I/O-bound operations. And a XAML UI element that needs to send a request to a remote web server, query a database, or read a file, just to know what its size is, is doing it wrong. That's a fast track to app certification rejection.
The best solution is almost certainly to move the asynchronous code out of the element itself. Only create/modify the UI elements after the necessary asynchronous work completes.
That said, if you feel you must block the UI thread while asynchronous operations complete, I've compiled a list of every hack I know of, published in my MSDN article on brownfield asynchronous development. | unknown | |
d5075 | train | Even better, the elegant and idiomatic solution provided by:
https://github.com/tidyverse/forcats/issues/122
library(dplyr)
df = df %>% mutate_if(is.factor,
fct_explicit_na,
na_level = "to_impute")
A: After some trial and error, the code below does what I want.
library(tidyverse)
df[, f_names] <- lapply(df[, f_names], function(x) fct_explicit_na(x, na_level = "to_impute")) %>% as.data.frame | unknown | |
d5076 | train | In short, you can't.
Doc and TIFF are two completely different things. It's not like converting from BMP to TIFF (two image formats), or WAV to MP3 (two audio formats). For very limited Word documents, I suppose you could run Word through OLE automation (or maybe even embed Word in your application for better control), then take a screenshot, but I think your problems runs deeper than that. Maybe you could provide some more info about what you try to achieve?
A: I've done it from within Word, however the code is long lost I'm sorry.
I created an Office plugin using the Add-in Express Component.
I used Word automation to convert the current document to RTF, used WP-Tools to render, which gave me the bitmap for each page. Finally I used GDI+ to create the multi-page TIFF.
A: The standard trick is like with word to pdf: find a virtual printer that outputs tiffs, and instrument word over OLE to print to the virtual printer.
If I put "tiff printer virtual" in google, I see quite some hits. (not all free though, and of course it complicates installation to use two programs (word+printer) to do this)
A: Word is not able to save its documents to TIFF format. Your best options are to use third party software which can do that. Just google for Doc to Tiff.
A: When looking for tools to do this, you should also be aware that not all TIFF files are faxable. TIFF files can contain a whole range of image formats and sizes. You need to find a tool which can convert your document to monochrome bitmaps 1728 pixels wide, with the page images each in a single strip and with a compression method supported by your fax software.
A: A good fax software usually comes with a fax printer driver, check with the maker of your fax software if they have one. With a driver you can simply use OLE Automation to make Word print the document to this driver. The fax software we use expects the fax number and other parameters embedded in the text like this: @@NUMBER12345678@@ | unknown | |
d5077 | train | In general, 3rd party integration is always easier and more maintainable when it's done in a black box manner. Rather than integrate based on how a 3rd party implements their solutions, you integrate based on their black box facade, so that you don't have to deal with knowing their implementation details.
Comparing it to a SQL query - a SQL query typically describes just what you want, rather than how you want the database server to retrieve what you want.
A: Yes - you absolutely have to know the controllers and action names unless you share a common routing table. However if you think if the destination application as a service, then this is fine as you have restful urls to the service endpoints, as would be typical in any app that calls a service. I would however store these in a single location - as you mentioned table, config file, etc. | unknown | |
d5078 | train | The following will get you to the sign in page:
var casper = require("casper").create ({
waitTimeout: 15000,
stepTimeout: 15000,
verbose: true,
viewportSize: {
width: 1400,
height: 768
},
onWaitTimeout: function() {
logConsole('Wait TimeOut Occured');
this.capture('xWait_timeout.png');
this.exit();
},
onStepTimeout: function() {
logConsole('Step TimeOut Occured');
this.capture('xStepTimeout.png');
this.exit();
}
});
casper.on('remote.message', function(msg) {
logConsole('***remote message caught***: ' + msg);
});
casper.userAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4');
// vars
var gUrl = 'http://www.usa.canon.com/cusa/home';
// Open URL and click sign in
casper.start(gUrl, function() {
this.clickLabel('Sign In', 'a');
});
//Sign in page
casper.then(function () {
//+++ ready for you to fill user information.
this.capture('xSignIn.png'); //+++ shows you are on signin page. can remove.
});
casper.run(); | unknown | |
d5079 | train | The OP seemed satisfied with the answer, but it doesn't keep the new window open after executing the program, which is what he seemed to be asking (and the answer I was looking for). So, after some more research, I came up with:
Start-Process cmd "/c `"your.exe & pause `""
A: I was solving a similar problem few weeks ago. If you don't want to use & (& '.\program.exe') then you can use start process and read the output by start process (where you read the output explicitly).
Just put this as separate PS1 file - for example (or to macro):
param (
$name,
$params
)
$process = New-Object System.Diagnostics.Process
$proInfo = New-Object System.Diagnostics.ProcessStartInfo
$proInfo.CreateNoWindow = $true
$proInfo.RedirectStandardOutput = $true
$proInfo.RedirectStandardError = $true
$proInfo.UseShellExecute = $false
$proInfo.FileName = $name
$proInfo.Arguments = $params
$process.StartInfo = $proInfo
#Register an Action for Error Output Data Received Event
Register-ObjectEvent -InputObject $process -EventName ErrorDataReceived -action {
foreach ($s in $EventArgs.data) { Write-Host $s -ForegroundColor Red }
} | Out-Null
#Register an Action for Standard Output Data Received Event
Register-ObjectEvent -InputObject $process -EventName OutputDataReceived -action {
foreach ($s in $EventArgs.data) { Write-Host $s -ForegroundColor Blue }
} | Out-Null
$process.Start() | Out-Null
$process.BeginOutputReadLine()
$process.BeginErrorReadLine()
$process.WaitForExit()
And then call it like:
.\startprocess.ps1 "c:\program.exe" "params"
You can also easily redirect output or implement some kind of timeout in case your application can freeze...
A: If the program is a batch file (.cmd or .bat extension) being launched with cmd /c foo.cmd command, simply change it to cmd /k foo.cmd and the program executes, but the prompt stays open.
If the program is not a batch file, wrap it in a batch file and add the pause command at the end of it. To wrap the program in a batch file, simply place the command in a text file and give it the .cmd extension. Then execute that instead of the exe.
A: Try doing:
start-process your.exe -NoNewWindow
Add a -Wait too if needed.
A: With Startprocess and in the $arguments scriptblock, you can put a Read-Host
$arguments = {
"Get-process"
"Hello"
Read-Host "Wait for a key to be pressed"
}
Start-Process powershell -Verb runAs -ArgumentList $arguments
A: pwsh -noe -c "echo 1" | unknown | |
d5080 | train | Step 0 - Create a new battleship and place them on the array just like the first one.
Step 1- Change your boolean hit to an int equaling 2.
Step 2- Instead of toggling hit, reduce it by 1 when you hit a ship and then set
that position on the array to a 0.
Step 3- Adjust your logic so that you do not win unless hit < 1 | unknown | |
d5081 | train | Here is a part of the solution
data_frame = lung
group = "sex"
survival_time = "time"
event = "death"
data_frame %>%
filter_(paste("!is.na(", group, ")")) %>%
group_by_(group) %>%
summarise_(
pt = paste("round(sum(as.numeric(", survival_time, ") / 365.25))"),
events = paste("sum(", event, ")")
) | unknown | |
d5082 | train | If you're still looking to get the images from the Director .exe,(a Projector I presume?), you might be able to use a converter such as http://swftools.sourceforge.net/exe-to-swf.html which may end up porting the media to a folder. I suggest going down that route. Also try the unofficial Director communities if they are still active http://www.deansdirectortutorials.com/
Hope that helps. | unknown | |
d5083 | train | Were you thinking of something like this?
(define (pp sxp)
(cond
((null? sxp) sxp)
((list? sxp) (let-values (((args op) (split-at-right sxp 1)))
(cons (car op) (map pp args))))
(else sxp)))
then
> (pp '(1 2 *))
'(* 1 2)
> (pp '(10 (1 2 3 +) ^))
'(^ 10 (+ 1 2 3))
A: Try something like this:
(define (postfix->prefix expr)
(cond
[(and (list? expr) (not (null? expr)))
(define op (last expr))
(define args (drop-right expr 1))
(cons op (map postfix->prefix args))]
[else expr]))
This operates on the structure recursively by using map to call itself on the arguments to each call. | unknown | |
d5084 | train | You can iterate over sys.argv[1:], e.g. via something like:
for grp in sys.argv[1:]:
for i in range(len(sh.col_values(8))):
if sh.cell(i, 1).value == grp:
hlo.append(sh.cell(i, 8).value)
A: outputList = [x for x in values if x in sys.argv[1:]]
Substitute the bits that are relevant for your (spreadsheet?) situation. This is a list comprehension. You can also investigate the optparse module which has been in the standard library since 2.3.
A: I would recommend taking a look at Python's optparse module. It's a nice helper to parse sys.argv.
A: argparse is another powerful, easy to use module that parses sys.argv for you. Very useful for creating command line scripts.
A: I believe this would work, and would avoid iterating over sys.argv:
hlo = []
for i in range(len(sh.col_values(8))):
if sh.cell(i, 1).value in sys.argv[1:]:
hlo.append(sh.cell(i, 8).value)
A: # First thing is to get a set of your query strings.
queries = set(argv[1:])
# If using optparse or argparse, queries = set(something_else)
hlo = []
for i in range(len(sh.col_values(8))):
if sh.cell(i, 1).value in queries:
hlo.append(sh.cell(i, 8).value)
=== end of answer to question ===
Aside: the OP is using xlrd ... here are a couple of performance hints.
Doesn't matter too much with this simple example, but if you are going to do a lot of coordinate-based accessing of cell values, you can do better than that by using Sheet.cell_value(rowx, colx) instead of Sheet.cell(rowx, colx).value which builds a Cell object on the fly:
queries = set(argv[1:])
hlo = []
for i in range(len(sh.nrows)): # all columns have the same size
if sh.cell_value(i, 1) in queries:
hlo.append(sh.cell_value(i, 8))
or you could use a list comprehension along with the Sheet.col_values(colx) method:
hlo = [
v8
for v1, v8 in zip(sh.col_values(1), sh.col_values(8))
if v1 in queries
] | unknown | |
d5085 | train | You'll need two things for this:
*
*A suitable XML parser.
*A custom table model, illustrated here.
Depending on the chosen parser, you can either
*
*Construct a Java data structure, e.g. List<Entity>, that can be accessed in the TableModel.
*Access the document object model directly to meet the TableModel contract for getValueAt(), getRowCount(), etc.
Addendum: Based on your edit,
*
*While you evaluate other parsing options, start with a simple SAXParser, illustrated here. The example builds a List<School>; you'll build a List<TableData>.
*In your custom table model, extend AbstractTableModel to get the event handling illustrated here. | unknown | |
d5086 | train | Since this is a programming Q&A site, we may as well write a program to do this for us :-)
You can create a script called (for example) odw for OpenDiffWeb which will detect whether you're trying to access web-based files and first download them to a temporary location.
Examine the following script, it's pretty rudimentary but it shows the approach that can be taken.
#!/bin/bash
# Ensure two parameters.
if [[ $# -ne 2 ]] ; then
echo Usage: $0 '<file/url-1> <file/url-2>'
exit 1
fi
# Download first file if web-based.
fspec1=$1
if [[ $fspec1 =~ http:// ]] ; then
wget --output-document=/tmp/odw.$$.1 $fspec1
fspec1=/tmp/odw.$$.1
fi
# Download second file if web-based.
fspec2=$2
if [[ $fspec2 =~ http:// ]] ; then
wget --output-document=/tmp/odw.$$.2 $fspec2
fspec2=/tmp/odw.$$.2
fi
# Show difference of two files.
diff $fspec1 $fspec2
# Delete them if they were web-based.
if [[ $fspec1 =~ /tmp/odw. ]] ; then
rm -f $fspec1
fi
if [[ $fspec2 =~ /tmp/odw. ]] ; then
rm -f $fspec2
fi
In this case, we detect a web-based file as one starting with http://. If it is, we simply use wget to bring it down to a temporary location. Both files are checked this way.
Once both files are on the local disk (either because they were brought down or because thet were already there), you can run the diff - I've used the standard diff but you can substitute your own.
Then, the temporary files are cleaned up.
As a test, I downloaded the page http://www.example.com and made a very minor change to it then compared the page to my modified local copy:
pax> odw http://www.example.com example.txt
--2014-09-25 16:40:02-- http://www.example.com/
Resolving www.example.com (www.example.com)... 93.184.216.119,
2606:2800:220:6d:26bf:1447:1097:aa7
Connecting to www.example.com (www.example.com)|93.184.216.119|:80...
connected.
HTTP request sent, awaiting response... 200 OK
Length: 1270 (1.2K) [text/html]
Saving to: `/tmp/odw.6569.1'
100%[=================================>] 1,270 --.-K/s in 0s
2014-09-25 16:40:02 (165 MB/s) - `/tmp/odw.6569.1' saved [1270/1270]
4c4
< <title>Example Domain</title>
---
> <title>Example Domain (slightly modified)</title>
Now there's all sorts of added stuff that could go into that script, the ability to pass flags to the diff and wget programs, the ability to handle other URL types, deletion of temporary files on signals and so on.
But it should hopefully be enough to get you started. | unknown | |
d5087 | train | AS your form is like this
<form class="form-horizontal tasi-form" method="post" name="user-form" action="{{url('services/store')}}" id="slider-form" enctype="multipart/form-data">
Add an route in your route file as
Route::post('services/store','ServicesController@checkEmail');
Modified:- Change
<form class="form-horizontal tasi-form" method="post" name="user-form" action="services/store"
id="slider-form" enctype="multipart/form-data">
Route::post('services/store','ServicesController@checkEmail');
Then try
It will work for you. | unknown | |
d5088 | train | This is the script I use myself using laravel 4 to flush a complete DB in Fortrabbit
DB::statement('SET FOREIGN_KEY_CHECKS=0');
$tables= DB::select('SHOW TABLES;');
foreach ($tables as $table) {
foreach ($table as $key=>$tableName) {
$tables= DB::statement("DROP TABLE $tableName;");
}
}
DB::statement('SET FOREIGN_KEY_CHECKS=1');
A: This answer is from Fortrabbit Support:
sorry, it's not possible to reset the git repo (for now).
But you can push new code any time. You can also delete files when you ssh into you App.
If you want to start form the scratch, I suggest to spin up a new App. | unknown | |
d5089 | train | Robert, you should directly return view from your Ajax call in your laravel method and just bind html response from the view with your new data.
That is pretty easy way of doing it. | unknown | |
d5090 | train | If you have data that is too large to fit in memory, you may pass a function returning a generator instead of a list.
from efficient_apriori import apriori as ap
def data_generator(df):
"""
Data generator, needs to return a generator to be called several times.
Use this approach if data is too large to fit in memory.
"""
def data_gen():
yield [tuple(row) for row in df.values.tolist()]
return data_gen
transactions = data_generator(df)
itemsets, rules = ap(transactions, min_support=0.9, min_confidence=0.6) | unknown | |
d5091 | train | Assuming you have a list of lists (like in the example, and not actual tuples):
problem = [[0, 3], [1, 3], [1, 2], [1, 2], [0, 1], [0, 3]]
You want to pair these pairs so that each pair contains each of the values in (0, 1, 2, 3) exactly once?
target = [0, 1, 2, 3]
And all the pairs that cannot be matched remain by themselves? This is one way of doing it:
answer = []
while problem:
# take the first element from problem
x1 = problem.pop()
# construct what the paired element should look like
x2 = [x for x in target if x not in x1]
try:
# attempt to remove it from problem
problem.remove(x2)
# if the remove succeeds, both x1 and x2 have now been removed, add the pair
answer.append([x1, x2])
except ValueError:
# when trying to remove a non-existent value, a ValueError is raised
# in that case, there is no matching pair, just add a single
answer.append(x1)
That's assuming:
*
*you never have values in the pairs that don't appear in the target
*the values in the pairs are always ordered like they are in the target
*you don't mind that the singles are mixed with the combinations
*you don't mind that the original problem is modified during the process
Put together:
problem = [[0, 3], [1, 3], [1, 2], [1, 2], [0, 1], [0, 3]]
target = [0, 1, 2, 3]
answer = []
while problem:
x1 = problem.pop()
x2 = [x for x in target if x not in x1]
try:
problem.remove(x2)
answer.append([x1, x2])
except ValueError:
answer.append(x1)
print(answer)
Result:
[[[0, 3], [1, 2]], [0, 1], [[1, 2], [0, 3]], [1, 3]]
A: Since the entries are only 0, 1, 2, 3 and the values are unique in every tuple, it means that the sum of the tuple can be generated by only one pair, except for 3, I mean:
[0, 1] is the only tuple wich the sum of values return 1, by the same way [0, 2] is the only one to return 2, but [0,3] and [1,2] return 3, so them require to check if it is a tuple containing one specific value, such as 3
a = [[0, 3], [1, 3], [1, 2], [1, 2], [0, 1], [0, 3]]
b = []
c = []
d_03 = []
d_12 = []
e = []
f = []
list_of_pairs = []
for tuples in a:
if sum(tuples) == 1:
b.append(tuples)
elif sum(tuples) == 2:
c.append(tuples)
elif sum(tuples) == 4:
e.append(tuples)
elif sum(tuples) == 5:
f.append(tuples)
#testing if there is a 3 in that tuple as suggested above
elif sum(tuples) == 3 and 3 in tuples:
d_03.append(tuples)
else:
d_12.append(tuples)
#one way to figure out the perfect range would be compare the len of the lists that match and use the smaller one, so you don not need the else statement
for i in range(5):
#compare len with i+1 because python starts counting from 0
#if there is any element in those lists, their len will be bigger than 0
if len(b) >= i+1 and len(f) >= i+1:
#b have [0, 1] only as tuples
#f have [2, 3] only as tuples
#so when you append one after the other, they will always match
list_of_pairs.append(b[i])
list_of_pairs.append(f[i])
#pop it so at the end will only be in those lists the ones wich don't have their pair
b.pop(i)
f.pop(i)
#insert blank spaces just so you do not modify the indexes of any elements in the list
b.insert(i-1, '')
f.insert(i-1, '')
else:
#break it because if you run the conditional above it will return IndexError
#the following i values would also return this error
break
for i in range(5):
#same principle for c and e
#and after for d
if len(c) >= i+1 and len(e) >= i+1:
list_of_pairs.append(c[i])
list_of_pairs.append(e[i])
c.pop(i)
e.pop(i)
c.insert(i-1, '')
e.insert(i-1, '')
else:
break
for i in range(5):
if len(d_12) >= i+1 and len(d_03) >= i+1:
list_of_pairs.append(d_03[i])
list_of_pairs.append(d_12[i])
d_12.pop(i)
d_03.pop(i)
d_12.insert(i-1, '')
d_03.insert(i-1, '')
else:
break
#this final list must have the pairs and also the rest
final_list = []
#append the pairs so it will be presented first and as a list inside the final list
final_list.append(list_of_pairs)
#extend by all the previous lists except for list of pairs and a
#this will put any rest in the final list as separate therms from the pairs
final_list.extend(b)
final_list.extend(c)
final_list.extend(d_03)
final_list.extend(d_12)
final_list.extend(e)
final_list.extend(f)
#now the final list might have some '' as rest
#so you can loop through it removing them
while '' in final_list:
final_list.remove('')
print(final_list)
This is the output:
[[[0, 3], [1, 2], [0, 3], [1, 2]], [0, 1], [1, 3]] | unknown | |
d5092 | train | Inside your freelancer.js file you're targeting all the a tags inside the navbar (which includes the navbar-toggle) to collapse the mobile menu when clicking any link.
Currently you have this:
// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
$('.navbar-toggle:visible').click();
});
You can prevent this by using jQuery :not() Selector
// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a:not(.dropdown-toggle)').click(function() {
$('.navbar-toggle:visible').click();
});
** As a Sidenote you should consider running your site through a Validation process if you have not all ready: See validator.nu as an example.
Working Example:
// Highlight the top nav as scrolling occurs
$('body').scrollspy({
target: '.navbar-fixed-top'
})
// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a:not(.dropdown-toggle)').click(function() {
$('.navbar-toggle:visible').click();
});
body {
position: relative;
}
section {
padding: 50px;
height: 500px;
}
section:nth-child(3) {
background-color: lightgreen;
}
section:nth-child(4) {
background-color: lightblue;
}
section:nth-child(5) {
background-color: darkblue;
}
section:nth-child(6) {
background-color: lightcoral;
}
section:nth-child(7) {
background-color: darkmagenta;
}
section:nth-child(8) {
background-color: lightskyblue;
}
section:nth-child(9) {
background-color: lightgoldenrodyellow;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<nav class="navbar navbar-default navbar-fixed-top" id="tophead">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand page-scroll" href="#">Pegasus eBrochure</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav navbar-right">
<li class="active"><a href="#">Home</a>
</li>
<li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" role="button">Packages<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#deals">Vacation Deals</a>
</li>
<li><a href="#sports">Sports</a>
</li>
<li><a href="#shopping">Shopping</a>
</li>
<li><a href="#holiday">Holiday</a>
</li>
<li><a href="#circuit">Circuits</a>
</li>
</ul>
</li>
<li><a href="#about">About</a>
</li>
<li><a href="#contact">Contact</a>
</li>
<li><a href="#"><span class="glyphicon glyphicon-user"></span> Sign Up</a>
</li>
<li><a href="#"><span class="glyphicon glyphicon-log-in"></span> Login</a>
</li>
</ul>
</div>
</div>
</nav>
<section id="deals">
<h1>Vacation Deals</h1>
</section>
<section id="sports">
<h1>Sports</h1>
</section>
<section id="shopping">
<h1>Shopping</h1>
</section>
<section id="holiday">
<h1>Holiday</h1>
</section>
<section id="circuit">
<h1>Circuits</h1>
</section>
<section id="about">
<h1>About</h1>
</section>
<section id="contact">
<h1>Contact</h1>
</section>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
A: I saw your website in the below line href="#" is missing just add that it will fix your problem
<a class="dropdown-toggle" data-toggle="dropdown" role="button">Packages<span class="caret"></span></a> | unknown | |
d5093 | train | In iPhone OS 4.0 and later, block-based animation methods are recommended by Apple such as
+ (void)animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations
for eg.
[UIView animateWithDuration:0.3
delay:0
options:UIViewAnimationOptionBeginFromCurrentState
animations:(void (^)(void)) ^{
self.view.frame = CGRectOffset(self.view.frame, 0, 70); }
completion:^(BOOL finished){
}];
A: So, there will be a UITableView that come from above to self.view and you wanted to move down all the elements in self.view, except the UITableView.
How about putting all the elements in self.view to a container view what have the same size as self.view? And then you can animate all the UI elements with one move
A: Yes, you missed commitAnimations for the view.
A: try this,
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.3];
[UIView setAnimationDelay:0.3];
self.view.frame = CGRectOffset(self.view.frame, 0, 70);
[UIView commitAnimations]; | unknown | |
d5094 | train | I'm sure it depends on the parser you are using... it seems than any scrupulous parser would follow that rule due to the structure of JSON... curly brackets around every "object" key/value pair, including any wrapping document { }).
As always with programming, test rather than assume. | unknown | |
d5095 | train | Let me clarify few of the things.
Mapped network drives are saved in Windows on the local computer. They're persistent, not session-specific,and can be viewed and managed in File Explorer and other tools.
When you scope the command locally, without dot-sourcing, the Persist parameter doesn't persist the creation of a PSDrive beyond the scope in which you run the command. If you run New-PSDrive inside a script, and you want the new drive to persist indefinitely, you must dot-source the script. For best results, to force a new drive to persist, specify Global as the value of the Scope parameter and include Persist in your command.
The name of the drive must be a letter, such as D or E. The value of Root parameter must be a UNC path of a different computer. The PSProvider parameter's value must be FileSystem.
So technically, you dont need to persist, you just need to specify the -Root properly:
New-PSDrive -PSProvider filesystem -Root C:\full\path\ -Name anyname
In your case the full path would be an UNC path \\remoteserver\full\path of FTP | unknown | |
d5096 | train | Self-answering the question so it doesn't keep coming up as unanswered.
I've used the code from Uncle Tomm's blog to solve the problem.
I just need a good algorithm for displaying nearby placenames without them overlapping... but that's another question! | unknown | |
d5097 | train | The only practical way to add support for VS 2017 is to open and build your extension in VS 2017: How to: Migrate Extensibility Projects to Visual Studio 2017. After the migration it should be easy to debug in VS 2017. | unknown | |
d5098 | train | call your api in onViewCreated like this.
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
callApi(); //here call your function.
} | unknown | |
d5099 | train | You can use:
#convert to datetimes if necessary
df['start_date'] = pd.to_datetime(df['start_date'])
df['end_date'] = pd.to_datetime(df['end_date'])
For each row generate list of Series by date_range, then divide their length and aggregate by groupby with sum:
dfs = [pd.Series(r.value, pd.date_range(r.start_date, r.end_date)) for r in df.itertuples()]
df = (pd.concat([x / len(x) for x in dfs])
.groupby(level=0)
.sum()
.rename_axis('date')
.reset_index(name='val'))
print (df)
date val
0 2018-05-14 1.0
1 2018-05-15 1.0
2 2018-05-16 1.0
3 2018-05-17 2.0
4 2018-05-18 2.0
5 2018-05-19 2.0
6 2018-05-20 2.0
7 2018-05-21 1.0
8 2018-05-22 2.0
9 2018-05-23 2.0
10 2018-05-24 2.0
11 2018-05-25 2.0
12 2018-05-26 2.0
13 2018-05-27 2.0 | unknown | |
d5100 | train | You need to set tableView.dataSource = self in viewWillAppear and it looks you missed func numberOfSections() -> Int method.
Add UITableViewDataSource like this
class YourViewController: UIViewController, UITableViewDataSource and it will recommend you required methods | 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.