text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Determining what action an NPC will take, when it is partially random but influenced by preferences? I want to make characters in a game perform actions that are partially random but also influenced by preferences. For instance, if a character feels angry they have a higher chance of yelling than telling a joke. So I'm thinking about how to determine which action the character will take. Here are the ideas that have come to me.
Solution #1: Iterate over every possible action. For each action do a random roll, then add the preference value to that random number. The action with the highest value is the one the character takes.
Solution #2: Assign a range of numbers to an action, with more likely actions having a wider range. So, if the random roll returns anywhere from 1-5, the character will tell a joke. If it returns 6-75, they will yell. And so on.
Solution #3: Group all the actions and make a branching tree. Will they take a friendly action or a hostile action? The random roll (with preference values added) says hostile. Will they make a physical attack or verbal? The random roll says verbal. Keep going down the line until you reach the action.
Solution #1 is the simplest, but hardly efficient. I think Solution #3 is a little more complicated, but isn't it more efficient?
Does anyone have any more insight into this particular problem? Is #3 the best solution? Is there a better solution?
A: #1 and #2 are simple but probably won't scale well to more complicated behaviors. Behavior trees (#3) seem to be the preferred system in many games nowadays. You can find some presentations and notes on AiGameDev.com, e.g. http://aigamedev.com/open/coverage/paris09-report/#session3 and http://aigamedev.com/open/coverage/gdc10-slides-highlights/#session2 (the first one from Crytek is quite good)
You probably don't need to worry about "efficiency" here in the sense of CPU usage, since this is very unlikely be a major bottleneck in your game. Reducing the amount of programmer/designer time needed to tweak the behavior is much more important.
A: If you're going to go with options 1 or 2, look into buckets of random results - see Randomness without Replacement. If you go with a tree action, you can still use some of the same concepts to determine which branch of the tree to go down; however, you'd have a bit more determinism built in, as your options will restrict as you traverse down the tree.
If I recall correctly, Neverwinter Nights, which had a fairly nice scripting engine for its NPCs, would use a random probability to determine some of the actions their NPCs would take in certain states, but the states themselves were more driven by the script for that NPC (more of a state machine than a tree, but the concepts are similar). For example, if the NPC was walking, there was a chance they would stop, maybe laugh, etc. - but if they were attacked, they would switch to combat and stay there.
In other words, it all depends on what your actions are, and how you want the character to behave.
A: Markov chain, influenced by real user actions.
From wikipedia:
A Markov chain is a discrete random
process with the property that the
next state depends only on the current
state.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2824143",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: javascript function internal scope property What is the Difference in internal scope property assigned on function declaration and on entering the function execution context?
Definition:
[[Scope]] property is already written and stored in function object. [[Scope]] in contrast with Scope (Scope chain) is the property of a function instead of a context.
Link:(http://dmitrysoshnikov.com/ecmascript/chapter-4-scope-chain/#function-creation)
What i mean is :as soon as function gets declared will it be assigned scope property or during execution time will scope property gets assigned.
A: This is the closure concept. It is worded differently here than normal. Basically there are two things going on -- first you have the closure, that is the variables that are declared locally to the context of the function definition are made available to the function. This is the "scope chain" he refers to. In addition, locally defined variables (var statements within the function) don't exist until the function starts at "execution context". (Typically these are stored on the stack or a heap).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17509208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Bluebird promises and async.forEach iteration This is my first time asking a question, so please bear with me. I'm trying to write a content scraper in node.js. My program will go to the landing page of the site, get the link to the next page and get the link for the next batch of pages. My problem is when I have to cycle through an array of links, go to that page, and get scrape information there. I'm trying a async.forEach iteration, but it finishes after the last then() in my chained promises. Many of the concepts here are new to me, so I'm sure this code is screwy. Any help would be appreciated.
var sX = require('scraper-x');
var request = require('request');
var async = require('async');
var Promise = require('bluebird');
var request = (require('request'));
var colors = require('colors');
var baseURL = 'http://shirts4mike.com';
var arrShirts = [
{
link: 'shirt.php?id=101',
img: 'some img'
},
{
link: 'shirt.php?id=102',
img: 'some img'
},
{
link: 'shirt.php?id=103',
img: 'some img'
}
];
var page = '';
var configMain = {
repeatItemGroup: '.nav > li',
dataFormat: {
link: {
selector: 'li > a',
type: 'attr:href'
}
}
};
var configShirts = {
repeatItemGroup: '.products > li',
dataFormat: {
link: {
selector: 'li > a',
type: 'attr:href'
},
img: {
selector: 'li > a > img',
type: 'attr:src'
}
}
};
var configDetails = {
repeatItemGroup: '.shirt-details',
dataFormat: {
price: {
selector: '.price',
type: 'text'
},
title: {
selector: '.shirt-details > h1',
type: 'text'
}
}
};
function getPage(url, config) {
return new Promise(function(resolve, reject) {
request(url, function(error, response, body, shirt) {
if (error) {
console.log('error');
reject();
}
if (!error && response.statusCode == 200) {
detail = sX.scrape(body, config);
resolve(detail);
}
});
});
}
function getDetailPage(arr, config) {
return new Promise(function(resolve, reject) {
async.forEach( arr, function( item, callback) {
request('http://www.shirts4mike.com' + '/' + item.link, function(error, response, body, item) {
if (!error && response.statusCode == 200) {
detail = sX.scrape(body, configDetails);
console.log('Item: ', detail);
}
});
callback();
});
resolve(detail);
});
}
getPage(baseURL, configMain).then( function(data) {
for (var i = 0; i < data.length; i++) {
//console.log('getMainPage: ', scrapedResult[i].link);
if (data[i].link.search('shirt') !== -1) {
page = '/' + data[i].link;
console.log(page.yellow);
baseURL += page;
return baseURL;
}
}
}).then( function(baseURL) {
return getPage(baseURL, configShirts);
}).then( function(data) {
for (var i = 0; i < data.length; i++) {
//console.log(data[i].link);
if (data[i].link.search('shirt') !== -1) {
arrShirts.push(data[i]);
console.log("arrShirts[" + i + "]: " + arrShirts[i].link);
}
}
return arrShirts;
}).then( function(arr) {
return getDetailPage(arrShirts, configDetails);
}).then(function (data) {
console.log("end: ", data);
}).catch( function(err) {
console.log(err);
});
A: I would suggest a bunch of changes.
*
*Stop using globals or higher scoped variables or undeclared variables. Declare local variables where they are used/needed and don't share variables with other functions.
*Don't mix the async library with promises. Since you're already promisifying your async functions, then use promise functions to manage multiple async operations. You can just remove the async library from this project entirely.
*Promisify at the lowest level that is practical so all higher level uses can just use promises directly. So, rather than promisifying getPage(), you should promisify request() and then use that in getPage().
*Since you have the Bluebird promise library, you can use it's higher level iteration functions such as Promise.map() to iterate your collection, collect all the results and return a single promise that tells you when everything is done.
Using these concepts, you can then use code like this:
// promisified request()
function getRequest(url) {
return new Promise(function(resolve, reject) {
request(url, function(err, response, body) {
if (err) {
reject(err);
} else {
resolve(body);
}
});
});
}
// resolves to scraped contents for one page
function getPage(url, config) {
return getRequest(url).then(function(body) {
return sX.scrape(body, config);
});
}
// resolves to an array of scraped contents for an array of objects
// that each have a link in them
function getDetailPage(arr, config) {
return Promise.map(arr, function(item) {
return getPage('http://www.shirts4mike.com' + '/' + item.link);
});
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40775738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using "this" in a jquery multiple selector Im trying to figure this one out, but no joy yet. For reasons that I cant go into here, I need to use both "this" and another selector to bind a click event.. Example
$('mySelector').each(function(){
$(this, this.siblings('img')).bind('click', function(e){
e.preventDefault();
doStuffTo($(this));
});
});
But I cant figure out how to do it. Anyone have any idea how I would achieve it?
A: Most of the jQuery methods (that don't return a value) are automatically applied to each element in the collection, so each() is not necessary.
Combining siblings() and andSelf(), the code can be simplified to:
$('.mySelector').siblings('img').andSelf().click(function (e) {
e.preventDefault();
doStuffTo($(this));
});
A: Instead, you could do this:
$('mySelector').each(function(){
$(this).siblings('img').andSelf()).bind('click', function(e){
e.preventDefault();
doStuffTo($(this));
});
});
A: It's not entirely clear what you're trying to do, but perhaps it's this:
var f = function(e){
e.preventDefault();
doStuffTo($(this));
};
$('mySelector').each(function() {
$(this).bind('click', f);
$(this).siblings('img').bind('click', f);
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5731196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Google Domain Shared Contacts API Using OAuth 2.0 for Server to Server Applications - Credential params I'm trying to get the "Google Domain Shared Contacts API" described here:
https://developers.google.com/admin-sdk/domain-shared-contacts/
Working using "OAuth 2.0 for Server to Server Applications" described here:
https://developers.google.com/accounts/docs/OAuth2ServiceAccount
The recommendation from the OAuth page is to use the provided Google client library... I'm using the Java library. But the Shared-Contacts API doesn't have an example that uses this library, and I'm having trouble figuring out how to use the library with the Shared-Contacts API.
I am able to make the example for the OAuth to work for me... It uses Google Cloud Storage. Here's a snippet of the code:
String STORAGE_SCOPE = "https://www.googleapis.com/auth/devstorage.read_write";
try {
try {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
String p12Content = Files.readFirstLine(new File(keyFile), Charset.defaultCharset());
// Build service account credential.
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(Collections.singleton(STORAGE_SCOPE))
.setServiceAccountPrivateKeyFromP12File(new File(keyFile))
.build();
// Set up and execute Google Cloud Storage request.
String URI;
URI = "https://storage.googleapis.com/" + BUCKET_NAME;
HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
GenericUrl url = new GenericUrl(URI);
HttpRequest request = requestFactory.buildGetRequest(url);
HttpResponse response = request.execute();
content = response.parseAsString();
} catch (IOException e) {
System.err.println(e.getMessage());
}
} catch (Throwable t) {
t.printStackTrace();
}
return content;
It's a request to get a listing of what's in a certain bucket on GCS. It calls a specific URL using the Credentials object, where the Credentials object does the work of the OAuth, using a key file I downloaded. There's other steps involved for getting it to work (setting the service account email, etc), which I did. It returns an xml string containing what is inside the bucket, and it works fine for me.
I then tried changing the URI to this string:
URI = "https://www.google.com/m8/feeds/contacts/myGoogleAppsDomain.com/full";
and I changed the STORAGE_SCOPE variable to be this string:
STORAGE_SCOPE = "http://www.google.com/m8/feeds/";
Hoping it would then return an xml-string of the shared-contacts. But instead, it returns this error:
403 Cannot request contacts belonging to another domain
I believe I'm getting this error because I'm not specifying the "hd" parameter when I do the authentication request... However, I'm unsure how I can specify the "hd" parameter using the GoogleCredential object (or the other parameters, except for "scope")... Can someone help me with that?
A: I think the issue here is that you are not specifying which user you want to impersonate in the domain (and you haven't configured the security settings in your domain to authorize the service account to impersonate users in the domain).
The doubleclick API auth documentation has good examples on how to do this. You can use their sample and replace the scopes and API endpoint:
https://developers.google.com/doubleclick-publishers/docs/service_accounts#benefits
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23820185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Data Studio SYSTEM_ERROR Code 13 with SQL query SELECT user_leads.id,
first_name AS 'Nombres',
last_name AS 'Apellidos',
ip AS 'IP o número de telefono',
city AS 'Ciudad',
state AS 'Estado',
From_unixtime(user_leads.timestamp) AS 'Fecha',
Count(wadmin.id) AS 'Total Grupos de Whatsapp (Admin)',
Coalesce(Group_concat(wadmin.name), '') AS 'Grupos de Whatsapp (Admin)',
lead_sources.name AS 'Fuente',
lead_statuses.name AS 'Status',
dw.session_id
FROM user_leads
LEFT JOIN dialogflow_sessions AS dw
ON dw.lead_id = user_leads.id
LEFT JOIN user_lead_global_fields AS gf_ans
ON gf_ans.leadid = user_leads.id
LEFT JOIN lead_sources
ON lead_sources.id = sourceid
LEFT JOIN lead_statuses
ON lead_statuses.id = user_leads.statusid
LEFT JOIN whatsapp_groups AS wadmin
ON wadmin.admin_lead_id = user_leads.id
GROUP BY user_leads.id
ORDER BY user_leads.id DESC
Im currently using that query, here is what I tried
*
*Removing special characters
*Removing "as *" statements
*clearing cache
*changing sql data source and double checked my connection yet nothing
Has anyone faced this issue?
A: Found it. Data Studio doesn't like spaces in column aliases, yet it won't show any error for them. The working is the same with all spaces in aliases replaced by underscore
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65298036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Multiple Actions (Forms) on one Page - How not to lose master data, after editing detail data? I've got a form where users can edit members of a group.
So they have the possibilty to add members or remove existing members. So the Url goes like
".../Group/Edit/4" Where 4 is the id of the group.
the view looks like this
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm("AddUser", "Group")) %>
<%{%>
<label for="newUser">User</label>
<%=Html.TextBox("username")%>
<input type="submit" value="Add"/>
</div>
<%}%>
<% using (Html.BeginForm("RemoveUser", "Group")) %>
<%{%>
<div class="inputItem">
<label for="groupMember">Bestehende Mitglieder</label>
<%= Html.ListBox("groupMember", from g in Model.GetMembers() select new SelectListItem(){Text = g}) %>
<input type="submit" value="Remove" />
</div>
<%}%>
</asp:Content>
The problem is that after adding or removing one user i lose the id of the group. What is the best solution for solving this kind of problem?
Should I use hidden fields to save the group id?
Thanks in advance.
A: Hidden fields are a good way of persisting the id during posts.
A: You could use a hidden field or you could just parse the value into your route. I'm not sure how you're parsing the group id to the view but it would look something like:
<% using (Html.BeginForm("AddUser", "Group", new { groupId = Model.GroupID })) { %>
Then your controller will look something like this using the PRG pattern
[HttpGet]
public ViewResult Edit(int groupId) {
//your logic here
var model = new MyModel() {
GroupID = groupId
};
return View("Edit", model);
}
[HttpPost]
public ActionResult AddUser(int groupId, string username) {
//your logic here
return RedirectToAction("Edit", new { GroupID = groupId });
}
[HttpPost]
public ActionResult RemoveUser(int groupId, string username) {
//your logic here
return RedirectToAction("Edit", new { GroupID = groupId });
}
The advantage to this method is that it's more RESTful
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2551716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to properly continue tasks when a given parameter is different I'm facing tasks right now and I have doubts. After an email/pass registration, I had to update the user's profile. So I first tried this:
FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password);
.continueWithTask(new Continuation<AuthResult, Task<Void>>() {
@Override
public Task<Void> then(@NonNull Task<AuthResult> t) throws Exception {
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(fullname)
.build();
return t.getResult().getUser().updateProfile(profileUpdates);
}
})
.addOnFailureListener(this, mOnSignInFailureListener)
.addOnSuccessListener(this, mOnSignInSuccessListener); // <- problem!
The problem is in the last line my listener waits for an AuthResult parameter but updateProfile task sends a Void. I handled that situation like bellow but it seems too messy. Tell me if there is another better way to do this:
final Task<AuthResult> mainTask;
mainTask = FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password);
mainTask
.continueWithTask(new Continuation<AuthResult, Task<Void>>() {
@Override
public Task<Void> then(@NonNull Task<AuthResult> t) throws Exception {
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(fullname)
.build();
return t.getResult().getUser().updateProfile(profileUpdates);
}
})
.continueWithTask(new Continuation<Void, Task<AuthResult>>() {
@Override
public Task<AuthResult> then(@NonNull Task<Void> t) throws Exception {
return mainTask;
}
})
.addOnFailureListener(this, mOnSignInFailureListener)
.addOnSuccessListener(this, mOnSignInSuccessListener);
A: It looks like you're expecting an AuthResult to get passed directly to mOnSignInSuccessListener. In this particular case, in my opinion, it's not worthwhile to try to coerce an extra Continuation to return the value you're looking for.
Instead of trying to arrange for the AuthResult to be passed to that listener as a parameter, the listener can simply reach directly into mainTask.getResult(), or you can save the AuthResult in a member variable and access it that way. Either way, it's safe because the mOnSignInSuccessListener will only be invoked after mainTask completes, which ensures the AuthResult is ready.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40161374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to check if it's null? I retrieve data from database like below. How do I check whether the value retrieved from database is null?
Private Function GetBatch() As DataSet
Dim dataset As New DataSet
Dim adapter As Data.SqlClient.SqlDataAdapter
Dim cn As New System.Data.SqlClient.SqlConnection(connectionstring())
GetBatchCommand.Connection = cn
adapter = New Data.SqlClient.SqlDataAdapter(GetBatchCommand)
adapter.Fill(dataset)
Return dataset
End Function
Dim dataset As New DataSet
dataset = GetBatch()
With dataset.Tables(0)
Dim PersonID As String = .Rows(int).Item("personId")
I'd like to check whether personID is null. How do do that?
A: Try DataRow's IsNull method to check null values :
Dim isPersonIDNull As Boolean = .Rows(0).IsNull("personId")
Or use IsDBNull method :
Dim isPersonIDNull As Boolean = IsDBNull(.Rows(int).Item("personId"))
Or manually Check if the value equals DBNull :
Dim isPersonIDNull As Boolean = .Rows(int).Item("personId").Equals(DBNull.Value)
A: If DBNull.Value.Equal(.Rows(int).Item("personId")) Then
...
DBNull
A: You can also use the Convert.DbNull constant.
A: You have to check if the value is null before you assign it to PersonID
like:
if .Rows(int).Item("personId") = DBNull.Value Then
' Assign some Dummy Value
PersonID = ""
else
PersonID = .Rows(int).Item("personId")
end if
I would recommend to extract that piece of code into a helper method which gets either the value or a default for a given column.
A: This situation can occur if table with no rows, that time ds.Table(0).Rows(int).Item("personId") will return null reference exception
so you have to use two conditions
Dim PersonID As String =""
if(ds.tables.count>0) Then
if(ds.tables(0).Rows.Count>0) Then
if(NOT DBNull.Value.Equal((ds.tables(0).Rows(int).Item("PersonID"))) Then
PersonID = ds.tables(0).Rows(int).Item("PersonID")
I think It will solve your issue..just minor syntax variation may be present
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1453429",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Concatenating char variables I tried making a small program using the libraries "iostream" and "String" to display a given string backwardly as the output on the command prompt. I used a recursive returning-value (string) function to perform the whole process of getting the given string in backward and returning it to the main function to be displayed on screen, as you can see below:
#include <iostream>
#include <string>
using namespace std;
string rev(string, int);
int main() {
string let;
cout << "Enter your string: ";
cin >> let;
cout << "The string in reverse is: " << rev(let, let.length());
cout << endl;
return 0;
}
string rev(string x, int y) {
if (y != 0 )
return x[y - 1] + rev(x, y - 1);
else
return "\0";
}
What I don't get about the process, is that while the concatenation performed on the rev function, recursively, and with the char variables works correctly and returns the string in backward to the main function, trying to concatenate the char variables normally like this gives rubbish as the output:
#include <iostream>
#include <string>
using namespace std;
int main() {
string hd;
string ah = "foo";
hd = ah[2] + ah[1] + ah[0];
cout << hd << endl;
return 0;
}
And even if I add to the "hd" chain "\0", it still gives rubbish.
A: Your first example implicitly converts characters to strings and uses appropriate operator +
While your second example is adding up characters
https://en.cppreference.com/w/cpp/string/basic_string/operator_at
returns reference to character at position
A: Writing instead
hd = ""s + ah[2] + ah[1] + ah[0];
will, informally speaking, put + into a "concatenation mode", achieving what you want. ""s is a C++14 user-defined literal of type std::string, and that tells the compiler to use the overloaded + operator on the std::string class on subsequent terms in the expression. (An overloaded + operator is also called in the first example you present.)
Otherwise, ah[2] + ah[1] + ah[0] is an arithmetic sum over char values (each one converted to an int due to implicit conversion rules), with the potential hazard of signed overflow on assignment to hd.
A: How about making use of everything that's already available?
string rev(const string &x) { return string{x.rbegin(), x.rend()}; }
Reverse iterators allow you to reverse the string, and the constructor of string with 2 iterators, constructs an element by iterati from begin to end.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57589468",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL - Average Quarter-Hour Persons (AQH) In radio broadcasting there is a term called, "Average Quarter-Hour Persons" aka (AQH), which can be defined as...as the average number of persons listening to a particular station for at least five minutes during a 15-minute period.
I am not quite sure how to start this in SQL as the listening sessions span between the different 15-minute buckets.
The 15-minute buckets are 0-15, 15-30, 30-45, and 45-60.
Here is an example from the creator of the metric, "For example, 1:00-1:05, 1:00-1:10 or 1:00-1:15 each equal one quarter-hour of listening. But, 1:11-1:19 is
not a quarter-hour of listening (there is not five minutes in either clock quarter-hour, 1:00-1:15 or 1:15-1:30)."
Let's assume I have the following table where each row contains the radio station, the time a user started listening and the time the user stopped listening. For sake of simplicity I am not including any sort of User ID, etc.
radio_station varchar
session_start time
session_stop time
How would I write the SQL to calculate said metric per hour?
A: This query work in sql server. Only question is how to handle those sessions that span or end at midnight, how they are represented.
Set up sample data:
declare @t table(session_start time, session_stop time)
insert @t values ('1:00','1:05'),('1:00','1:10'),('1:00','1:15'),('1:11','1:19')
Query based on a CTE. Create the time buckets. If CTEs are not available, create a table containing these entries instead., and rest of the query is unchanged.
;with valid_times as (
select convert(time,'00:00') as valid_start, convert(time,'00:15') as valid_end
union all
select dateadd(minute,15,valid_start), dateadd(minute,15,valid_end)
from valid_times
where valid_start<='23:30'
)
select valid_start, valid_end,
sum(case when datediff(minute,
case when session_start<valid_start then valid_start else session_start end,
case when session_stop>valid_end then valid_end else session_stop end
)>=5 then 1 else 0 end) as AQH
from valid_times
left join @t t on valid_end>=session_start and valid_start<=session_stop
group by valid_start, valid_end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52619204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Create a new column in excel with a condition I want to create a new column called Book in which I take data from a column called Exposure. If the value from the exposure column is 0, I want it to return 100, else I want to retain the same value.
This is what I've already tried:
df['Book'] = np.where(df['Exposure']==0,100,)
how do I get it to return the same value if it's not zero?
A: Try this :
df['Book'] = df['Exposure'].replace(0, 100)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56936842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Does it matter which algorithm you use for Multiple Imputation by Chained Equations (MICE) I have seen MICE implemented with different types of algorithms e.g. RandomForest or Stochastic Regression etc.
My question is that does it matter which type of algorithm i.e. does one perform the best? Is there any empirical evidence?
I am struggling to find any info on the web
Thank you
A: Yes, (depending on your task) it can matter quite a lot, which algorithm you choose.
You also can be sure, the mice developers wouldn't out effort into providing different algorithms, if there was one algorithm that anyway always performs best. Because, of course like in machine learning the "No free lunch theorem" is also relevant for imputation.
In general you can say, that the default settings of mice are often a good choice.
Look at this example from the miceRanger Vignette to see, how far imputations can differ for different algorithms. (the real distribution is marked in red, the respective multiple imputations in black)
The Predictive Mean Matching (pmm) algorithm e.g. makes sure that only imputed values appear, that were really in the dataset. This is for example useful, where only integer values like 0,1,2,3 appear in the data (and no values in between). Other algorithms won't do this, so while doing their regression they will also provide interpolated values like on the picture to the right ( so they will provide imputations that are e.g. 1.1, 1.3, ...) Both solutions can come with certain drawbacks.
That is why it is important to actually assess imputation performance afterwards. There are several diagnostic plots in mice to do this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68794697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Set value of jtable column using setValueAt() I am trying to set the value of a jtable column using setValueAt() in netbeans and it is not working.
following is what i have set using 'customize code' option.
The columns showing null are of type boolean ie they can be checked and unchecked.
I want to read values from the database and set the column values accordingly.
pref_table = new javax.swing.JTable();
pref_table.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{"MONDAY", null, null, null, null},
{"TUESDAY", null, null, null, null},
{"WEDNESDAY", null, null, null, null},
{"THURSDAY", null, null, null, null},
{"FRIDAY", null, null, null, null},
{"SATURDAY", null, null, null, null}
},
new String [] {
"DAY", "9 A.M-11 A.M", "11 A.M-1 P.M", "1 P.M-3 P.M", "3 P.M-5 P.M"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
As the frame containing the jtable(pref_table) is initialised,the column values are either set to true or false by calling the following function but it does not seem to work.
public void set_tab_val(boolean x,int r,int c)
{
pref_table.setValueAt(true,r,c);
}
A: I have added a button to the frame and called the method which you wrote and it worked fine for me.
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class TableSetEx
{
static JTable pref_table;
public static void main(String[] args) {
pref_table = new javax.swing.JTable();
pref_table.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{"MONDAY", null, null, null, null},
{"TUESDAY", null, null, null, null},
{"WEDNESDAY", null, null, null, null},
{"THURSDAY", null, null, null, null},
{"FRIDAY", null, null, null, null},
{"SATURDAY", null, null, null, null}
},
new String [] {
"DAY", "9 A.M-11 A.M", "11 A.M-1 P.M", "1 P.M-3 P.M", "3 P.M-5 P.M"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
JButton button = new JButton("Click");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// Some hardceded cell.
set_tab_val(true,2,3);
}
});
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(pref_table), BorderLayout.NORTH);
frame.add(button, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public static void set_tab_val(boolean x,int r,int c)
{
pref_table.setValueAt(true,r,c);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15332585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Two classes inheriting from the same base to see each other I have a program with a lot of classes. I want classes in the program to be visible to each other. For that, I am following a trick such that all classes are inherited from a base class, which holds pointers to every class. But I hit an error in doing so. Below is a piece of code produces the error I am after:
#include <iostream>
using namespace std;
class AClass;
class BClass;
class RoofClass {
public:
RoofClass();
AClass* a_class;
BClass* b_class;
};
class BaseClass {
public:
BaseClass(RoofClass* roof_class) {
a_class = roof_class->a_class;
b_class = roof_class->b_class;
}
AClass* a_class;
BClass* b_class;
};
class AClass : public BaseClass {
public:
AClass(RoofClass* roof_class) : BaseClass(roof_class) {}
void Afunction();
int Aint = 1;
};
class BClass : public BaseClass {
public:
BClass(RoofClass* roof_class) : BaseClass(roof_class) {}
void Bfunction();
int Bint = 2;
};
void AClass::Afunction() {
cout << b_class->Bint << endl;
}
void BClass::Bfunction() {
cout << a_class->Aint << endl;
}
RoofClass::RoofClass() {
a_class = new AClass(this);
b_class = new BClass(this);
}
int main(int argc, char **argv) {
RoofClass roof_class;
cout << "b calls a" << endl;
roof_class.b_class->Bfunction();
cout << "a calls b" << endl;
roof_class.a_class->Afunction();
}
Roof is the top level class which consists of classes A and B. I want A and B visible to each other. To achieve that, as I said, they both inherit from the Base class. My problem, in particular, is that while B sees A, A does not see B. The reason for this is probably due to the fact that A is initialized before B in constructor of Roof. So, why can I solve this issue?
A: When RoofClass constructor creates an instance of AClass, it passes a pointer to itself, with uninitialized members a_class and b_class. AClass constructor then copies those values and returns. When RoofClass constructor sets a_class to point to the newly constructed object, the pointers inside AClass are still pointing to nothing.
You probably want BaseClass to store a pointer to RoofClass instead:
class BaseClass {
public:
BaseClass(RoofClass* roof_class) {
r_class = roof_class;
}
RoofClass* r_class;
};
class AClass : public BaseClass {
public:
AClass(RoofClass* roof_class) : BaseClass(roof_class) {}
void Afunction();
int Aint = 1;
// access class B as r_class->b_class
};
A: I actually solved the question. It is like this:
In its constructor, the RoofClass creates a and b objects, in order. It first initializes a object by going into its constructor (which actually is the constructor of BaseClass due to inheritance) and setting a's a and b objects to roof's a and b. But the problem is that, roof's b is not constructed yet. That is why, a's b is initialized to a value of 00000000. When the RoofClass goes to b object's constructor for initialization, this time both roof's a and b are in place so that b's a and b's b are properly initialized. That is why, b can have a proper a but not vice versa.
The solution is introducing an InitPointer function to the base class, which acts after the roof objects constructs all a and b objects. This way, InitPointer sets pointers of a and b objects to already constructed a and b objects. Here is the working code:
#include <iostream>
using namespace std;
class AClass;
class BClass;
class RoofClass {
public:
RoofClass();
AClass* a_class;
BClass* b_class;
};
class BaseClass {
public:
BaseClass() {}
void InitPointer(RoofClass* roof_class) {
a_class = roof_class->a_class;
b_class = roof_class->b_class;
}
AClass* a_class;
BClass* b_class;
};
class AClass : public BaseClass {
public:
AClass() : BaseClass() {}
void Afunction();
int Aint = 1;
};
class BClass : public BaseClass {
public:
BClass() : BaseClass() {}
void Bfunction();
int Bint = 2;
};
void AClass::Afunction() {
cout << b_class->Bint << endl;
}
void BClass::Bfunction() {
cout << a_class->Aint << endl;
}
RoofClass::RoofClass() {
a_class = new AClass();
b_class = new BClass();
a_class->InitPointer(this);
b_class->InitPointer(this);
}
int main(int argc, char **argv) {
RoofClass roof_class;
cout << "b calls a" << endl;
roof_class.b_class->Bfunction();
cout << "a calls b" << endl;
roof_class.a_class->Afunction();
}
Thanks for the all discussion!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24874088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: wcf configuration maxStringContentLength does not seem to be working We're trying to send a large xml string to a service method in WCF and we're getting the error
The maximum string content length
quota (8192) has been exceeded while
reading XML data.
The error suggests increasing the maxstringcontentlength although we weren't sure if we were supposed to do this on the client side or the server side or both. We've tried putting in on both but we still seem to get the error. I'm going to post the client and service configs below. I'm assuming there is a problem with one or both of them preventing this from working.
Any suggestions?
Client:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_ITESTService"
closeTimeout="00:01:00" openTimeout="00:01:00"
receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false"
hostNameComparisonMode="StrongWildcard"
maxBufferSize="65536" maxBufferPoolSize="524288"
maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8"
transferMode="Buffered" useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="4096"
maxNameTableCharCount="2147483647" />
<security mode="None" />
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint name="BasicHttpBinding_ITESTService"
address="http://localhost/TESTService.svc"
binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_ITESTService"
contract="TESTService.ITESTService" />
</client>
</system.serviceModel>
Server:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding
name="BasicHttpBinding_Service1"
maxBufferSize="2147483647"
maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="32"
maxStringContentLength="2147483647" maxArrayLength="2147483647"
maxBytesPerRead="4096" maxNameTableCharCount="2147483647" />
<security mode="None" />
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="TESTService">
<endpoint name="BasicHttpBinding_Service1"
address="http://localhost/TESTService.svc"
binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_Service1"
contract="ITESTService" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
A: Try adding a 'default' binding (without any name specified).
Add the readerQuota settings to this binding.
You can then even remove the readerQuota settings from the named binding you are actually using.
This worked for me (although I'm not sure why the readerQuotas on the correct named binding are ignored by WCF)
A: 'default' binding option worked for me. I was trying customize maxStringContentLength value in named WebHttpBinding but for some reason it did not picked up by WCF. finally I followed the D.Tiemstra work around then it started working.
<webHttpBinding>
<binding maxReceivedMessageSize="2147483647" >
<readerQuotas maxDepth="2147483647"
maxStringContentLength="2147483647"
maxArrayLength="2147483647"
maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647" />
</binding>
</webHttpBinding>
A: This thread explains in detail how to specify the binding settings on server and client correctly in order to change the MaxStringContentLength.
This other thread also provides a clear and efficient answer on using the readerQuotas.
A: I would use this values for the WCF configuration (programmatically):
Security = { Mode = SecurityMode.None},
CloseTimeout = TimeSpan.MaxValue,
OpenTimeout = TimeSpan.MaxValue,
SendTimeout = TimeSpan.FromMinutes(5),
ReceiveTimeout = TimeSpan.FromMinutes(5),
MaxBufferSize = 2147483647,
MaxBufferPoolSize = 524288,
MaxReceivedMessageSize = 2147483647,
ReaderQuotas = new XmlDictionaryReaderQuotas
{
MaxDepth = 32,
MaxStringContentLength = 8192,
MaxArrayLength = 16384,
MaxBytesPerRead = 4096,
MaxNameTableCharCount =1638
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4834489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: find element that doesn't equal a string in xpath Need help in finding element that doesn't equal to a string, Here is my XML:
<collection >
<device>
<name>Test</name>
<dcs>
<dc>
<nodes>
<node>
<name>Host1</name>
</node>
<node>
<name>test</name>
</node>
<node>
<name>testing</name>
</node>
</nodes>
</dc>
<dc>
<nodes>
<node>
<name>test</name>
</node>
<node>
<name>testing</name>
</node>
</nodes>
</dc>
</dcs>
</device>
XPath I have tried:
/collection/device/dcs/dc/nodes/node[not(contains(name,'test'))]
O/p:
<node>
<name>Host1</name>
</node>
Expected O/p:
<node>
<name>Host1</name>
</node>
<node>
<name>testing</name>
</node>
Actual output is ignoring testing also but that I need in output.
Can anyone help me?
Thanks in advance.
A: To filter out nodes having inner text exactly equals certain value, use = operator wrapped in not() instead of using contains() in the same way :
/collection/device/dcs/dc/nodes/node[not(name='test')]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32579643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MediaPlayer.OnCompletionListener and View.OnClickListener? I am currently trying:
extends Activity implements MediaPlayer.OnCompletionListener
extends Activity implements View.OnClickListener
at the same time and its not working or rather im not sure how to implement it...how would I go about doing this?
edit: maybe it will help if I show you guys what I have now and its not working:
package com.vamp6x6x6x.rusty;
import java.io.IOException;
import com.vamp6x6x6x.rusty.R;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
public class rustyactivity extends Activity implements MediaPlayer.OnCompletionListener, View.OnClickListener {
/** Called when the activity is first created. */
ImageView display;
int toPhone;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
display = (ImageView) findViewById(R.id.IVDisplay);
ImageView image1 = (ImageView) findViewById(R.id.IVimage1);
ImageView image2 = (ImageView) findViewById(R.id.IVimage2);
ImageView image3 = (ImageView) findViewById(R.id.IVimage3);
ImageView image4 = (ImageView) findViewById(R.id.IVimage4);
ImageView image5 = (ImageView) findViewById(R.id.IVimage5);
Button setWall = (Button) findViewById(R.id.bSetWallpaper);
toPhone = R.drawable.guy1;
image1.setOnClickListener(this);
image2.setOnClickListener(this);
image3.setOnClickListener(this);
image4.setOnClickListener(this);
image5.setOnClickListener(this);
setWall.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.IVimage1:
display.setImageResource(R.drawable.guy1);
toPhone = R.drawable.guy1;
break;
case R.id.IVimage2:
display.setImageResource(R.drawable.guy2);
toPhone = R.drawable.guy2;
break;
case R.id.IVimage3:
display.setImageResource(R.drawable.guy3);
toPhone = R.drawable.guy3;
break;
case R.id.IVimage4:
display.setImageResource(R.drawable.guy4);
toPhone = R.drawable.guy4;
break;
case R.id.IVimage5:
display.setImageResource(R.drawable.guy5);
toPhone = R.drawable.guy5;
break;
case R.id.bSetWallpaper:
Bitmap whatever = BitmapFactory.decodeStream(getResources().openRawResource(toPhone));
try{
getApplicationContext().setWallpaper(whatever);
}catch(IOException e){
e.printStackTrace();
}
}
Button ending = (Button) findViewById(R.id.theme);
ending.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
playSound(R.raw.theme);
}
});
}
private void playSound(int resId) {
MediaPlayer mp = MediaPlayer.create(this, resId);
mp.setOnCompletionListener(this);
mp.start();
}
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
}
}
A: extends Activity implements MediaPlayer.OnCompletionListener, View.OnClickListener
Then you need to register your activity.
mediaPlayer.setOnCompletionListener(this);
someView.setOnClickListener(this);
Where 'this' is the activity you just created
A: Stick this code right up at the start as part of the onCreate():
MediaPlayer mp = MediaPlayer.create(this, pathToTheFile, web, whereverTheSoundIs);
mp.setOnCompletionListener(this);
mp.start();
If that doesn't work, then you have a problem locating the sound file, or it is in the wrong format.
From experience, cut things down to simple parts and try and get each part working first before moving on.
Another thing I do is put comments after each } for example: '} // End of Case'
Oh, almost forgot, in the onCompletion you might like to close off the media player with
mp.release();
Cheers
A: try this! it works to me, i hope it helps you:
main:
package com.hairdryer;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import com.hairdryer.ServiceReproductor;
public class Reproductor extends Activity implements OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton btnInicio = (ImageButton) findViewById(R.id.on);
ImageButton btnFin = (ImageButton) findViewById(R.id.off);
btnInicio.setOnClickListener(this);
btnFin.setOnClickListener(this);
}
public void onClick(View src) {
ImageButton btnInicio = (ImageButton) findViewById(R.id.on);
switch (src.getId()) {
case R.id.on:
btnInicio.setBackgroundResource(R.drawable.on2);
startService(new Intent(this, ServiceReproductor.class));
break;
case R.id.off:
stopService(new Intent(this, ServiceReproductor.class));
btnInicio.setBackgroundResource(R.drawable.on);
break;
}
}
}
ServiceReproductor.java:
package com.hairdryer;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.IBinder;
import android.widget.Toast;
public class ServiceReproductor extends Service implements OnCompletionListener{
private MediaPlayer player;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
//Toast.makeText(this, "Servicio Creado", Toast.LENGTH_LONG).show();
player = MediaPlayer.create(this, R.raw.inicio);
player.setOnCompletionListener(this);
}
@Override
public void onDestroy() {
//Toast.makeText(this, "Servicio Detenido", Toast.LENGTH_LONG).show();
player.stop();
}
@Override
public void onStart(Intent intent, int startid) {
//Toast.makeText(this, "Servicio Iniciado", Toast.LENGTH_LONG).show();
player.start();
}
@Override
public void onCompletion(MediaPlayer mp) {
player = MediaPlayer.create(this, R.raw.secador);
player.start();
player.setLooping(true);
// TODO Auto-generated method stub
}
}
main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/secador"
/>
<ImageButton android:id="@+id/off"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="@drawable/off"
/>
<ImageButton android:id="@+id/on"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_alignParentBottom="true"
android:layout_toRightOf="@+id/off"
android:layout_marginRight="10dp"
android:background="@drawable/on"
/>
</RelativeLayout>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5365323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: py2app and python 2.7 OSX 10.6 Does py2app work with python 2.7 on Snow Leopard?
I can't even get a 'hello world' to compile properly.
Here's what I'm doing...
My script is
print "Hello World"
and then from a terminal:
cd myFolder
py2applet --make-setup helloWorld.py myIcon.icns
python setup.py py2app
The build hangs indefinitely at this point. If I add the -A switch it will build, but crashes with a Tick Count error.
If I edit the setup.py file and set argv_emulation to 'False' it'll build with the -A option and work (still hangs indefinitely without the -A).
So my real question is:
How can I get this to build without the -A option?
A: It seems as though py2app had some issues with the 32/64-bit install of python 2.7 I was using (the official one from python.org).
I downloaded a 32-bit only version of 2.7 and it works now.
On a related note, on another build I was using wxPython and to get it to work without the -A switch I had to import the package explicitly in my setup.py file.
DATA_FILES = []
OPTIONS = {'argv_emulation': True,
'packages' : ['wx', 'pubsub'],
}
A: I've read that you need to leave the 'argv_emulation': True setting out of the options for a 64bit build. Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5969439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Reverse Regular Expression Matching in Javascript I have a file that contains basic examples of input and output:
[Database.txt]
Hello*==Hello. How are you?
How*are*you*==I am fine I guess.
Can you*die*==I can not die. I am software.
I will get an input string that does not have punctuation.
Example: "can you ever die in a million years"
I am trying to match the input with the first side of the database on the left of "==" and return the second side of the line the string matched the first side with.
So where input = "can you ever die in a million years", output = "I can not die. I am software."
I have to use native JavaScript. This is part of a personal project I have been working on and have not been able to get past in 4 months. It is part of an independent natural speech engine that could download the file, read it to a variable, and use it as a reference. I have tried combinations of looping through lines, splitting at "==", str.match(), and a lot of other stuff. I will manage case insensitivity. Any help would be greatly appreciated.
A: You can split it up into an array, and make each left side into a regexp.
then you can run a guantlet of tests to find the match.
the tricky part is that you need to make multiple tests, beyond just one super regexp. i used [].some() to terminate after the first match is found. you can change the some with filter and collect the output to get multiple matches.
var gaunlet=[],
str="[Database.txt]\n\
Hello*==Hello. How are you?\n\
How*are*you*==I am fine I guess.\n\
Can you*die*==I can not die. I am software.";
str.split("\n").forEach(function(a,b){
var r=a.split("==");
gaunlet[b]=[RegExp(r[0].replace(/\*/g,"[\\w\\W]*?"), "i"), r[1]];
});
function lookup(inp){
var out;
gaunlet.some(function(a){
if(a[0].test(inp)) return out=a[1];
});
return out;
}
alert(lookup("can you die in a million years?"));
fiddle: https://jsfiddle.net/joaze5u6/1/
i also wrote in a fix for the way js captures wildcards, the [\w\W]*? does what .*? should probably do but doesn't in js...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29713343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Index was outside the bounds of the array This is my code where I am getting error "Index was outside the bounds of the array."
var objectData = new object[colRindas.Count, 4];
int i = 0;
foreach (DeArtIzm izm in colRindas)
{
objectData[i, 1] = izm.ArtCode;
objectData[i, 2] = izm.ArtName;
objectData[i, 3] = izm.Price;
objectData[i, 4] = izm.RefPrice;
i++;//Place where I get that error
}
What seems to be the problem hare, cause I can't find the problem.
A: Arrays are 0-indexed instead of one.
foreach (DeArtIzm izm in colRindas)
{
objectData[i, 0] = izm.ArtCode;
objectData[i, 1] = izm.ArtName;
objectData[i, 2] = izm.Price;
objectData[i, 3] = izm.RefPrice;
i++;//Place where I get that error
}
A: in C#, Arrays are Zero-based by default (i.e. The first element has the index 0).
So you need to start with objectData[i, 0], and end with objectData[i, 3].
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10414499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to Create plus symbol with background-color in CSS? I want to create plus symbol using CSS.
this is the final output need to be shown.
But the challenge is, to create this icon using,
*
*only use one div tag
*use before/after pseudo-elements
*can't use keyboard '+' icon as a base.
A:
#plus {
/* change this value to the desired width */
--width: 40px;
/* setting the background color */
background-color: black;
/* setting height and width with the value of css variable */
width: var(--width);
height: var(--width);
/* perfect circle */
border-radius: var(--width);
/* centrering */
display: grid;
place-items: center;
/* don't delete this, is important for the ::before and ::after pseudoelements */
position: relative;
}
#plus::before,
#plus::after {
content: "";
/* using css calc() https://developer.mozilla.org/en-US/docs/Web/CSS/calc */
/* height and width relative to css variable, change to what you feel is good */
height: calc(var(--width) / 1.5);
width: calc(var(--width) / 5);
/* coloring the pseudoelements */
background-color: white;
/* here the TRICK, using calc() we easily canculate the rotation, without hardcoding this value */
transform: rotate(calc(var(--i) * 90deg));
/* important don't delete */
position: absolute;
}
#plus::before {
--i: 1;
}
#plus::after {
--i: 2;
}
<div id="plus"></div>
this code is relative to the width of the element, so just change the width and all the elements inside will be changed automatically!
#plus {
--width: 5rem; /* change this value if you need */
}
or here directly on your element (if you have multiple same buttons)
<div id="plus" style="--width: 100px;"></div>
for this I am using CSS variables, make sure to see this before https://developer.mozilla.org/en-US/docs/Web/CSS/var
Example:
*
*smaller value
*higher value:
so now you can see, the div remain always the same as with big values
the code:
#plus {
/* change this value to the desired width */
--width: 5rem;
/* setting the background color */
background-color: black;
/* setting height and width with the value of css variable */
width: var(--width);
height: var(--width);
/* perfect circle */
border-radius: var(--width);
/* centrering */
display: grid;
place-items: center;
/* don't delete this, is important for the ::before and ::after pseudoelements */
position: relative;
}
#plus::before,
#plus::after {
content: "";
/* using css calc() https://developer.mozilla.org/en-US/docs/Web/CSS/calc */
/* height and width relative to css variable, change to what you feel is good */
height: calc(var(--width) / 1.5);
width: calc(var(--width) / 5);
/* coloring the pseudoelements */
background-color: white;
/* here the TRICK, using calc() we easily canculate the rotation, without hardcoding this value */
transform: rotate(calc(var(--i) * 90deg));
/* important don't delete */
position: absolute;
}
#plus::before {
--i: 1;
}
#plus::after {
--i: 2;
}
<div id="plus"></div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72755494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: How can I obfuscate only com.foo.* but excluding com.foo.bar.*? (Proguard) I tried:
-keep class !com.foo.** { *; }
-keep class com.foo.bar.** { *; }
but it obfuscates classes other than com.foo.* (which I don't want)
I also tried:
-keep class !com.foo.**, com.foo.bar.** { *; }
and it fails to parse.
A: From your description I understand that you want to keep everything in the com.foo.bar package (+ subpackages?). You can achieve this by the following rule:
-keep class com.foo.bar.** { *; }
The ** pattern will match also subpackages, if you only want to current package, use * instead.
If you use a rule like this:
-keep class !com.foo.** { *; }
you will actually keep everything but com.foo.**, so you should be careful with exclusion patterns. Always include at least one inclusion pattern afterwards. The exclusion pattern should be more specific as the inclusion pattern, see below.
This rule should parse correctly (just tested it), but will not work, as ProGuard will stop evaluating a rule once it finds a match:
-keep class !com.foo.**, com.foo.bar.** { *; }
The exclusion pattern !com.foo.** will match everything in com.foo and subpackages, thus it will also match com.foo.bar.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37848799",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Video trimming on Android using MediaCodec, Media Extractor and Media Muxer In my Android App I need a solution when the user can trim a video from internal storage. I am trying to achieve this without using any third-party library. I was referencing this Google's Gallery App source code here. But I am getting the following error :
timestampUs 66733 < lastTimestampUs 133467 for Video track
There are few SO questions which talk about this timestamp issue, but I am really not being to figure out as I am new to using MediaCodecs, MediaMuxers etc. Would be great if any can hep
Here's my code :
// Set up MediaExtractor to read from the source.
MediaExtractor extractor = new MediaExtractor();
extractor.setDataSource(srcPath);
int trackCount = extractor.getTrackCount();
System.out.println("tracl" + trackCount);
// Set up MediaMuxer for the destination.
MediaMuxer muxer;
muxer = new MediaMuxer(dstPath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
// Set up the tracks and retrieve the max buffer size for selected
// tracks.
HashMap<Integer, Integer> indexMap = new HashMap<>(trackCount);
int bufferSize = -1;
for (int i = 0; i < trackCount; i++) {
MediaFormat format = extractor.getTrackFormat(i);
String mime = format.getString(MediaFormat.KEY_MIME);
boolean selectCurrentTrack = false;
if (mime.startsWith("audio/") && useAudio) {
selectCurrentTrack = true;
} else if (mime.startsWith("video/") && useVideo) {
selectCurrentTrack = true;
}
if (selectCurrentTrack) {
extractor.selectTrack(i);
int dstIndex = muxer.addTrack(format);
System.out.println(format);
System.out.println("dstIndex" + dstIndex);
indexMap.put(i, dstIndex);
if (format.containsKey(MediaFormat.KEY_MAX_INPUT_SIZE)) {
int newSize = format.getInteger(MediaFormat.KEY_MAX_INPUT_SIZE);
bufferSize = newSize > bufferSize ? newSize : bufferSize;
}
}
}
System.out.println(indexMap);
if (bufferSize < 0) {
bufferSize = DEFAULT_BUFFER_SIZE;
}
// Set up the orientation and starting time for extractor.
MediaMetadataRetriever retrieverSrc = new MediaMetadataRetriever();
retrieverSrc.setDataSource(srcPath);
String degreesString = retrieverSrc.extractMetadata(
MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
if (degreesString != null) {
int degrees = Integer.parseInt(degreesString);
if (degrees >= 0) {
muxer.setOrientationHint(degrees);
}
}
if (startMs > 0) {
extractor.seekTo(startMs * 1000, MediaExtractor.SEEK_TO_CLOSEST_SYNC);
}
// System.out.println(extractor.);
// Copy the samples from MediaExtractor to MediaMuxer. We will loop
// for copying each sample and stop when we get to the end of the source
// file or exceed the end time of the trimming.
int offset = 0;
int trackIndex = -1;
ByteBuffer dstBuf = ByteBuffer.allocate(bufferSize);
MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
try {
muxer.start();
while (true) {
System.out.println("copying");
bufferInfo.offset = offset;
bufferInfo.size = extractor.readSampleData(dstBuf, offset);
if (bufferInfo.size < 0 ) {
// InstabugSDKLogger.d(TAG, "Saw input EOS.");
System.out.println("Saw input EOS.");
bufferInfo.size = 0;
break;
} else {
/**
* The presentation timestamp in microseconds for the buffer.
* This is derived from the presentation timestamp passed in
* with the corresponding input buffer. This should be ignored for
* a 0-sized buffer.
*/
/**
* Returns the current sample's presentation time in microseconds.
* or -1 if no more samples are available.
*/
bufferInfo.presentationTimeUs = extractor.getSampleTime();
//1 sec = 1000000 micco sec
if (endMs > 0 && bufferInfo.presentationTimeUs > (endMs * 1000)) {
break;
} else {
bufferInfo.flags = extractor.getSampleFlags();
trackIndex = extractor.getSampleTrackIndex();
muxer.writeSampleData(indexMap.get(trackIndex), dstBuf, bufferInfo);
//System.out.println(muxer);
extractor.advance();
}
}
}
muxer.stop();
File file = new File(srcPath);
file.delete();
} catch (IllegalStateException e) {
System.out.println("The source video file is malformed");
} finally {
muxer.release();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58923605",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there an ExecutorService implementation with queue limit and an option to replace old queue members with new ones? I need an ExecutorService implementation that can limit how many Runnables can be queued. I would also like to be able to control what happens when new runnables are submitted while the queue is already full. Ideally I'd like to be able to select a strategy but just removing the runnable at the front of the queue and placing the new one at the end of the queue would suffice. I'm sure there must be something like that already implemented and I looked around but couldn't find any.
A: Use DiscardOldestPolicy :
A handler for rejected tasks that discards the oldest unhandled
request and then retries execute, unless the executor is shut down, in
which case the task is discarded.
and BlockingQueue with fixed capacity:
int fixedThreadNumber = 10;
int idleSeconds = 10;
BlockingQueue<Runnable> blockingQueue = new LinkedBlockingQueue<>(10);
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
fixedThreadNumber,
fixedThreadNumber,
idleSeconds, TimeUnit.SECONDS,
blockingQueue, new ThreadPoolExecutor.DiscardOldestPolicy());
ExecutorService executor = threadPoolExecutor;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52109822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JPA/Hibernate using shared id and cascade=all tries to save child before parent, causing foreign key violation I am using JPA with hibernate. I have a 1-to-1 parent child relationship (the child is optional), with the id shared between the two and a foreign key relationship on the child table. My entities look like this:
parent:
public class LogItemEntity {
...
@OneToOne(cascade={CascadeType.ALL}, mappedBy = "logItem", orphanRemoval=true, optional=true)
@PrimaryKeyJoinColumn(referencedColumnName="ral_id")
private LogAdditionalRequirement additionalRequirement;
...
}
child:
public class LogAdditionalRequirement {
...
@Id
@GeneratedValue(generator = "foreign")
@GenericGenerator(name = "foreign", strategy = "foreign", parameters = { @Parameter(name = "property", value = "logItem") })
@Column(name = "ral_id")
private Long id;
@OneToOne(optional=false)
@PrimaryKeyJoinColumn(referencedColumnName="id")
private LogItemEntity logItem;
...
}
When inserting a new object, the id for the parent is generated from a sequence and the cascade operation copies it onto the child. But the sql insert for the child is placed in the action queue of the session before the sql insert for the parent, and so it fails with a constraint violation on the foreign key:
ERROR o.h.util.JDBCExceptionReporter - ERROR: insert or update on table "rar_log_additional_requirement" violates foreign key constraint "fk_rar_ral_id"
Detail: Key (ral_id)=(70150) is not present in table "ral_log".
So how can I make the insert of the parent happen first?
This must be a pretty common usage, so I assume I'm doing something wrong, but I don't see what it is. I originally had the mappedBy attribute on the child side. I think that's wrong, but swapping it round made no difference.
A: One solution could be to remove the cascade "cascade={CascadeType.ALL}"
More on this subject here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23735217",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Braintree for flutter web I have a broader question. Is there any possibility to use a brain tree for the flutter web? I was searching for an API on pub.dev but there was only one for Android & Ios, but not for Web.
If there is one do you have a link to an example project, I just don't seem to find anything about the detailed integration
A: You can use Braintree using API calls with their GraphQL client. Read the whole guide on how to make API calls on their website.
Making API Calls
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73166393",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make an image fill the entire div on hover? I want an image to show up on the div when I hover it. The code I am using makes the image larger than the div, how can I contain it to the fill the size of the div and not leak?
Here is the CSS code:
img{
display: none;
max-height: 50vh;
}
.effect:hover .text{
display: none;
}
.effect:hover img{
display: block;
}
Here is the HTML code:
<div class="row">
<div class="col-lg-3 alternate_2 effect">
<h1 class="display-6 text">Studio Griot</h1>
<p class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.</p>
<a href="#">
<img src="images/Shalaj.JPG"/>
</a>
</div>
<div class="col-lg-3 effect">
<h1 class="display-6 text">Web Development</h1>
<p class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.</p>
<a href="#">
<img src="images/Shalaj.JPG"/>
</a>
</div>
<div class="col-lg-3 alternate_2 effect">
<h1 class="display-6 text">Data Visualisation</h1>
<p class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.</p>
<a href="#">
<img src="images/Shalaj.JPG"/>
</a>
</div>
<div class="col-lg-3 effect">
<h1 class="display-6 text">Incrediminds</h1>
<p class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.</p>
<a href="#">
<img src="images/Shalaj.JPG"/>
</a>
</div>
</div>
Thanks For The Help
A: EDIT with what OP actually wanted.
Here is the image that takes up the full width and height without stretching. You can use object-fit: cover
Information on object-fit: https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
img {
display: none;
width: 100%;
height: 100%;
object-fit: cover;
}
.effect:hover .text {
display: none;
}
.effect:hover img {
display: block;
}
h1.text {
font-size: 14px;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="row">
<div class="col-sm-3 alternate_2 effect">
<h1 class="display-6 text">Studio Griot</h1>
<p class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.</p>
<a href="#">
<img src="http://via.placeholder.com/500/500" />
</a>
</div>
<div class="col-sm-3 effect">
<h1 class="display-6 text">Web Development</h1>
<p class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.</p>
<a href="#">
<img src="http://via.placeholder.com/500/500" />
</a>
</div>
<div class="col-sm-3 alternate_2 effect">
<h1 class="display-6 text">Data Visualisation</h1>
<p class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.</p>
<a href="#">
<img src="http://via.placeholder.com/500/500" />
</a>
</div>
<div class="col-sm-3 effect">
<h1 class="display-6 text">Incrediminds</h1>
<p class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.</p>
<a href="#">
<img src="http://via.placeholder.com/500/500" />
</a>
</div>
</div>
Add width: 100% to the img. That will keep it 100% width of its parent. I changed your bootstrap markup to col-sm so you could see it when you run the snippet.
Added information for future visitors:
An img will always display as large as its own default/native size, unless you specify the width: 100% and make sure it is display: block, since img are inline by default.
img {
display: none;
width: 100%;
}
.effect:hover .text {
display: none;
}
.effect:hover img {
display: block;
}
h1.text {
font-size: 14px;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="row">
<div class="col-sm-3 alternate_2 effect">
<h1 class="display-6 text">Studio Griot</h1>
<p class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.</p>
<a href="#">
<img src="http://via.placeholder.com/500/500" />
</a>
</div>
<div class="col-sm-3 effect">
<h1 class="display-6 text">Web Development</h1>
<p class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.</p>
<a href="#">
<img src="http://via.placeholder.com/500/500" />
</a>
</div>
<div class="col-sm-3 alternate_2 effect">
<h1 class="display-6 text">Data Visualisation</h1>
<p class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.</p>
<a href="#">
<img src="http://via.placeholder.com/500/500" />
</a>
</div>
<div class="col-sm-3 effect">
<h1 class="display-6 text">Incrediminds</h1>
<p class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.</p>
<a href="#">
<img src="http://via.placeholder.com/500/500" />
</a>
</div>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61415503",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Efficient way to store form data? I have a web app that has a big and complex form (fields, checks, etc).
I hade using standard OS form controls because they have visual (styling) limits.
I have been basically creating spans with IDs and attaching class or custom data attributes. I later need to send this to a PHP script for insertion into a database. This has worked well in the past, but I'm having to do a lot of manual processing of fields, which I don't think is efficient... Is there a better way?
I currently do,
IF ($('#foo').hasClass('on')){bar=1}
...
Then I manually compose a POST string via
foo=bar&bla=blabla ...
Then lots more on the PHP side to create an insert SQL statement.
Seems like its inefficient if you have dozens of fields... But I hate standard FORM elements...
Any suggestions? .... Loops? Arrays?
A: You should use a form. But how to make it pretty?
With JavaScript you can have a kind of front-end for the form. Hide the form elements and have some JS that changes the form field values on interaction.
Search for pretty forms jquery in Google.
A: From what I understand is that you don't want to manually get the value of each element that has the class 'on'. You could use jQuery's each function looping through all the elements you need. Something like:
var query = "";
$(".on").each(function(i){
if(i === 0) {
query+="?"+$(this).attr('id')+"="+$(this).text();
} else {
query+="&"+$(this).attr('id')+"="+$(this).text();
}
});
(see: http://jsfiddle.net/MkbrV/)
Is this something you are looking for?
A: You could use jQuery's serialize() method:
$('form .on').serialize();
jsFiddle example
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11305151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Prefetch all relationship instances without call .all() I prefetch_related my objects with the following code:
objs = wm.ModelA.objects.prefetch_related(
'ModelB__ModelC')
and i want to iterate all ModelB from all objs and i do it with the following way
for o in objs:
for t in o.ModelB.all():
I noticed that in every iteration of e.ModelB.all() it calls the database. Is there a way to avoid this and bring all MobelB from the begining ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56732750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: OPC Foundation Tree structure I've been searching the web, but I can't figure out how to get a tree view of the items on an OPC server. I used the following code:
using Opc.Da;
using Server=Opc.Da.Server;
using Factory=OpcCom.Factory;
string urlstring = string.Format("opcda://{0}/{1}/{{{2}}}", _hostName, _serverName, serverid);
Server s = new Server(new Factory(), new URL(urlstring));
ItemIdentifier itemId = null;
BrowsePosition position;
BrowseFilters filters = new BrowseFilters() {BrowseFilter = browseFilter.item};
BrowseElement[] elements = s.Browse(itemId, filters, out position);
A: You do not state what precisely does not work. However, the main problems is probably in the fact that you are using BrowseFilter = browseFilter.item. The nodes in the tree are either leaves (sometimes called items), or branches. Your code only asks for the leafs, under the root of the tree. There may be no items under the root whatsoever, and you need to obtain the branches as well, and then dwelve deeper into the branches, recursively.
Start by changing your code to use BrowseFilter = browseFilter.all. This should give you all nodes under the root. Then, call the Browse recursively for the branches (just branches, not items) you receive, using the item ID of each branch as the starting point for the new browse.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27527763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use ClamAV Antivirus in AWS EC2 for scanning S3 Bucket object when any file uploaded to s3 bucket? I need to run ClamAV antivirus in EC2 instance that can help me to scan a virus for s3 bucket object when any object being uploaded to s3. Is their any blog or way that i can use?
A: You can use S3 VirusScan, which is a third-party open source tool.
Some of its features are:
*
*Uses ClamAV to scan newly added files on S3 buckets
*Updates ClamAV database every 3 hours automatically
*Scales EC2 instance workers to distribute workload
*Publishes a message to SNS in case of a finding
*Can optionally delete compromised files automatically
*Logs to CloudWatch Logs
A: If you want to implement the solution by yourself, you can use: https://aws.amazon.com/blogs/developer/virus-scan-s3-buckets-with-a-serverless-clamav-based-cdk-construct/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67635408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Working with jsoncpp to automate outputing json data
I am trying to automate the process of outputing the broad disciplines of UC Berkeley's majors. I have shortened the code and the JSON data to make the issue clearer. It is stored in JSON format and I am using the jsoncpp api to work with the data. The json data is the following:
{ "Berkeley": {
"1" :
{
"Broad Discipline": "Agriculture & Natural Resources",
"College/School**": "Letters & Science",
"Major": "ENVIRONMENTAL ECONOMICS & POLICY",
"Admit GPA Range": "3.63 - 3.94",
"Admit Rate": "0.342105263",
"Enroll GPA Range": "3.65 - 3.94",
"Yield Rate": "0.730769231",
"Admits": "26",
"Apps": "76",
"Enrolls": "19"
},
"2" :
{
"Broad Discipline": "Agriculture & Natural Resources",
"College/School**": "Natural Resources",
"Major": "CONSERVATION & RESOURCE STUDIES",
"Admit GPA Range": "3.32 - 3.88",
"Admit Rate": "0.333333333",
"Enroll GPA Range": "3.30 - 3.90",
"Yield Rate": "0.818181818",
"Admits": "22",
"Apps": "66",
"Enrolls": "18"
}
}}
Prior to this section of code, root is a json::Value and holds all the json data shown above.
// for loop through school's broad disciplines
for (int i = 0; i < 2; i++)
{
string element = "\"" + to_string(i + 1) + "\"";
string broadDiscipline = (root["Berkeley"][element]["Broad Discipline"]).asString();
cout << "Broad Discipline: " << broadDiscipline << endl;
}
I would expect it to output:
Broad Discipline: "Agriculture & Natural Resources"
Broad Discipline: "Agriculture & Natural Resources"
The actual result is:
Broad Discipline:
Broad Discipline:
I do not know what I am doing wrong. Also I can not find the documentation in jsoncpp for whatever function is called in a command like: root["Berkeley"].
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47690839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Queue messages not being moved to the poison queue I have a job that imports files into a system. Everytime a file is imported, we create a blob in azure and we send a message with instructions to a queue so that the data is persisted in SQL accordingly. We do this using azure-webjobs and azure-webjobssdk.
We experienced an issue in which after the messages failed more than 7 times, they didn't move to the poision queue as expected. The code is the following:
Program.cs
public class Program
{
static void Main()
{
//Set up DI
var module = new CustomModule();
var kernel = new StandardKernel(module);
//Configure JobHost
var storageConnectionString = AppSettingsHelper.Get("StorageConnectionString");
var config = new JobHostConfiguration(storageConnectionString) { JobActivator = new JobActivator(kernel), NameResolver = new QueueNameResolver() };
config.Queues.MaxDequeueCount = 7;
config.UseTimers();
//Pass configuration to JobJost
var host = new JobHost(config);
host.RunAndBlock();
}
}
Functions.cs
public class Functions
{
private readonly IMessageProcessor _fileImportQueueProcessor;
public Functions(IMessageProcessor fileImportQueueProcessor)
{
_fileImportQueueProcessor = fileImportQueueProcessor;
}
public async void FileImportQueue([QueueTrigger("%fileImportQueueKey%")] string item)
{
await _fileImportQueueProcessor.ProcessAsync(item);
}
}
_fileImportQueueProcessor.ProcessAsync(item) threw an exception and the message's dequeue count was properly increased and re-processed. However, it was never moved to the poison-queue. I attached a screenshot of the queues with the dequeue counts at over 50.
After multiple failures the webjob was stuck in a Pending Restart state and I was unable to either stop or start and I ended up deleting it completely. After running the webjob locally, I saw messages being processed (I assumed that the one with a dequeue count of over 7 should've been moved to the poison queue).
Any ideas on why this is happening and what can be done to have the desired behavior.
Thanks,
Update
Vivien's solution below worked.
Matthew has kind enough to do a PR that will address this. You can check out the PR here.
A: Fred,
The FileImportQueue method being an async void is the source of your problem.
Update it to return a Task:
public class Functions
{
private readonly IMessageProcessor _fileImportQueueProcessor;
public Functions(IMessageProcessor fileImportQueueProcessor)
{
_fileImportQueueProcessor = fileImportQueueProcessor;
}
public async Task FileImportQueue([QueueTrigger("%fileImportQueueKey%")] string item)
{
await _fileImportQueueProcessor.ProcessAsync(item);
}
}
The reason for the dequeue count to be over 50 is because when _fileImportQueueProcessor.ProcessAsync(item) threw an exception it will crash the whole process. Meaning the WebJobs SDK can't execute the next task that will move the message to the poison queue.
When the message is available again in the queue the SDK will process it again and so on.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41876364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to read long lines from child pocress' stdout in an efficient way? Note: This question has changed significantly since the first version, so some comments or answers could seem weird. Please, check the edit history if something seems weird.
I am launching a child process from a C# class library.
I am using Process.BeginOutputReadLine() to read the output/error in an asynchronous way. I thought it didn't work with very long lines, but the problem seems to be that it's not scalable. In my computer, a 128 kb line is processed instantly, a 512 kb line seems to take around one minute, 1 mb seems to take several minutes, and I've been around two hours waiting for a 10 mb line to be processed, and it was still working when I cancelled it.
It seems easy to fix reading directly from the StandardOutput and StandardError streams, but the data from those streams seems to be buffered. If I get wnough data from stdout to fill the buffer, and then some more data from stderr, I can't find a way to check if there's data pending in one of them, and if I try to read from stderr, it will hang forever.
Why is this happening, what am I doing wrong, and what's the right way to do this?
Some code samples to illustrate what I'm trying to achieve.
Program1:
// Writes a lot of data to stdout and stderr
static void Main(string[] args)
{
int numChars = 512 * 1024;
StringBuilder sb = new StringBuilder(numChars);
String s = "1234567890";
for (int i = 0; i < numChars; i++)
sb.Append(s[i % 10]);
int len = sb.Length;
Console.WriteLine(sb.ToString());
Console.Error.WriteLine(sb.ToString());
}
Program2:
// Calls Program1 and tries to read its output.
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder();
StringBuilder sbErr = new StringBuilder();
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardInput = false;
proc.StartInfo.Arguments = "";
proc.StartInfo.FileName = "program1.exe";
proc.ErrorDataReceived += (s, ee) => { if (ee.Data != null) sbErr.AppendLine(ee.Data); };
proc.OutputDataReceived += (s, ee) => { if (ee.Data != null) sb.AppendLine(ee.Data); };
proc.Start();
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
proc.WaitForExit();
}
Program1 has a constant that allows to set the size of data to generate, and Program2 launches Program1 and tries to read the data. I should expect the time to grow linearly with size, but it seems much worse than that.
A: I hope i understand your problem. the application hangs on Process.WaitForExit() because this is what Process.WaitForExit(): it waits for the process to exit.
you might want to call it in a new thread:
int your method that create the process:
Thread trd = new Thread(new ParameterizedThreadStart(Start));
trd.Start();
and add this method:
private void Start(object o)
{
((Process)o).WaitForExit();
// your code after process ended
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18715889",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MySQL doesn't always use a key with the same query I've got a table:
CREATE TABLE `myTable` (
`a` DECIMAL(8,3) NULL DEFAULT NULL,
`b` INT(11) NULL DEFAULT NULL,
`name` VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8_general_ci',
`id` INT(11) NOT NULL AUTO_INCREMENT,
`plus` VARCHAR(100) NOT NULL DEFAULT 't' COLLATE 'utf8_unicode_ci',
PRIMARY KEY (`id`),
INDEX `myKey` (`a`, `b`, `name`)
)
COLLATE='utf8_unicode_ci'
ENGINE=InnoDB
AUTO_INCREMENT=2416682;
I run a query:
SELECT * FROM myTable
order by a, b, name
limit 10000, 8 ;
It is very slow, takes about two seconds.
If I run an explain, it gives back this:
'id' => 1,
'select_type' => 'SIMPLE',
'table' => 'myTable ',
'partitions' => NULL,
'type' => 'ALL',
'possible_keys' => NULL,
'key' => NULL,
'key_len' => NULL,
'ref' => NULL,
'rows' => 1759263,
'filtered' => 100.00,
'Extra' => 'Using filesort',
Now if I set the limit to a lower value, it becomes very fast and explain says it uses myKey:
SELECT * FROM myTable
order by a, b, name
limit 1000, 8 ;
explain:
'id' => 1,
'select_type' => 'SIMPLE',
'table' => 'myTable',
'partitions' => NULL,
'type' => 'index',
'possible_keys' => NULL,
'key' => 'myKey',
'key_len' => '779',
'ref' => NULL,
'rows' => 1008,
'filtered' => 100.00,
'Extra' => NULL,
What can I do to make the select faster when the limit has high numbers?
I'm suprised the key is not used all the time, independent of the limit value. Is this normal?
MySQL version is 5.7.20-log.
Thanks
A: You can force the use of the index by doing the following:
FORCE INDEX (myKey)
FORCE INDEX mySQL ...where do I put it?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48083815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C# model for nested properties I need to make API request to CloudFlare to purge cache of individual files.
Can someone please guide how to represent the below as C# model class.
files: [
"http://www.example.com/css/styles.css",
{
"url": "http://www.example.com/cat_picture.jpg",
"headers": {
"Origin": "cloudflare.com",
"CF-IPCountry": "US",
"CF-Device-Type": "desktop"
}
}
]
A: var obj = new
{
files = new object[]
{
"http://www.example.com/css/styles.css",
new
{
url = "http://www.example.com/cat_picture.jpg",
headers = new Dictionary<string,string>
{
{ "Origin", "cloudflare.com" },
{ "CF-IPCountry","US" },
{ "CF-Device-Type", "desktop"}
}
}
}
};
The dictionary is there because of the awkward property names like CF-IPCountry which make it not possible to use an anonymous type.
To show it working:
var json = Newtonsoft.Json.JsonConvert.SerializeObject(obj, Formatting.Indented);
gives:
{
"files": [
"http://www.example.com/css/styles.css",
{
"url": "http://www.example.com/cat_picture.jpg",
"headers": {
"Origin": "cloudflare.com",
"CF-IPCountry": "US",
"CF-Device-Type": "desktop"
}
}
]
}
Edit; that's not quite right - the dictionary didn't work, but I don't have time to fix it.
A: Using classes (maybe you could use better class names then mine :) ):
class Root
{
[JsonProperty(PropertyName = "files")]
public List<object> Files { get; set; } = new List<object>();
}
class UrlContainer
{
[JsonProperty(PropertyName = "url")]
public string Url { get; set; }
[JsonProperty(PropertyName = "headers")]
public Headers Headers { get; set; }
}
class Headers
{
public string Origin { get; set; }
[JsonProperty(PropertyName = "CF-IPCountry")]
public string CfIpCountry { get; set; }
[JsonProperty(PropertyName = "CF-Device-Type")]
public string CfDeviceType { get; set; }
}
Usage
var root = new Root();
// Add a simple url string
root.Files.Add("http://www.example.com/css/styles.css");
var urlContainer = new UrlContainer() {
Url = "http://www.example.com/cat_picture.jpg",
Headers = new Headers()
{
Origin = "cloudflare.com",
CfIpCountry = "US",
CfDeviceType = "desktop"
}
};
// Adding url with headers
root.Files.Add(urlContainer);
string json = JsonConvert.SerializeObject(root);
Note: I'm using Newtonsoft.Json
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48228041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Pass value from internal to external function - Cannot save password I try to hash passwords with crypto and I cannot save them in the database.
I have node.js 4.2.3 express 4.13.3, and my database is PostgreSQL 9.1. The field is character varying (255) and is named pswrd.
This is my code:
var tobi = new User({
usrnm:'sp',
pswrd:'an'
});
module.exports = User;
function User(obj){
for(var key in obj){
this[key] = obj[key];
}
}
User.prototype.save = function (fn){
var user=this;
//EDIT, added this :
var psw ;
var salt = crypto.randomBytes(50).toString('base64');
crypto.pbkdf2(user.pswrd, salt, 10000, 150, 'sha512',function(err, derivedKey) {
//user.pswrd = derivedKey.toString('hex');
//EDIT, added this:
var justCrypted = derivedKey.toString('hex');
});
var query=client.query('INSERT INTO mytable(usrnm,pswrd)VALUES($1,$2) RETURNING mytable_id',[user.usrnm,user.pswrd], function(err, result) {
if(err) {console.log(err)}
else {
var newlyCreatedId = result.rows[0].mytable_id;
}
});
query.on("end", function (result) {console.log(result);client.end();});
}
tobi.save(function (err){
if (err)throw error;
console.log("yo");
})
To run this, I type node lib/user. I get no errors, but the password is not saved properly. The first value gets saved, the an, not the hashed one. What am I missing here?
EDIT
AshleyB answer is good, but, please help me understand how to pass data from an internal function (crypto.pbkdf2) to its external (User.prototype.save = function (fn)) , when the internal has predifined, fixed syntax (crypto.pbkdf2) , so I dont know if or how I can edit it.
How can I leave code as is and still pass the justCrypted back to psw (see edits on code) ? If it was a function that I wrote, I could use apply I guess, but, crypto.pbkdf2 is predifined and I dont know if can add stuff to it.
Thanks
A: The problem is with the scope, currently the query the altered user.pswrd is outside of the scope of the query so it falls back to the value assigned at the top.
By moving the query inside the 'crypto.pbkdf2'... block the user.pswrd value will work as intended. I've updated your code (and made the salt generation asynchronous, as you have used the async version of pbkdf2 anyway).
var tobi = new User({
usrnm: 'sp',
pswrd: 'an'
});
module.exports = User;
function User(obj) {
for (var key in obj) {
this[key] = obj[key];
}
}
User.prototype.save = function(fn) {
var user = this;
// Changed salt generation to async version
// See: https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback
crypto.randomBytes(50, function(ex, buf) {
if (ex) throw ex;
salt = buf.toString('base64');
// password, salt, iterations, keylen[, digest], callback
crypto.pbkdf2(user.pswrd, salt, 10000, 150, 'sha512', function(err, derivedKey) {
user.pswrd = derivedKey.toString('hex');
// Moved the query within the hash function
var query = client.query('INSERT INTO mytable(usrnm,pswrd)VALUES($1,$2) RETURNING mytable_id', [user.usrnm, user.pswrd], function(err, result) {
if (err) {
console.log(err)
} else {
var newlyCreatedId = result.rows[0].mytable_id;
}
});
query.on("end", function(result) {
console.log(result);
client.end();
});
});
});
}
tobi.save(function(err) {
if (err) throw error;
console.log("yo");
})
A: To answer your edit, I think you just need to understand that crypto.pbkdf2 is an asynchronous function that has a callback function as it's last parameter.
So within that callback function, you can access the psw variable, and you are able to do something like psw = newlyCreatedId. However, in your code the query is most likely called before the callback is. Therefore, you cannot make use of the psw variable in the query as your code stands.
What Ashley B did is to put your query function within the callback, to ensure that the query is not called until after the crypto function. You could also structure your code to use events, or promises if you didn't wish to nest the functions.
A: This is to answer your EDIT and to help you understand the passing of data between internal and external functions:
I've modified your code slightly to demonstrate the point. What you must understand is the scope and context of the calling function and how your function gets invoked. Crypto.pbkdf2 function accepts a function as a callback. This function is not part of the regular/sequential flow of control. The pbkdf2 function is an 'asynchronous' function - it returns immediately, but the processing can continue on background. This is why the code marked with '//Output 1: This will be undefined' below, will output 'undefined'. The main thread continues while pbkdf2 continues processing in background.
When the system is done processing, it calls the function you specified as the callback to let you know its done processing. Think of it as an SMS you send to someone vs. making a phone call. They reply back with an SMS whenever they get a chance.
However, when the system invokes the callback function, the "scope" or the "context" is different (think of it as an external entity calling your callback function). Therefore, it does not know what the scope/variables/functions in your context. In order to pass data between callback function and your objects, you can use the 'bind' method along with 'this' keyword:
var tobi = new User({
usrnm:'sp',
pswrd:'an'
});
module.exports = User;
function User(obj){
for(var key in obj){
this[key] = obj[key];
}
}
User.prototype.save = function (fn){
var user=this;
var psw ; //Change this to this.psw to pass changes back.
var crypto = require('crypto');
var salt = crypto.randomBytes(50).toString('base64');
crypto.pbkdf2(user.pswrd, salt, 10000, 150, 'sha512',function(err, derivedKey) {
var justCrypted = derivedKey.toString('hex');
console.log('Finished crypting' + justCrypted);
this.psw = justCrypted;
//When we use 'this' here, we set the value in the right scope/context.
//The var psw does not exist outside the scope of this function, so the
//external function will not know about it. By defining it in the current
// (this) scope, we ensure that external function is also aware of it.
this.externalFunction(justCrypted);
//Bind the callback function to the current context - it will remember
//this when the callback gets invoked. Think of it as explicitly specifying
//the 'context' of the call/method.
}.bind(this));
//Output 1: This will be undefined as callback has not returned yet.
console.log('New psw' + this.psw);
/*var query=client.query('INSERT INTO mytable(usrnm,pswrd)VALUES($1,$2) RETURNING mytable_id',[user.usrnm,user.pswrd], function(err, result) {
if(err) {console.log(err)}
else {
var newlyCreatedId = result.rows[0].mytable_id;
}
});
query.on("end", function (result) {console.log(result);client.end();}); */
}
User.prototype.externalFunction = function (someData) {
console.log('Data passed from an internal function');
console.log('New PSW: ' + this.psw);
console.log('Data from external function: ' + someData);
}
tobi.save(function (err){
if (err)throw error;
console.log("yo");
})
If I run the above, I see the following output. Note that data is now being passed between internal and external functions via the callback:
C:\temp\node\npm-test>node index.js
New pswundefined
3f9219ae14f9246622973724ace5cb66b190a4b5e86abf482fce5d7889e6aff870741d672ff78e7765fada25f150c70e5e61
c13b5bcdec634d03830668348b5a7d06cf75f426259dcf804241eb2f4362d10f1ebf23a1aecca28072a3f38fb8a39eba88c9
f055e9e7ccabafcd8caed25d8b26f3726022973175545f77e4024bcbcc657081ea5d1f2baf5e9080cbb20696135f2be8834c
Data passed from an internal function
New PSW: 3f9219ae14f9246622973724ace5cb66b190a4b5e86abf482fce5d7889e6aff870741d672ff78e7765fada25f15
0c70e5e61c13b5bcdec634d03830668348b5a7d06cf75f426259dcf804241eb2f4362d10f1ebf23a1aecca28072a3f38fb8a
39eba88c9f055e9e7ccabafcd8caed25d8b26f3726022973175545f77e4024bcbcc657081ea5d1f2baf5e9080cbb20696135
f2be8834c
Data from external function: 3f9219ae14f9246622973724ace5cb66b190a4b5e86abf482fce5d7889e6aff870741d6
72ff78e7765fada25f150c70e5e61c13b5bcdec634d03830668348b5a7d06cf75f426259dcf804241eb2f4362d10f1ebf23a
1aecca28072a3f38fb8a39eba88c9f055e9e7ccabafcd8caed25d8b26f3726022973175545f77e4024bcbcc657081ea5d1f2
baf5e9080cbb20696135f2be8834c
Have a look here to understand how bind works and here to understand the concept of this and context in javascript.
EDIT: In response to your latest, comment.
if you just wanted to pass the justCrypted from pbkdf2 to the var psw of User.prototype.save, you can use the synchronous version of the same method:
crypto.pbkdf2Sync(password, salt, iterations, keylen[, digest])
Your method will then look like:
User.prototype.save = function (fn){
var user=this;
var psw ;
var crypto = require('crypto');
var salt = crypto.randomBytes(50).toString('base64');
psw = crypto.pbkdf2Sync(user.pswrd, salt, 10000, 150, 'sha512');
var justCrypted = psw.toString('hex');
console.log(justCrypted);
....
....
}
The important difference here is that this is an synchronous method and the code will wait for crypto.pbkdf2Sync to finish returning a value before it moves to the next line, thus following a sequential flow.
Hope that helps.
EDIT 2: Here is a little diagram of how async works:
Unfortunately, you just can't do it the way you want without using an external function or a synchronous function.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34458576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: file upload and download with servlet I want to write an simple java servlet which receives file upload from a simple html page, does something with the file and sends back the manipulated file to the user.
The file upload event is handled by doPost method of a servlet on the server side. The requirements is that "Save as..." window needs to be appear immediately after the file is uploaded and processed on the server side and user can save the generated file to his/her computer.
File upload is handled by doPost and file download is handled by doGet method of a servlet. Is it possible to boundle these two events together somehow?
Can I receive byte content as a response of a file upload event? I upload file with ajax post and I can send back content to the browser and I can show this message on the client side.
Is it possible to write a clever java script code which receives binary content as a response of a post request and forces the web browser to pop up the "save as..." window for save the received bytes to a file?
Another solution could be
*
*file upload with ajax
*on the server side the new generated content is saved to a file into a temporary directory
*id or path of the file on the server is sent back to the client as a response
*client (java script) receives the id of the generated file and makes a new GET request immediately to a file download servlet
*file download servlet receives the id/path of the file and reads it from the temp folder and send i bact to the client web browser.
What is the best practice for this scenario?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36667600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the importance of collections framework in java for the programming of android and how to benefit from it How to use true data structure in android programming I need good learning resources and examples of applying data structure in certain functions
A: The collections framework was designed to meet several goals, such as −
*
*The framework had to be high-performance. The implementations for the fundamental collections (dynamic arrays, linked lists, trees, and hashtables) were to be highly efficient.
*The framework had to allow different types of collections to work in a similar manner and with a high degree of interoperability.
*The framework had to extend and/or adapt a collection easily.
A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following −
Interfaces − These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages, interfaces generally form a hierarchy.
Implementations, i.e., Classes − These are the concrete implementations of the collection interfaces. In essence, they are reusable data structures.
Algorithms − These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface.
For More Details you can find documents on ORACLE's Collection Documents
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48220411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-6"
} |
Q: Numpy array to Pandas data frame formatting Sorry if this has already been answered somewhere!
I am trying to format an array in numpy to a data frame in pandas, which I have done like so:
# array
a = [[' ' '0' 'A' 'T' 'G']
['0' 0 0 0 0]
['G' 0 -3 -3 5]
['G' 0 -3 -6 2]
['A' 0 5 0 -3]
['A' 0 5 2 -3]
['T' 0 0 10 5]
['G' 0 -3 5 15]]
# Output data frame using pandas
0 1 2 3 4
0 0 A T G
1 0 0 0 0 0
2 G 0 -3 -3 5
3 G 0 -3 -6 2
4 A 0 5 0 -3
5 A 0 5 2 -3
6 T 0 0 10 5
7 G 0 -3 5 15
# Output I want
0 A T G
0 0 0 0 0
G 0 -3 -3 5
G 0 -3 -6 2
A 0 5 0 -3
A 0 5 2 -3
T 0 0 10 5
G 0 -3 5 15
Any advice on how to do this would be appreciated! :)
A: Declare the first row to be column names and the first column to be row names:
df = pd.DataFrame(data=a[1:], columns=a[0]).set_index(' ')
df.index.name = None
# 0 A T G
#0 0 0 0 0
#G 0 -3 -3 5
#G 0 -3 -6 2
#A 0 5 0 -3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60534935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java - Saving StringTokenizer into arrays for further processing in other methods I've been coding Perl and Python a lot and this time I got an assignment to code in Java instead. So I'm not too familiar with handling data in Java.
My task involves having a input file where I need to check dependencies and then output those with transitive dependencies. Clearer ideas below:
Input File:
A: B C
B: C E
C: G
D: A
Output File:
A: B C E G
B: C E G
C: G
D: A B C E G
So far this is what I've got (separating the first and second token):
import java.util.StringTokenizer;
import java.io.*;
public class TestDependency {
public static void main(String[] args) {
try{
FileInputStream fstream = new FileInputStream("input-file");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null) {
StringTokenizer items = new StringTokenizer(strLine, ":");
System.out.println("I: " + items.nextToken().trim());
StringTokenizer depn = new StringTokenizer(items.nextToken().trim(), " ");
while(depn.hasMoreTokens()) {
System.out.println( "D: " + depn.nextToken().trim() );
}
}
} catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Any help appreciated. I can imagine Perl or Python to handle this easily. Just need to implement it in Java.
A: This is not very efficient memory-wise and requires good input but should run fine.
public class NodeParser {
// Map holding references to nodes
private Map<String, List<String>> nodeReferenceMap;
/**
* Parse file and create key/node array pairs
* @param inputFile
* @return
* @throws IOException
*/
public Map<String, List<String>> parseNodes(String inputFile) throws IOException {
// Reset list if reusing same object
nodeReferenceMap = new HashMap<String, List<String>>();
// Read file
FileInputStream fstream = new FileInputStream(inputFile);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
// Parse nodes into reference mapping
while((strLine = br.readLine()) != null) {
// Split key from nodes
String[] tokens = strLine.split(":");
String key = tokens[0].trim();
String[] nodes = tokens[1].trim().split(" ");
// Set nodes as an array list for key
nodeReferenceMap.put(key, Arrays.asList(nodes));
}
// Recursively build node mapping
Map<String, Set<String>> parsedNodeMap = new HashMap<String, Set<String>>();
for(Map.Entry<String, List<String>> entry : nodeReferenceMap.entrySet()) {
String key = entry.getKey();
List<String> nodes = entry.getValue();
// Create initial node set
Set<String> outSet = new HashSet<String>();
parsedNodeMap.put(key, outSet);
// Start recursive call
addNode(outSet, nodes);
}
// Sort keys
List<String> sortedKeys = new ArrayList<String>(parsedNodeMap.keySet());
Collections.sort(sortedKeys);
// Sort nodes
Map<String, List<String>> sortedParsedNodeMap = new LinkedHashMap<String, List<String>>();
for(String key : sortedKeys) {
List<String> sortedNodes = new ArrayList<String>(parsedNodeMap.get(key));
Collections.sort(sortedNodes);
sortedParsedNodeMap.put(key, sortedNodes);
}
// Return sorted key/node mapping
return sortedParsedNodeMap;
}
/**
* Recursively add nodes by referencing the previously generated list mapping
* @param outSet
* @param nodes
*/
private void addNode(Set<String> outSet, List<String> nodes) {
// Add each node to the set mapping
for(String node : nodes) {
outSet.add(node);
// Get referenced nodes
List<String> nodeList = nodeReferenceMap.get(node);
if(nodeList != null) {
// Create array list from abstract list for remove support
List<String> referencedNodes = new ArrayList<String>(nodeList);
// Remove already searched nodes to prevent infinite recursion
referencedNodes.removeAll(outSet);
// Recursively search more node paths
if(!referencedNodes.isEmpty()) {
addNode(outSet, referencedNodes);
}
}
}
}
}
Then, you can call this from your program like so:
public static void main(String[] args) {
try {
NodeParser nodeParser = new NodeParser();
Map<String, List<String>> nodeSet = nodeParser.parseNodes("./res/input.txt");
for(Map.Entry<String, List<String>> entry : nodeSet.entrySet()) {
String key = entry.getKey();
List<String> nodes = entry.getValue();
System.out.println(key + ": " + nodes);
}
} catch (IOException e){
System.err.println("Error: " + e.getMessage());
}
}
Also, the output is not sorted but that should be trivial.
A: String s = "A: B C D";
String i = s.split(":")[0];
String dep[] = s.split(":")[1].trim().split(" ");
System.out.println("i = "+i+", dep = "+Arrays.toString(dep));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7621478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: change size of kendo window when pressing the "minimize" button I'm trying to change the width of a kendoui window when the "minimize" button is pushed. I'm new to kendo and coulnd't find the help in their docs.
Here's the code I've got:
HTML: <div id="recon_cont_div">Some data here</div>
var thewindow = $("#recon_cont_div");
thewindow.kendoWindow({
actions: ["Minimize", "Maximize", "Pin", "Close"],
width: "100%",
height: "100%",
draggable: true,
resizable: true,
minimize: function(e) {
debugger;
thewindow.data("kendoWindow").setOptions({width: 250});
},
close: function(e) {
alert("window will close now")
},
title: "The window"
}).data("kendoWindow");
When the "minimize function" runs, the window does not resize...it does nothing?
Any help is appreciated. thanks.
A: The window wrapper is the one you need to change:
$("#dialog").kendoWindow({
actions: ["Minimize"],
minimize: function(e) {
$("#dialog").getKendoWindow().wrapper.css({
width: 200
});
}
});
Example: Window size change
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65100510",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Should "/users" and "/users/" point to the same (RESTful) resource? They do in this and probably any other website, but I'm not sure I understand why.
A popular analogy compares RESTful resources to files in the file system and filename users wouldn't point to the same object as filename users/ static web pages and in a static website users would point to users.html and users/ - to a different file - users/index.html.
A:
filename users wouldn't point to the same object as filename users/.
That is not true. In most filesystems, you cannot have a file named users and a directory named users in the same parent directory.
cd users and cd users/ have the same result.
A: Short answer: they may only identify the same resource if one redirects to the other.
URI's identify resources, but they do so differently depending on the response status code to a GET request in HTTP. If one returns a 3xx to the other, then the two URI's identify the same resource. If the two resources each return a 2xx code, then the URI's identify different resources. They may return the same response in reply to a GET request, but they are not therefore the same resource. The two resources may even map to the same handler to produce their reply, but they are not therefore the same resource. To quote Roy Fielding:
The resource is not the storage object. The resource is not a
mechanism that the server uses to handle the storage object. The
resource is a conceptual mapping -- the server receives the identifier
(which identifies the mapping) and applies it to its current mapping
implementation (usually a combination of collection-specific deep tree
traversal and/or hash tables) to find the currently responsible
handler implementation and the handler implementation then selects the
appropriate action+response based on the request content.
So, should /users and /users/ return the same response? No. If one does not redirect to the other, then they should return different responses. However, this is not itself a constraint of REST. It is a constraint, however, which makes networked systems more scalable: information that is duplicated in multiple resources can get out of sync (especially in the presence of caches, which are a constraint of REST) and lead to race conditions. See Pat Helland's Apostate's Opinion for a complete discussion.
Finally, clients may break when attempting to resolve references relative to the given URI. The URI spec makes it clear that resolving the relative reference Jerry/age against /users/ results in /users/Jerry/age, while resolving it against /users (no trailing slash) results in /Jerry/age. It's amazing how much client code has been written to detect and correct the latter to behave like the former (and not always successfully).
For any collection (which /users/ often is), I find it best to always emit /users/ in URI's, redirect /users to /users/ every time, and serve the final response from the /users/ resource: this keeps entities from getting out of sync and makes relative resolution a snap on any client.
A: There are some nuances on this, while "users" represent one resource while "users/" should represent a set of resources, or operations on all resources "users"... But there does not seem to exist a "standard" for this issue.
There is another discussion on this, take a look here: https://softwareengineering.stackexchange.com/questions/186959/trailing-slash-in-restful-api
A: Technically they are not the same. But a request for /users will probably cause a redirect to /users/ which makes them semantically equal.
In terms of JAX-RS @Path, they can both be used for the same path.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17948172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Make Cocoa application respond to simple AppleScript command I am trying to add a trivial AppleScript support to a Cocoa application. The application performs a check periodically and I just want to be able to tell it to perform it on demand.
I am trying to follow the SimpleScriptingVerbs Apple example.
I have subclassed NSScriptCommand as follows:
Header:
#import <Cocoa/Cocoa.h>
@interface rdrNotifierUpdateCommand : NSScriptCommand {
}
-(id)performDefaultImplementation;
@end
Implementation:
#import "rdrNotifierUpdateCommand.h"
#import "rdrNotifierAppDelegate.h"
@implementation rdrNotifierUpdateCommand
-(id)performDefaultImplementation {
NSLog(@"Works at last");
[((rdrNotifierAppDelegate *)[[NSApplication sharedApplication] delegate])
checkForNewItems]; // This just fires the timer
return nil;
}
@end
My .sdef file goes as follows (and the problem seems to be there, but I cannot find it):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dictionary SYSTEM "file://localhost/System/Library/DTDs/sdef.dtd">
<dictionary title="Dictionary" xmlns:xi="http://www.w3.org/2003/XInclude">
<xi:include href="file:///System/Library/ScriptingDefinitions/CocoaStandard.sdef" xpointer="xpointer(/dictionary/suite)"/>
<suite name="rdrNotifier Suite" code="rdrN" description="rdrNotifier application specific scripting facilities.">
<command name="do update" code="rdrNUpdt" description="Check for new items">
<cocoa class="rdrNotifierUpdateCommand"/>
</command>
</suite>
</dictionary>
The Info.plist is set up appropriately.
But, when I try to run the following script in AppleScript editor:
tell application "rdrNotifier"
do update
end tell
I receive an error about variable "update" not being defined.
I can open the dictionary for my application from AppleScript Editor (i.e. it is successfully registered).
Edit: Found a solution
The problem was indeed in the sdef file: I was not specifying that the application can reply to the command. My final definition goes as follows (Obj-C code unchanged):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dictionary SYSTEM "file://localhost/System/Library/DTDs/sdef.dtd">
<dictionary title="Dictionary" xmlns:xi="http://www.w3.org/2003/XInclude">
<!-- I have removed the standard suite as the application does not open, print... -->
<suite name="rdrNotifier Suite" code="rdrN" description="rdrNotifier application specific scripting facilities.">
<command name="do update" code="rdrNUpdt" description="Check for new items">
<cocoa class="rdrNotifierUpdateCommand"/>
</command>
<class name="application" code="Capp">
<cocoa class="NSApplication"/>
<responds-to name="do update">
<!-- Note you need to specify a method here,
although it is blank -->
<cocoa method=""/>
</responds-to>
</class>
</suite>
</dictionary>
Any improvements/tips/criticisms are still welcome.
A: Thanks for making the effort of adding applescript support to your app! Just a quick observation / criticism: When constructing terminology, by all means include spaces, but if that terminology takes the form of 'verb noun' (like 'do update') appleScripters will be irritated if the noun 'update' is not a properly modelled object, and if 'do' is not a proper command.
I would argue that 'do' is a poor choice for a command name, because it is very vague. What's wrong with just using 'update' as the command? (i.e. treat it as a verb).
This issue is treated in some detail by Apple's own technote 2106 (currently here), which you definitely should read and digest if you hope to please your AppleScripting user community.
Apple themselves are not beyond stupid terminology choices such as updatePodcast and updateAllPodcasts (in iTunes). These are stupid choices because (according to tn2106) they contain no spaces, and because the better choice would be to have a proper podcast class and then have an update command which could be used on an individual podcast, all podcasts, or a particular chosen set of podcasts.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6004312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Cython print() outputs before C printf(), even when placed afterwards I'm trying to pick up Cython.
import counter
cdef public void increment():
counter.increment()
cdef public int get():
return counter.get()
cdef public void say(int times):
counter.say(times)
This is the "glue code" I'm using to call functions from counter.py, a pure Python source code file. It's laid out like this:
count = 0
def increment():
global count
count += 1
def get():
global count
return count
def say(times):
global count
print(str(count) * times)
I have successfully compiled and run this program. The functions work fine. However, a very strange thing occured when I tested this program:
int main(int argc, char *argv[]) {
Py_Initialize();
// The following two lines add the current working directory
// to the environment variable `PYTHONPATH`. This allows us
// to import Python modules in this directory.
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append(\".\")");
PyInit_glue();
// Tests
for (int i = 0; i < 10; i++)
{
increment();
}
int x = get();
printf("Incremented %d times\n", x);
printf("The binary representation of the number 42 is");
say(3);
Py_Finalize();
return 0;
}
I would expect the program to produce this output:
Incremented 10 times
The binary representation of the number 42 is
101010
However, it prints this:
Incremented 10 times
101010
The binary representation of the number 42 is
But if I change the line
printf("The binary representation of the number 42 is");
to
printf("The binary representation of the number 42 is\n");
then the output is corrected.
This seems strange to me. I understand that if I want to print the output of a Python function, I might just as well return it to C and store it in a variable, and use C's printf() rather than the native Python print(). But I would be very interested to hear the reason this is happening. After all, the printf() statement is reached before the say() statement (I double checked this in gdb just to make sure). Thanks for reading.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42380030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to minimize amount of requests for Google API (places) autocomplete? I am using google API - places to autocomplete locations in AutoCompleteTextView. I did couple of tests maybe 20 searches and in my profile on google devs, it's written that I have made 200 API requests.
I understand that it is making request every time I type something or edit typed text. But is there any way how to reduce amount of calls to server?
One of ideas is to define threshold to 3 characters.
A: If you did not find a better solutions( I know it is very late, but I am doing something similar and I found my self in here.)
I think you can "cache" previous results, put them in ArrayList. And then in your adapter when performFiltering is called, start by checking the results you have in your Arraylist and if you receive a number of similar items, dont make a request to the API. I am not sure if it is clear but you can at least save a couple requests like that and for the user side, the autocomplete is always refreshing.
I hope it helps.
A: I think a better implementation to reduce the number of calls to the Places API would be to put in a delay of maybe 0.75 seconds after the last key-press. That would avoid confusion on the part of a user who after seeing autocomplete after 3 letters, sits and waits after typing his 5th.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27916517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Import csv in Rapidminer is not loading data properly Importing csv in Rapidminer is not loading data properly in the attributes/ columns and returns errors.
I have set the parameter values correctly in the 'Data Import Wizard'.
Column Separation is set to comma and when I check the "Use Quotes" parameter I see that there are too many "?" appear in the columns even though there is data in the actual csv file.
And when I do not check the “Use Quotes” option then I notice that the content of the columns are distributed across different columns, i.e., data does not appear in the correct column. It also gives error for the date column.
How to resolve this? Any suggestions please? I saw a lot of Rapidminer videos and read about it but did not help.
I am trying to import twitter conversations data which I exported from a 3rd party SaaS tool which extracts Twitter data for us.
Could someone help me soon please? Thanks, Geeta
A: It's virtually impossible to debug this without seeing the data.
The use quotes option requires that each field is surrounded by double quotes. Do not use this if your data does not contain these because the input process will import everything into the first field.
When you use comma as the delimiter, the observed behaviour is likely to be because there are additional commas contained in the data. This seems likely if the data is based on Twitter. This confuses the import because it is just looking for commas.
Generally, if you can get the input data changed, try to get it produced using a delimiter that cannot appear in the raw text data. Good examples would be | or tab. If you can get quotes around the fields, this will help because it allows delimiter characters to appear in the field.
Dates formats can be handled using the data format parameter but my advice is to import the date field as a polynominal and then convert it later to date using the Nominal to Date operator. This gives more control especially when the input data is not clean.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35472446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Print what is not in a join table I have a join table created from 2 other tables.
Say one model is called cat, another is called request, and the join table is called catrequest (this table would have cat_id and request_id)
How would I print all of the cats not intersected in the join table i.e. all of the cats NOT requested using rails. I saw some DB based answers, but I am looking for a rails solution using ruby code.
I get how to print a cat that belongs to a request i.e.:
<% @requests.each do |request| %>
<% request.cats.each do |cat| %>
<%= cat.name %>
<% end %>
but I don't understand how to do the reverse of this.
A: To get a list of cats that have never been requested you'd go with:
Cat.includes(:cat_requests).where(cat_requests: { id: nil })
# or, if `cat_requests` table does not have primary key (id):
Cat.includes(:cat_requests).where(cat_requests: { cat_id: nil })
The above assumes you have the corresponding association:
class Cat
has_many :cat_requests
end
A: It sounds like what you need is an outer join, and then to thin out the cats rows that don't have corresponding data for the requests? If that's the case, you might consider using Arel. It supports an outer join and can probably be used to get what you're looking for. Here is a link to a guide that has a lot of helpful information on Arel:
http://jpospisil.com/2014/06/16/the-definitive-guide-to-arel-the-sql-manager-for-ruby.html
Search the page for "The More the Merrier" section which is where joins are discussed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42353380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can I parallelise a Python function that returns None with Ray? I have a function that takes in a filename and creates a symlink in a target directory if that filename exists in the "source" directory:
def _symlink_photos(photo_name: str, photos_dir: Path, target_dir: Path) -> None:
"""
Given a string, checks if it exists in `photos_dir`,
then creates a symlink in `target_dir`
"""
photo_path: Path = photos_dir / photo_name
if photo_path.exists():
(target_dir / photo_name).symlink_to(photo_path)
This function is meant to be used to iterate over a somewhat big list of filenames (some 70k), like so:
def main() -> None:
"""
Given a list of photos, checks if they exist in the source directory,
and symlinks them into the target directory.
"""
for photo_name in tqdm(photo_list):
_symlink_photos(photo_name, photo_dir, target_dir)
The brute-force/for-loop approach is taking me too long (tqdm estimates over a day), so I was wondering how to parallelise this job. I knew I could use ray, but in order to use it I would need to write my code like this:
futures = [_symlink_photos.remote(photo_name, photo_dir, target_dir) for photo in photo_list]
result = ray.get(futures)
Yet this does not make sense to me, as my function does not return anything. Can I still use ray? Should I switch to something else, like joblib/threading?
Another alternative I was thinking of is to parallelise the "check if photo_name exists in the source dir" part with ray, i.e. to retrieve the list of photos that actually are in the target directory. Only then I would create the symlinks, hopefully taking less time...
A: You can use Ray in the way that you described. The ray.get call will simply return a list of None values, which you can ignore.
You can also look up ray.wait which can be used to wait for certain tasks to finish without actually retrieving the task outputs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71329511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: DirectX 2D grid I have been trying to get a 2D grid going. It's for a game map.
Unfortunately, the grid is not as it should be. And I cannot figure out why.
Does anyone have an idea?
Imports Microsoft.DirectX
Imports Microsoft.DirectX.Direct3D
Public Class clsIsometric
'==================================
' SETTINGS
'==================================
Private tile_size As New Point(64, 64) 'Size of one tile in pixels
Private map_size As New Point(25, 25) 'Amount of tiles in total
Private gDevice As Device
Private bufVertex As VertexBuffer
Private bufIndex As IndexBuffer
Private gVertices() As CustomVertex.TransformedColored
Private gIndices() As Integer
'==================================
' CONSTRUCTOR
'==================================
Public Sub New(vDevice As Device)
gDevice = vDevice
End Sub
Public Sub dispose()
bufVertex.Dispose()
bufIndex.Dispose()
bufVertex = Nothing
bufIndex = Nothing
End Sub
'==================================
' RENDERING
'==================================
Public Sub buildMap()
' Recreate buffers to fit the map size
ReDim gVertices((map_size.X + 1) * (map_size.Y + 1)) ' x+1 * y+1
ReDim gIndices(map_size.X * map_size.Y * 6) ' x * y * 6
Dim k As Integer
For cX = 0 To map_size.X - 1 'Rows
For cY = 0 To map_size.Y - 1 'Columns
'VERTEX
k = cX * map_size.X + cY
gVertices(k) = New CustomVertex.TransformedColored(cX * tile_size.X, cY * tile_size.Y, 0, 1, Color.Blue.ToArgb)
Next cY
Next cX
Dim vertexPerCol As Integer = map_size.Y + 1
k = 0
For ccX = 0 To map_size.X - 1
For ccY = 0 To map_size.Y - 1
gIndices(k) = ccX * vertexPerCol + ccY ' 0
gIndices(k + 1) = (ccX + 1) * vertexPerCol + (ccY + 1) ' 1
gIndices(k + 2) = (ccX + 1) * vertexPerCol + ccY ' 2
gIndices(k + 3) = ccX * vertexPerCol + ccY ' 3
gIndices(k + 4) = ccX * vertexPerCol + (ccY + 1) ' 4
gIndices(k + 5) = (ccX + 1) * vertexPerCol + (ccY + 1) ' 5
k += 6 'Each tile has 6 indices. Increase for next tile
Next
Next
bufVertex = New VertexBuffer(GetType(CustomVertex.TransformedColored), gVertices.Length, gDevice, Usage.Dynamic Or Usage.WriteOnly, CustomVertex.TransformedColored.Format, Pool.Default)
bufIndex = New IndexBuffer(GetType(Integer), gIndices.Length, gDevice, Usage.WriteOnly, Pool.Default)
End Sub
Public Sub render()
'RENDER THE MAP
bufVertex.SetData(gVertices, 0, LockFlags.ReadOnly)
bufIndex.SetData(gIndices, 0, LockFlags.None)
gDevice.VertexFormat = CustomVertex.TransformedColored.Format
gDevice.SetStreamSource(0, bufVertex, 0)
gDevice.Indices = bufIndex
gDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, gVertices.Length, 0, CInt(gIndices.Length / 3))
End Sub
End Class
This should output a perfect square grid of 25 by 25 tiles. But the wireframe looks like:
http://i43.tinypic.com/2whf51c.jpg
A: Your loop which build the vertices seems to end too early, because you have n+1 vertices each row/column. It fills the array only to the forelast column, which leads to a shift in the vertices.
For cX = 0 To map_size.X 'Rows
For cY = 0 To map_size.Y 'Columns
'VERTEX
k = cX * (map_size.X + 1) + cY
gVertices(k) = New CustomVertex.TransformedColored(cX * tile_size.X, cY * tile_size.Y, 0, 1, Color.Blue.ToArgb)
Next cY
Next cX
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18334043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What do you call an application that does not come with an installer? what you call a software that requires no installation only unzipping like eclipse where it has no installation only we have to unzip and also for uninstalling just delete the Workspace.
A: That's typically called a portable application.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15516326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MomentJs giving NaN result I'm trying to count the days from current date to a certain date, and i'm using momentJs to do it, the problem is that it's giving me NaN result, maybe because of the date formatting!
I'm fetching the end date from an api, and it's in this format "DD MM YYYY" "16/12/2023" but in moment I don't know how it's formatted, some help would be appreciated.
The code i'm using
const start = moment();
const end = moment(post.validTill);
const diff = end.diff(start, "days");
I just want to get the days from current date till the end date !
A: You can calculate the duration and request the value in days.
const
diffInDays = (start, end) => moment.duration(end.diff(start)).asDays(),
dateFormat = 'DD MM YYYY',
nextWeek = moment().add(1, 'weeks').format(dateFormat),
post = { validTill: nextWeek },
diff = diffInDays(moment(), moment(post.validTill, dateFormat));
console.log('Start of next week:', nextWeek);
console.log('Days until:', diff); // 6.xxx (days)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74213070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Asp Core 3 - How to allow nullable [FromBody] object in controller method Let's say I have a simple controller with one POST method that accepts an object from its body. However, the presence of this object should be optional in the HTTP request body. I tried to implement this behavior with the following code
public class User
{
public string Name { get; set; }
}
[ApiController]
[Route("[controller]")]
public class GreetingController : ControllerBase
{
[HttpPost]
public string SayHello([FromBody] User user = null)
{
return "Hello " + user?.Name;
}
}
If I make a request with an object in the body, everything works fine. But with this configuration, it is unable to make a POST request with empty body. If I create a request without Content-Type header (as there is actually no content), I get the following error:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.13",
"title": "Unsupported Media Type",
"status": 415,
"traceId": "|192e45d5-4bc216316f8d3966."
}
if the Content-Type header has value application/json then the response looks like this:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|192e45d6-4bc216316f8d3966.",
"errors": {
"": [
"A non-empty request body is required."
]
}
}
So, how to make the object optional in the request body? It is quite common problem and I am curious if there is a simple solution for that in ASP Core 3. I don't want to read the object from Request stream and deserialize it on my own.
A: Right now, the only way is via a global option, MvcOptions.AllowEmptyInputInBodyModelBinding. It defaults to false, so you just need to do:
services.AddControllers(o =>
{
o.AllowEmptyInputInBodyModelBinding = true;
});
A: There is now an easier way (since 5.0-preview7)
You can now achieve this per action method, by configuring a FromBodyAttribute property named EmptyBodyBehavior
Demonstration:
public IActionResult Post([FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] MyModel model)
Thanks to LouraQ's comment, which guided me towards the above answer on github
A: I'm not sure about your final intention, but if you don't want to choose the content-type, you can pass an empty json string.
At this time, the user is not empty, but the content of it's field's value is null, and the final result is the same. Maybe you You can try it.
Here is the debug process with the postman:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61387180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: String that contains $1 I have a script that scrolls through all the folders of unzipped files and get information of the contents.
The problem is in the name of files such as:
filename="SearchView$10.smali"
Because if I want to get the stats the $1 in the string disappears,and I get the following error:
subprocess.check_output("stat "+ filename,shell=True)
cannot open `SearchView0.smali' (No such file or directory)
How can I fix it?
A: Avoid shell=True, it leads to security issues. And it is also at the root of your problem, as the $1 is interpreted.
Do this instead:
subprocess.check_output(["stat", filename])
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34006394",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Only some Font Awesome glyphs display in WPF I am attempting to use Font Awesome in a WPF app. It half works. That is, some glyphs are picked up and show, others show a rectangle.
I'm following guides correctly, I think, but something is going wrong!
Here's a code snippet
<Window.Resources>
<FontFamily x:Key="FontAwesomeRegular">Fonts/Font Awesome 5 Free-Regular-400.otf#Font Awesome 5 Free Regular</FontFamily>
<FontFamily x:Key="FontAwesomeBrands">Fonts/Font Awesome 5 Brands-Regular-400.otf#Font Awesome 5 Brands Regular</FontFamily>
<FontFamily x:Key="FontAwesomeSolid">Fonts/Font Awesome 5 Free-Regular-400.otf#Font Awesome 5 Free Solid</FontFamily>
</Window.Resources>
<Grid>
<StackPanel Orientation="Vertical">
<TextBlock FontFamily="{StaticResource FontAwesomeSolid}" Text="" HorizontalAlignment="Left" Foreground="Red" Margin="0" TextWrapping="Wrap" VerticalAlignment="Center" FontSize="100"/>
<TextBlock FontFamily="{StaticResource FontAwesomeSolid}" Text="" HorizontalAlignment="Left" Foreground="Red" Margin="0" TextWrapping="Wrap" VerticalAlignment="Center" FontSize="100"/>
</StackPanel>
</Grid>
The fonts are installed in a Fonts directory
And Marked as Resource
And this is what it shows on the screen
You can see that the first icon xf15c; displays as expected but the second one xf15a; does not. Generally, most do not display.
Why?
A: If you open the .otf file, you can see the name of the font. This is what you need to use to the FontFamily resource, without the file extension.
Try the following code:
<FontFamily x:Key="Icons">pack://application:,,,/{YOUR PROJECT NAME};component/Fonts/#Font Awesome 5 Free Solid</FontFamily>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68897905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Backbone: event lost in re-render I have super-View who is in charge of rendering sub-Views. When I re-render the super-View all the events in the sub-Views are lost.
This is an example:
var SubView = Backbone.View.extend({
events: {
"click": "click"
},
click: function(){
console.log( "click!" );
},
render: function(){
this.$el.html( "click me" );
return this;
}
});
var Composer = Backbone.View.extend({
initialize: function(){
this.subView = new SubView();
},
render: function(){
this.$el.html( this.subView.render().el );
}
});
var composer = new Composer({el: $('#composer')});
composer.render();
When I click in the click me div the event is triggered. If I execute composer.render() again everything looks pretty the same but the click event is not triggered any more.
Check the working jsFiddle.
A: When you do this:
this.$el.html( this.subView.render().el );
You're effectively saying this:
this.$el.empty();
this.$el.append( this.subView.render().el );
and empty kills the events on everything inside this.$el:
To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.
So you lose the delegate call that binds events on this.subView and the SubView#render won't rebind them.
You need to slip a this.subView.delegateEvents() call into this.$el.html() but you need it to happen after the empty(). You could do it like this:
render: function(){
console.log( "Composer.render" );
this.$el.empty();
this.subView.delegateEvents();
this.$el.append( this.subView.render().el );
return this;
}
Demo: http://jsfiddle.net/ambiguous/57maA/1/
Or like this:
render: function(){
console.log( "Composer.render" );
this.$el.html( this.subView.render().el );
this.subView.delegateEvents();
return this;
}
Demo: http://jsfiddle.net/ambiguous/4qrRa/
Or you could remove and re-create the this.subView when rendering and sidestep the problem that way (but this might cause other problems...).
A: There's a simpler solution here that doesn't blow away the event registrations in the first place: jQuery.detach().
http://jsfiddle.net/ypG8U/1/
this.subView.render().$el.detach().appendTo( this.$el );
This variation is probably preferable for performance reasons though:
http://jsfiddle.net/ypG8U/2/
this.subView.$el.detach();
this.subView.render().$el.appendTo( this.$el );
// or
this.$el.append( this.subView.render().el );
Obviously this is a simplification that matches the example, where the sub view is the only content of the parent. If that was really the case, you could just re-render the sub view. If there were other content you could do something like:
var children = array[];
this.$el.children().detach();
children.push( subView.render().el );
// ...
this.$el.append( children );
or
_( this.subViews ).each( function ( subView ) {
subView.$el.detach();
} );
// ...
Also, in your original code, and repeated in @mu's answer, a DOM object is passed to jQuery.html(), but that method is only documented as accepting strings of HTML:
this.$el.html( this.subView.render().el );
Documented signature for jQuery.html():
.html( htmlString )
http://api.jquery.com/html/#html2
A: When using $(el).empty() it removes all the child elements in the selected element AND removes ALL the events (and data) that are bound to any (child) elements inside of the selected element (el).
To keep the events bound to the child elements, but still remove the child elements, use:
$(el).children().detach(); instead of $(.el).empty();
This will allow your view to rerender successfully with the events still bound and working.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12028835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "38"
} |
Q: DocuSign field mandatory/not mandatory per REST request I have a question: is it possible to choose a field to be mandatory or not mandatory per DocuSign REST request when we are forming an envelope?
In some cases I need field to be mandatory, in other - not (or even not usable)
A: Yes, document tabs have parameters required which can be set to true or false.
They also have the parameter readOnly which can also be set to true or false
The API reference has all the parameters in it
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72405612",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PhantomJS driver is not clicking on element in page, but no errors thrown Lately I have faced on issue with latest phantomjs driver and selenium in java development, so issue is this , we have a web site with list of users where every line of user have a delete button which have js action onclick(). What we are trying to do is to simply remove user, but it is not working on phantomjs, but works perfectly on chrome driver. Note that after clicking on delete button js alert is shown with yes/no, so it must be accepted also.
So here is our current code:
FindBy(css = ".glyphicon.glyphicon-trash.text-blue")
private WebElement customerRemoveButton;
.
.
.
.
Actions mouseAction = new Actions(driver);
mouseAction.moveToElement(customerRemoveButton);
mouseAction.click();
mouseAction.build().perform();
acceptAlert();
driver is properly initialised (cause obviously for chrome driver it is working perfectly), note that we already tried with clicking on button with JS Executor of webdriver and ofc with click().
So, when we execute it via chrome, user successfully removed, when via phantomjs test is passing without any single issue, but user is not removed.
A: Phantom JS something act weirdly. Check if you have a overlay of custom element over html element. if so try to click on custom element and not on actual html element.
if it doesn't work try to click using Javascript, that is you best bet.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41330007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to load a text file and store into data structure I have a 'text' file having content as follows:
012abc3cb7503bddef3ff59e0e52fd79.jpg 160.073318 18.588472 14.246923 8.054444 6.600504 6.261390 5.838249 4.447019 3.639888 3.357715 2.996645 2.910991 2.574769 2.527163 2.343448 2.264113 2.176161 2.088773 1.915582 1.902159 1.836033 1.725432 1.667595 1.633245 1.557424 1.542059 1.434280 1.430181 1.321047 1.302652 1.272890 1.261313 1.188892 1.138115 1.114376 1.070352 1.044311 1.025954 0.993622 0.988920 0.969866 0.933977 0.931669 0.913624 0.882856 0.876036 0.840088 0.822686 0.814072 0.787075 0.781157 0.778171 0.763771 0.748851 0.740975 0.708208 0.691589 0.688566 0.664124 0.659779 0.644820 0.623200 0.614799 0.607180 0.590615 0.578751 0.57...........
Each row represents an image (instance) with the first column being image name, remaining 240 columns being the feature-vector of the image.
How can I load this file in MATLAB and store the image names into 'names' variable and the 240 values into a 'histogram' variable?
A: You might be able to do it with textscan and repmat so you can avoid conversion from strings:
Nfeatures = 240;
fid = fopen('text.txt');
format = ['%s ' repmat('%f', [1 Nfeatures])];
imageFeatureCell = textscan(fid, format, 'CollectOutput', true);
fclose(fid);
A test on a file with 7 rows:
>> fileData
fileData =
{7x1 cell} [7x240 double]
Move into your desired variables:
names = fileData{1}; % names{1} contains first file name, etc.
histogram = fileData{2}; % histogram(1,:) contains first file's features
A: str = textread('tmp.txt','%s');
str = reshape(str,241,[]).';
names = str(:,1); %'// cell array of strings with image names
histogram = str2double(str(:,2:end)); %// each row refers to an image
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22234568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to display relation table in php? How to display relation table in php using oracle 11g with index format
this is my code:
$stid = oci_parse($conn, 'SELECT * FROM HOTEL');
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_BOTH)) != false) {
$id_hotel = $row['ID_HOTEL'];
$nama = $row['NAMA_HOTEL'];
$kamar = $row->KAMAR_ID['NAMA_KAMAR'];
$harga = $row['HARGA'];
$gambar = $row['GAMBAR'];
$lat = $row['LAT'];
$lng = $row['LNG'];
echo ("addMarker($lat, $lng, '<b><img src=http://localhost/hotel/common/uploads/hotel/$gambar width=85 height=85></img></b> <p><b>$nama</b> - <b>$kamar</b></p> <b>Rp.$harga</b> <p><a href=index.php?r=catalog%2Fview&id=$id_hotel class=button_maps>Lihat Hotel</a></p>');\n");
}
oci_free_statement($stid);
oci_close($conn);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40705873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Trouble scraping email information from a website I wish to get persmission to use the images on www.confluence.org for an art project but i need to do that by going to each individual member and asking for thier permission. There is about 10,000 people on the site.
I want to use BeautifulSoup to scrape the site for all the emails, so i can send one mass email instead of 1 email 10,000 times.
The problem however is the email is not written into the the html using text, but what i assume is a php file....located inside an img src.
<img src="visitormailimg.php?id=851" border="0" alt>
and an example of how this appears on the site is
I initially thought of the above email as a simple image that I could run through tesseract to get the text version of the email, but tesseract doesn't recognize it as an image object. I can click and download the php file as an image manually, but i cant figure out how to do something similar when scraping
Then i saved the webpage onto a folder on my desktop and opened the saved php file visitormailimg.php. Except when opened it i get "the file is not displayed in the editor because it is either binary or uses unsupported text encode" in vscode.
So i am at this stage unsure of how to proceed scraping ww.confluence.org website. Is it an image problem...is it a php problem? Any suggestions?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67936894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL Server get a JSON of all distinct columns grouped by a different column I have a table that looks like this:
What I want to do is convert it to a JSON that has all distinct years as keys, and an array of Make as value for each key. So based on the image, it would be something like this:
{ "1906": ["Reo", "Studebaker"], "1907": ["Auburn", "Cadillac", "Duryea", "Ford"], ... }
Could someone please help me on how to write a query to achieve this? I've never worked with converting SQL -> JSON before, and all I know is to use FOR JSON to convert a query to JSON.
A: I managed to solve this for whoever needs something similar. However, I think this way is inefficient and I would love for someone to tell me a better method.
I first ran this SQL query:
WITH CTE_Make AS
(
SELECT [Year], [Make]
FROM VehicleInformation
GROUP BY [Year], [Make]
)
SELECT
( SELECT
[Year] AS Year,
STRING_AGG([Make],',') AS MakeList
FOR JSON PATH,
WITHOUT_ARRAY_WRAPPER)
FROM CTE_Make
GROUP BY [Year]
This gave me the JSON in a different format from what I wanted. I stored this in a file "VehicleInformationInit.json", and loaded it in JS as variable vehicleInfoInitJsonFile and ran the following code in JavaScript:
var dict = {};
$.getJSON(vehicleInfoInitJsonFile, function
(result) {
result.forEach(x => {
var makeList = x.MakeList.split(',');
dict[x.Year] = makeList;
})
var newJSON = JSON.stringify(dict);
});
I simply copied the contents of newJSON by attaching a debugger into my required file. However, you can easily use fs and store it in a file if you want to.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73912930",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java Array of InnerClass throwing java.lang.NoSuchFieldError I am trying to brushup java after a long time.
Any help is much appreciated.
For demonstration I have Animal Class that has an array of innerclass of Organs.
public class Animal
{
String nameOfAnimal;
Organs [] vitalOrgans = new Organs[3];
public Animal()
{
}
public String getNameOfAnimal() {
return nameOfAnimal;
}
public void setNameOfAnimal(String nameOfAnimal) {
this.nameOfAnimal = nameOfAnimal;
}
@Override
public String toString() {
return "Animal{" + "nameOfAnimal=" + nameOfAnimal + "}";
}
class Organs{
String nameOfOrgan;
public String getNameOfOrgan() {
return nameOfOrgan;
}
public void setNameOfOrgan(String nameOfOrgan) {
this.nameOfOrgan = nameOfOrgan;
}
@Override
public String toString() {
return "Organs{" + "nameOfOrgan=" + nameOfOrgan + '}';
}
}
}
Now in driver file when I make call there is no syntactical error but I get "Exception in thread "main" java.lang.NoSuchFieldError: vitalOrgans"
Animal mamal = new Animal();
mamal.setNameOfAnimal("Chimp");
mamal.vitalOrgans[0].setNameOfOrgan("Heart");
System.out.println(mamal.vitalOrgans[0].getNameOfOrgan());
What would be the way to make this (or similar idea) to work.
Thanks.
A: Taking the relevant bit of code:
public class Animal
{
//...
Organs [] vitalOrgans = new Organs[3];
//...
}
Since your declaration of vitalOrgans was never given an access modifier (i.e. one of private, public, protected) it took on default access, which means only other classes in the same package can see it. Since your other block of code is not in the same package, it cannot see the field.
A minimally viable modification to just make it work would be to set the access to public:
public class Animal
{
//...
public Organs [] vitalOrgans = new Organs[3];
//...
}
While this works, it's not necessarily the best solution, as if you ever change how vitalOrgans is represented, or need to perform any validation, those edits would have to be done throughout the application. Thus, a better solution (and also, a major stylistic convention in Java for those exact reasons) is to make it (and all your fields, in fact) private and access via methods:
public class Animal {
private String nameOfAnimal;
private Organs[] vitalOrgans = new Organs[3];
//...
public Organs[] getVitalOrgans() {
return vitalOrgans;
}
//Alternative accessor that fetches only one organ.
public Organs getVitalOrgan(int index) {
if(index >= 0 && index < vitalOrgans.length)
return vitalOrgans[index];
else
return null;
}
public void setVitalOrgans(Organs[] vitalOrgans) {
this.vitalOrgans = vitalOrgans
}
//...
}
Your caller could then access Organs via either form of the get method (note, you probably want Organs to be public):
Animal.Organs futureMammalHeart = mamal.getVitalOrgan(0); //Animal.Organs due to Organs being an inner class.
if(futureMammalHeart != null) //Demonstration of null check. Safety first!
futureMammalHeart.setNameOfOrgan("Heart");
Animal.Organs[] mammalianVitalOrgans = mamal.getVitalOrgans();
if(mammalianVitalOrgans != null) //Just in case...
System.out.println(mamal.mammalianVitalOrgans[0].getNameOfOrgan());
Also, as Ari mentioned in his answer, don't forget to initialize the organs in your array, otherwise you will get a NullPointerException!
A: You would need to initialize the vitalOrgrans with new Organs(). Like:
public Animal() {
for (int i = 0; i < vitalOrgans.length; i++) {
vitalOrgans[i] = new Organs();
}
}
Because when you say :
Organs[] vitalOrgans = new Organs[3];
You are creating an array of 3 null Organs. Hence the null pointer exception, when accessing "vitalOrgans[i].".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48931629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Mahout evaluation - unable to recommend in x cases I am trying to evaluate the recommender algorithms on my data set which probably is sparse, and I have only 341 items for around 20 000 users. I just want to evaluate all of the similarity algorithms. I tried almost all user-based recommendations, and for all of them I am getting this INFO from the evaluator, no matter which one, (AverageAbsoluteDifferenceRecommenderEvaluator or Root mean-square scoring Evaluator) which is Unable to recommend in xXXX cases. However the final output still have some result. Here is the output of my evaluator:
3/06/17 14:11:35 INFO eval.AbstractDifferenceRecommenderEvaluator: Beginning evaluation using 0.7 of org.apache.mahout.cf.taste.impl.model.jdbc.PostgreSQLJDBCDataModel@44303e7b
13/06/17 14:15:17 INFO model.GenericDataModel: Processed 10000 users
13/06/17 14:15:17 INFO model.GenericDataModel: Processed 20000 users
13/06/17 14:15:17 INFO model.GenericDataModel: Processed 20530 users
13/06/17 14:15:17 INFO eval.AbstractDifferenceRecommenderEvaluator: Beginning evaluation of 11240 users
13/06/17 14:15:17 INFO eval.AbstractDifferenceRecommenderEvaluator: Starting timing of 11240 tasks in 4 threads
13/06/17 14:15:17 INFO eval.AbstractDifferenceRecommenderEvaluator: Average time per recommendation: 4ms
13/06/17 14:15:17 INFO eval.AbstractDifferenceRecommenderEvaluator: Approximate memory used: 57MB / 101MB
13/06/17 14:15:17 INFO eval.AbstractDifferenceRecommenderEvaluator: Unable to recommend in 3 cases
13/06/17 14:15:19 INFO eval.AbstractDifferenceRecommenderEvaluator: Average time per recommendation: 4ms
13/06/17 14:15:19 INFO eval.AbstractDifferenceRecommenderEvaluator: Approximate memory used: 48MB / 99MB
13/06/17 14:15:19 INFO eval.AbstractDifferenceRecommenderEvaluator: Unable to recommend in 882 cases
13/06/17 14:15:20 INFO eval.AbstractDifferenceRecommenderEvaluator: Average time per recommendation: 5ms
13/06/17 14:15:20 INFO eval.AbstractDifferenceRecommenderEvaluator: Approximate memory used: 33MB / 109MB
13/06/17 14:15:20 INFO eval.AbstractDifferenceRecommenderEvaluator: Unable to recommend in 1787 cases
13/06/17 14:15:22 INFO eval.AbstractDifferenceRecommenderEvaluator: Average time per recommendation: 5ms
13/06/17 14:15:22 INFO eval.AbstractDifferenceRecommenderEvaluator: Approximate memory used: 41MB / 86MB
13/06/17 14:15:22 INFO eval.AbstractDifferenceRecommenderEvaluator: Unable to recommend in 2687 cases
13/06/17 14:15:23 INFO eval.AbstractDifferenceRecommenderEvaluator: Average time per recommendation: 5ms
13/06/17 14:15:23 INFO eval.AbstractDifferenceRecommenderEvaluator: Approximate memory used: 38MB / 98MB
13/06/17 14:15:23 INFO eval.AbstractDifferenceRecommenderEvaluator: Unable to recommend in 3569 cases
13/06/17 14:15:24 INFO eval.AbstractDifferenceRecommenderEvaluator: Average time per recommendation: 5ms
13/06/17 14:15:24 INFO eval.AbstractDifferenceRecommenderEvaluator: Approximate memory used: 28MB / 93MB
13/06/17 14:15:24 INFO eval.AbstractDifferenceRecommenderEvaluator: Unable to recommend in 4465 cases
13/06/17 14:15:26 INFO eval.AbstractDifferenceRecommenderEvaluator: Average time per recommendation: 5ms
13/06/17 14:15:26 INFO eval.AbstractDifferenceRecommenderEvaluator: Approximate memory used: 41MB / 88MB
13/06/17 14:15:26 INFO eval.AbstractDifferenceRecommenderEvaluator: Unable to recommend in 5420 cases
13/06/17 14:15:27 INFO eval.AbstractDifferenceRecommenderEvaluator: Average time per recommendation: 5ms
13/06/17 14:15:27 INFO eval.AbstractDifferenceRecommenderEvaluator: Approximate memory used: 45MB / 90MB
13/06/17 14:15:27 INFO eval.AbstractDifferenceRecommenderEvaluator: Unable to recommend in 6317 cases
13/06/17 14:15:28 INFO eval.AbstractDifferenceRecommenderEvaluator: Average time per recommendation: 5ms
13/06/17 14:15:28 INFO eval.AbstractDifferenceRecommenderEvaluator: Approximate memory used: 46MB / 103MB
13/06/17 14:15:28 INFO eval.AbstractDifferenceRecommenderEvaluator: Unable to recommend in 7220 cases
13/06/17 14:15:30 INFO eval.AbstractDifferenceRecommenderEvaluator: Average time per recommendation: 5ms
13/06/17 14:15:30 INFO eval.AbstractDifferenceRecommenderEvaluator: Approximate memory used: 72MB / 102MB
13/06/17 14:15:30 INFO eval.AbstractDifferenceRecommenderEvaluator: Unable to recommend in 8145 cases
13/06/17 14:15:31 INFO eval.AbstractDifferenceRecommenderEvaluator: Average time per recommendation: 5ms
13/06/17 14:15:31 INFO eval.AbstractDifferenceRecommenderEvaluator: Approximate memory used: 67MB / 99MB
13/06/17 14:15:31 INFO eval.AbstractDifferenceRecommenderEvaluator: Unable to recommend in 9084 cases
13/06/17 14:15:33 INFO eval.AbstractDifferenceRecommenderEvaluator: Average time per recommendation: 5ms
13/06/17 14:15:33 INFO eval.AbstractDifferenceRecommenderEvaluator: Approximate memory used: 31MB / 83MB
13/06/17 14:15:33 INFO eval.AbstractDifferenceRecommenderEvaluator: Unable to recommend in 9982 cases
13/06/17 14:15:33 INFO eval.AbstractDifferenceRecommenderEvaluator: Evaluation result: 1.643042326271061
I don't understand the numbers, why they show so many times, and is this unable to recommend in xxx cases bigger then 20% of all my data? Does it mean that for one user it can't recommend in 3 cases, and for other in 9892?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17148591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to open Telegram desktop source in Qt? I'm trying to open the source of Telegram (desktop version) in Qt but I can't find any .pro file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45909301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Alloc - add as accessoryView - release: does it leak? Does this leak memory? This code is executed in cellForRowAtIndexPath: outside the cell creation block (so each time the table cell is updated).
MyView *myView = [[MyView alloc] init];
// ... configuration code
cell.accessoryView = myView;
[myView release];
Or in other words, will the UITableViewCell release the object in its accessoryView when a new object gets assigned to it?
Thanks.
A: Yes, the cell will release the accessory view and you do not have a leak in the example.
A: The property accessoryView of a UITableViewCell is a retain type, in common with many view properties in the kit. Check the Apple documentation for UITableViewCell to convince yourself of this. Therefore there will be no leak in your example - the retain count has been correctly managed. You've also correctly released after setting the accessory view, on account of your alloc call.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7570783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to solve TypeError: The DTypes and do not have a common DType? I have a dataframe which I want to plot using stacked chart for all columns
date company1 company2 company3
0 2015-09-30 0.1729652326951854 5.10825384154414 5.28662587089132
1 2015-12-31 0.33177760613144625 5.341402694012068 7.757158664745589
2 2016-03-31 0.45978954321258786 0.601947573082123 14.280848001613228
3 2016-06-30 0.08512062667254938 0.26628902842588686 9.342680735839917
4 2016-09-30 0.07052086314882283 10.032170981625246 8.964205526466738
5 2016-12-31 0.06143896111634454 10.06041088786925 8.3778390910586
6 2017-03-31 0.03742645731812014 7.156923204928792 6.793302965780993
7 2017-06-30 0.1032395546373315 5.438273795868809 4.857798532828831
I did the following
df['date'] = pd.to_datetime(df.date)
fig, ax = plt.subplots(figsize=(9,6), dpi= 80)
ax = exchanges_disagg_data.plot.area(legend=None, figsize=(9,6), alpha=0.9)
and i get the following error message.
TypeError: The DTypes <class 'numpy.dtype[uint8]'> and <class 'numpy.dtype[datetime64]'> do not have a common DType. For example they cannot be stored in a single array unless the dtype is `object`.
Then i tried
df.date= df['date'].dt.strftime('%Y-%m-%d')
and i get the plot but instead of date time x ticks, i just get index numbers...
This is very frustrating, would anyone know how to solve this? Many thanks in advance.
A: Note: np.nan is float type and pd.NaT is of datetime null type. Problem with your code is that null values have been filled with np.nan
I got the same error while doing the following thing....
df['date'] = np.where((df['date2'].notnull()) & (df['date3'].notnull()),df['date2']-df['date3'],np.nan)
problem here is date difference of date2 and date3 is of datetime type but the type of "np.nan" is float/int. For saving it to df['date'], datatype should be same. In datetime type the null date is "pd.NaT". So when I replace the above code with below. It worked for me. You can try the same..
df['date'] = np.where((df['date2'].notnull()) & (df['date3'].notnull()),df['date2']-df['date3'],pd.NaT)
So you can replace the nulls present in your data with pd.NaT instead of np.nan
you can use below thing as well...
df['date'].replace(np.NaN, pd.NaT)
or
df['date'].fillna(pd.NaT)
Hope it is helpful for you :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71611309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android CheckedTextView - Changing checked status on click I have a listview that needs to be multiple choice (i.e each list item has a checkbox which can be checked / unchecked)
The list view is in a tabhost and is the content for teh first tab.
My set up is like so:
My tab is set up with:
TabSpec tab = tabHost.newTabSpec("Services");
tabHost.addTab(tabHost.newTabSpec("tab_test1").setIndicator("Services").setContent(new Intent(this, ServiceList.class)));
When the tab is clicked new activity ServiceList is started
ServiceList is defined as such:
public class ServiceList extends ListActivity{
private EscarApplication application;
ListView listView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.service_list);
ServiceList.this.application = (EscarApplication) this.getApplication();
final ListView listView = getListView();
}
protected void onListItemClick(ListView l, View v, int position, long id) {
String.valueOf(id);
Long.toString(id);
((CheckedTextView) v).setChecked(true);
super.onListItemClick(l, v, position, id);
}
@Override
public void onStart() {
super.onStart();
//Generate and display the List of visits for this day by calling the AsyncTask
GenerateServiceList services = new GenerateServiceList();
int id = ServiceList.this.application.getVisitId();
services.execute(id);
listView = getListView();
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
//The AsyncTask to generate a list
private class GenerateServiceList extends AsyncTask<Integer, String, Cursor> {
// can use UI thread here
protected void onPreExecute() {
}
// automatically done on worker thread (separate from UI thread)
protected Cursor doInBackground(Integer...params) {
int client_id = params[0];
ServiceList.this.application.getServicesHelper().open();
Cursor cur = ServiceList.this.application.getServicesHelper().getPotentialVisitServices(client_id);
return cur;
}
// can use UI thread here
protected void onPostExecute(Cursor cur){
startManagingCursor(cur);
// the desired columns to be bound
String[] columns = new String[] {ServicesAdapter.KEY_SERVICE};
// the XML defined views which the data will be bound to
int[] to = new int[] {R.id.display_service};
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(ServiceList.this, R.layout.service_list_element, cur, columns, to);
// set this adapter as your ListActivity's adapter
ServiceList.this.setListAdapter(mAdapter);
ServiceList.this.application.getServicesHelper().close();
}
}
}
So, everything works ok until I click on my list item to change the checkbox state.
The part of teh code set to handle click events is causing me problems:
protected void onListItemClick(ListView l, View v, int position, long id) {
String.valueOf(id);
Long.toString(id);
((CheckedTextView) v).setChecked(true);
super.onListItemClick(l, v, position, id);
}
My understanding is that the View v passed to the onListItemClick method reperesents my list element, so I am trying to cast v as a CheckedTextView and set teh checked value to true, however this just causes my app to crash. Am I missing something simple here, or is there an easier way to do this?
Thanks
Kevin
A: Have you debugged it to check if 'v' is null? If so, you need to use a layoutInflator to retrieve the view.
if(v == null)
{
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.service_list, null);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3548406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unable to get data from foreign table in mongodb nodejs using $lookup I have just started working on mongodb and I want to get data from foreign table(User) and table(Connection) by performing join but foreign table data is always an empty array
User Schema:
[
{key: 1, name: "a"},
{key: 2, name: "b"},
{key: 1, name: "c"},
{key: 2, name: "d"},
]
Connection schema:
[
{initiator_id: 1, target_id: 2}
{initiator_id: 3, target_id: 4}
]
And this is my join code
const pipeline = [
{
$match: {
initiator_id: { $eq: user_id },
},
},
{
$lookup: {
from: "user",
localField: "initiator_id",
foreignField: "key",
as: "user",
},
},
];
mongoose.model("connection").aggregate(pipeline).then((res) => {
console.log(res);
});
And the console.log response is an array in which the user field is always an empty array
[
{
connection_id: 'some_id'
initiator_id: 1
target_id: 2,
user: []//this is where I'm expecting data from User table but it is always empty
}
]
initiator_id, target_id, and key .... all are type Number
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67244430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Message: cache_dir must be a directory Hello people I have some problems with Zend Framework. I first got the following message:
Message: Could not determine temp directory, please specify a cache_dir manually.
I searched google and found this post: Zend Framework : Could not determine temp directory, please specify a cache_dir manually
I read it and now when I fill in the form I get the following error:
(Everywhere where I put .. in the error means the domain.)Message: cache_dir must be a directory
- #0 /home/daan/domains/../library/Zend/Cache/Backend/File.php(154): Zend_Cache::throwException('cache_dir must ...')
- #1 /home/daan/domains/../library/Zend/Cache/Backend/File.php(121): Zend_Cache_Backend_File->setCacheDir('/domains/daan.h...')
- #2 /home/daan/domains/../library/Zend/Cache.php(153): Zend_Cache_Backend_File->__construct(Array)
- #3 /home/daan/domains/../library/Zend/Cache.php(94): Zend_Cache::_makeBackend('File', Array, false, false)
- #4 /home/daan/domains/../library/Zend/Locale/Data.php(307): Zend_Cache::factory('Core', 'File', Array, Array)
- #5 /home/daan/domains/../library/Zend/Locale/Format.php(796): Zend_Locale_Data::getList('nl_NL', 'day')
- #6 /home/daan/domains/../library/Zend/Locale/Format.php(1106): Zend_Locale_Format::_parseDate('16-02-2013', Array)
- #7 /home/daan/domains/../library/Zend/Date.php(4763): Zend_Locale_Format::getDate('16-02-2013', Array)
- #8 /home/daan/domains/../library/Zend/Validate/Date.php(175): Zend_Date::isDate('16-02-2013', 'MM-DD-YYYY', NULL)
- #9 /home/daan/domains/../library/Zend/Form/Element.php(1391): Zend_Validate_Date->isValid('16-02-2013', Array)
- #10 /home/daan/domains/../library/Zend/Form.php(2135): Zend_Form_Element->isValid('16-02-2013', Array)
- #11/home/daan/domains/../application/controllers/BugController.php(27): Zend_Form->isValid(Array)
- #12 /home/daan/domains/../library/Zend/Controller/Action.php(513): BugController->submitAction()
- #13 /home/daan/domains/../library/Zend/Controller/Dispatcher/Standard.php(289): Zend_Controller_Action->dispatch('submitAction')
- #14 /home/daan/domains/../library/Zend/Controller/Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
- #15 /home/daan/domains/../library/Zend/Application/Bootstrap/Bootstrap.php(97): Zend_Controller_Front->dispatch()
- #16 /home/daan/domains/../library/Zend/Application.php(366): Zend_Application_Bootstrap_Bootstrap->run()
- #17 /home/daan/domains/../public_html/index.php(26): Zend_Application->run()
- #18 {main}
Application.ini:
resources.cachemanager.configFiles.frontend.name = File
resources.cachemanager.configFiles.frontend.customFrontendNaming = false
resources.cachemanager.configFiles.frontend.options.lifetime = false
resources.cachemanager.configFiles.frontend.options.automatic_serialization = true
resources.cachemanager.configFiles.backend.name = File
resources.cachemanager.configFiles.backend.customBackendNaming = false
resources.cachemanager.configFiles.backend.options.cache_dir = APPLICATION_PATH "/../tmp"
resources.cachemanager.configFiles.frontendBackendAutoload = false
Initcache:
protected function _initCaching() {
$frontend = array(
'lifetime' => $time,
'automatic_serialization' => true
);
$backend = array(
'cache_dir' => sys_get_temp_dir(),
);
$cache = Zend_Cache::factory('core', 'File', $frontend, $backend);
Zend_Registry::set('cache', $cache);
}
Folder Structure:
.htpasswd
application
awstats
library
logs
public_ftp
public_html
tmp
A: cache_dir must be a directory :
This problem came generally when you move your code to another host or server . There are mainly two solution for this problem
1 - Make sure your cache directory is writable or you can make writable to var folder of magento
but sometimes this situation does not work so here is the alternate solution. Go to this location lib/Zend/Cache/Backend/
and open file.php file you’ll see the code something like this
protected $_options = array(
'cache_dir' => null,
'file_locking' => true,
'read_control' => true,
'read_control_type' => 'crc32',
'hashed_directory_level' => 0,
'hashed_directory_umask' => 0700,
'file_name_prefix' => 'zend_cache',
'cache_file_umask' => 0600,
'metadatas_array_max_size' => 100
);
change this code as below
protected $_options = array(
'cache_dir' => '/var/www/html/webkul/magento/tmp',
'file_locking' => true,
'read_control' => true,
'read_control_type' => 'crc32',
'hashed_directory_level' => 0,
'hashed_directory_umask' => 0700,
'file_name_prefix' => 'zend_cache',
'cache_file_umask' => 0600,
'metadatas_array_max_size' => 100
);
assign path of cache_dir as per your configuration .
A: May be Zend is not able to find your cache directory. Try to se this in Bootstrap.php like this
protected function _initCache() {
$frontend = array(
'lifetime' => $time,
'automatic_serialization' => true
);
$backend = array(
'cache_dir' => sys_get_temp_dir(), /**automatically detects**/
);
$cache = Zend_Cache::factory('core', 'File', $frontend, $backend);
Zend_Registry::set('cache', $cache);
}
A: Remove the _initCaching function from your bootstrap, you shouldn't have this and the application.ini entries as they are both trying to setup the same thing (but using different cache locations).
Your cache dir is set to APPLICATION_PATH "/../tmp" - i.e. a folder called 'tmp' at the root of your application (NOT in the application folder). Are you 100% sure that your tmp folder exists at this location? If so, you could try changing the application.ini configuration to use a full path instead:
resources.cachemanager.configFiles.backend.options.cache_dir = "/home/daan/domains/whatever/tmp"
just to see if that fixes the problem.
If you still can't get it working please post more information about the file structure of your application.
A: The answer of this question is that open File.php file and change the path of the tmp folder.
This issue mostly comes when you tranfer your site from one server to another. When you transfer the site then the path of the tmp folder doesn't changed to the the new one. So edit the file.php and change the path of the tmp folder.
A: magento root
Creating "tmp" file in the magento directory solved this error for me.
I was able to access admin easily
A: assign full path for your cache directory. For example,
'cache_dir' => '/var/www/html/var/cache1',
A: Change path in /install/config/, edit file vfs.php and put new path name.
A: One of the causes for this problem in CentOS/RedHat could be Selinux.
I got rid of this issue by just disabling Selinux
Edit the /etc/selinux/config file and set the SELINUX to disabled.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16031456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: SailsJS: delete parameters from URL before passing to blueprint We are building an application which uses SailsJS for backend and ExtJS for frontend. ExtJS automaitcally appends these parameters to every AJAX request coming from its grid:
_dc=1421519546371&page=1&start=0&limit=25
I need to remove these parameters on the Sails side before they are passed to the blueprint actions, so that I can take advantage of the blueprint REST API. Where would be the best place to remove these parameters? I can think of my NGINX reverse proxy as one option, but I am sure there is a better place within Sails.
A: In sails the easiest place would be to remove them with a policy.
RemoveParams.js
module.exports = function(req, res, next) {
if(req.query._dc) delete req.query._dc
// ect ....
next();
};
Alternate method using undocumented req.options. I have not used this, but it would seem to work and was recommended in the comments.
module.exports = function(req, res, next) {
req.options.values.blacklist = ['_dc']
// or req.options.values.blacklist.push('_dc') ??
next();
};
If you so choose you could also add your own middleware to replace / remove them as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28002923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Object Code vs. Machine Code Machine code is the Processor Specific Binary Representation of the Instructions that a program is translated into; lowest level instructions from the processor architecture's instruction set.
The operating system is the agent responsible for passing the (((Binary))) instructions to the processor through the hardware architecture.
the most abstract translation made by translators is, therefore supposed to be the Binary instructions.
The assembler takes in the Assembly code that has instructions with one-to-one correspondence to the processor's architecture instructions ( that have binary representations ), and yields the Object Code.
The yield of the linker is nothing more linked Object Files, no translation happens at this stage. The load module is Object Code. I.e.: The loaded code by OS to RAM is the Object Code (which is not the binary representation of the instructions).
Question 1: Are the binary representations saved in the OS?
Question 2: What's the translator of the object code into binary representations? is it the OS (or the language runtime installed on it, if any)? Do all languages implementations have an installed runtime to do this if it's the runtime's job? Does an earlier agent than the OS do this job?
Question 3: Is the loaded code to the RAM really the object code not the binary representation? or does the loader translate the object code to its binary representation.
A: You are misunderstanding object files. Start by taking a look at this question:
What does an object file contain?
Object files do contain binary machine language instructions for the target platform, so there is no "translator" of any kind between the binary code contained in them and what is executed on the target CPU.
I think your confusion stems from the fact that object files also contain other information, such as symbol tables and constants. It is the linker's job to collect all of this information and package it into an executable.
Side Note: This answer is assuming a C/C++ perspective. Languages like Java that execute on a virtual machine have other layers in between compiling and execution.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24681357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: list in reverse order python How should I fix this code in order to get a list that is in the reverse order of sequence s?
def reverse(s):
"""Return a list that is the reverse of sequence s.
>>> reverse([1,2,3])
[3, 2, 1]
"""
rs = []
for element in s:
rs = s + rs
return rs
A: I'd actually do something like this (I'm assuming you cant use reversed()). This uses slicing notation to reverse a list.
def reverse(s):
return s[::-1]
I'm also assuming you need to wrap this in a function, you could just use the index notation on its own.
EDIT:
Here is a bit of an explanation of the [::-1] operation:
Slicing notation is of the format [start_point:end_point:step]
The start_point is not specified, this becomes the length of the list so the operation starts at the end.
The end_point is also not specified, this becomes -1 so the operation will end at the start.
The step is -1, so it will iterate backwards in steps of 1 (i.e. every element of the list).
This will create a shallow copy of your original list. This means the list you pass into reverse(s) will remain the same.
Example for clarification:
>>> x = [1, 2, 3]
>>> y = x[::-1]
>>> x
[1, 2, 3]
>>> y
[3, 2, 1]
A: parameter passed to function is of type list.
def reverse(s):
return s[::-1]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48638951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Playground.js Not Rendering I went through the first two tutorials on the Playground.js website, but the rectangle is not rendering the rectangle. Here is the directory structure:
index.html
scripts
---main.js
---playground.js
index.html:
<!DOCTYPE html>
<html>
<head><title>Simple Game</title></head>
<body>
<script src="scripts/main.js"></script>
<script src="scripts/playground.js"></script>
</body>
</html>
main.js:
var app = playground({
render: function() {
this.layer.clear("#000088");
this.layer.fillStyle("#ffffff");
this.layer.fillRect(32, 32, 64, 64);
}
});
playground.js is the downloaded file from the website.
What is going wrong, and how can I fix it?
A: Switch your main and playground script tags. The order matters:
<script src="scripts/playground.js"></script>
<script src="scripts/main.js"></script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38445658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Srcset not working but shows alt tag message I am building a new website, and want to use the srcset to let the browser deside what image is the best for the current viewport.
What happens is that what ever i put in the srcset the browser will just show the alt tag text "test". If i through F12 developer tools removes the srcset attribute completely, the image shows up just fine.
All images in my example exists and shows up in a browser:
Here is my image tag, can any one see what is wrong with that?
<img src="http://localhost/Medium/Alaska-2-1818.jpg" srcset="http://localhost/Large/Alaska-2-1818.jpg 500w, http://localhost/XXLarge/Alaska-2-1818.jpg 1000w" alt="test">
My problem is shown in this codepen i made:
https://codepen.io/AxelAndersen/project/editor/DxKeaV
A: In your Codepen, some URLs have an error, missing one "i".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46387630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to manage orientation in landscape and portrait using fragment I create one example in Android 3.0 and I use the fragment in it. when I change the mode landscape to portrait or viseversa it give me the error as following but when I comment the fragment calling part it works smoothly as per my changes. for this I create layout-land folder and put may xml file with changes.
does any one have a hint or solution or example for match with this?
this is my fragment:
<fragment
class="com.Organisemee.fragment.TaskListFragment"
android:id="@+id/tasklistfrag"
android:layout_width="match_parent"
android:layout_height="match_parent" />
And this is error:
07-01 12:38:33.363: ERROR/AndroidRuntime(641): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.Organisemee/com.Organisemee.OrganisemeeList}: android.view.InflateException: Binary XML file line #167: Error inflating class fragment
07-01 12:38:33.363: ERROR/AndroidRuntime(641): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1736)
07-01 12:38:33.363: ERROR/AndroidRuntime(641): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1752)
07-01 12:38:33.363: ERROR/AndroidRuntime(641): at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3096)
07-01 12:38:33.363: ERROR/AndroidRuntime(641): at android.app.ActivityThread.access$1600(ActivityThread.java:123)
07-01 12:38:33.363: ERROR/AndroidRuntime(641): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:997)
07-01 12:38:33.363: ERROR/AndroidRuntime(641): at android.os.Handler.dispatchMessage(Handler.java:99)
07-01 12:38:33.363: ERROR/AndroidRuntime(641): at android.os.Looper.loop(Looper.java:126)
07-01 12:38:33.363: ERROR/AndroidRuntime(641): at android.app.ActivityThread.main(ActivityThread.java:3997)
07-01 12:38:33.363: ERROR/AndroidRuntime(641): at java.lang.reflect.Method.invokeNative(Native Method)
07-01 12:38:33.363: ERROR/AndroidRuntime(641): at java.lang.reflect.Method.invoke(Method.java:491)
07-01 12:38:33.363: ERROR/AndroidRuntime(641): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
07-01 12:38:33.363: ERROR/AndroidRuntime(641): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
07-01 12:38:33.363: ERROR/AndroidRuntime(641): at dalvik.system.NativeStart.main(Native Method)
07-01 12:38:33.363: ERROR/AndroidRuntime(641): Caused by: android.view.InflateException: Binary XML file line #167: Error inflating class fragment
07-01 12:38:33.363: ERROR/AndroidRuntime(641): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:688)
07-01 12:38:33.363: ERROR/AndroidRuntime(641): at android.view.LayoutInflater.rInflate(LayoutInflater.java:724)
07-01 12:38:33.363: ERROR/AndroidRuntime(641): at android.view.LayoutInflater.rInflate(LayoutInflater.java:727)
07-01 12:38:33.363: ERROR/AndroidRuntime(641): at android.view.LayoutInflater.inflate(LayoutInflater.java:479)
07-01 12:38:33.363: ERROR/AndroidRuntime(641): at android.view.LayoutInflater.inflate(LayoutInflater.java:391)
07-01 12:38:33.363: ERROR/AndroidRuntime(641): at android.view.LayoutInflater.inflate(LayoutInflater.java:347)
07-01 12:38:33.363: ERROR/AndroidRuntime(641): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:224)
07-01 12:38:33.363: ERROR/AndroidRuntime(641): at android.app.Activity.setContentView(Activity.java:1777)
07-01 12:38:33.363: ERROR/AndroidRuntime(641): at com.Organisemee.OrganisemeeList.onCreate(OrganisemeeList.java:73)
07-01 12:38:33.363: ERROR/AndroidRuntime(641): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
07-01 12:38:33.363: ERROR/AndroidRuntime(641): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1700)
07-01 12:38:33.363: ERROR/AndroidRuntime(641): ... 12 more
07-01 12:38:33.363: ERROR/AndroidRuntime(641): Caused by: java.lang.IllegalStateException: Fragment com.Organisemee.fragment.TaskListFragment did not create a view.
07-01 12:38:33.363: ERROR/AndroidRuntime(641): at android.app.Activity.onCreateView(Activity.java:4114)
07-01 12:38:33.363: ERROR/AndroidRuntime(641): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:664)
07-01 12:38:33.363: ERROR/AndroidRuntime(641): ... 22 more
A: Need to define a Fragment in XML Like This.
<RelativeLayout
android:id="@+id/main_tasklist_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toRightOf="@+id/main_viewmenu_layout"
android:layout_below="@+id/main_tasklist_outer">
<fragment
class="com.Organisemee.fragment.TaskListFragment"
android:id="@+id/tasklistfrag"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
To Call the Fragment put this code in java file
Fragment f = listFragment();
FragmentTransaction ListFragft = getFragmentManager().beginTransaction();
ListFragft.replace(R.id.main_tasklist_layout, f);
ListFragft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ListFragft.addToBackStack(null);
ListFragft.commit();
This Works fine in change both orientation, landscape to portrait and vice versa.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6546531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: List contains method not working in JSF page I have two list that consist out of the same object.
I want to check if the first list containts an object of the second list
<ui:repeat var="item" value="#{userTypeController.permissionItems}">
<c:if test="#{userTypeController.permissionItemsUserType.contains(item)}">
<h:selectBooleanCheckbox value="#{true}"/>
<h:outputText value="#{item.getAction()}" />
</c:if>
<c:if test="#{!userTypeController.permissionItemsUserType.contains(item)}">
<h:selectBooleanCheckbox value="#{false}"/>
<h:outputText value="#{item.getAction()}" />
</c:if>
</ui:repeat>
but this doesn't seem to work and all I'm getting is false.
I've changed the equals and hashcode methodes but didn't help.
A: JSTL tags like <c:if> runs during view build time and the result is JSF components only. JSF components runs during view render time and the result is HTML only. They do not run in sync. JSTL tags runs from top to bottom first and then JSF components runs from top to bottom.
In your case, when JSTL tags runs, there's no means of #{item} anywhere, because it's been definied by a JSF component, so it'll for JSTL always be evaluated as if it is null. You need to use JSF components instead. In your particular case a <h:panelGroup rendered> should do it:
<ui:repeat var="item" value="#{userTypeController.permissionItems}">
<h:panelGroup rendered="#{userTypeController.permissionItemsUserType.contains(item)}">
<h:selectBooleanCheckbox value="#{true}"/>
<h:outputText value="#{item.getAction()}" />
</h:panelGroup>
<h:panelGroup rendered="#{!userTypeController.permissionItemsUserType.contains(item)}">
<h:selectBooleanCheckbox value="#{false}"/>
<h:outputText value="#{item.getAction()}" />
</h:panelGroup>
</ui:repeat>
See also:
*
*JSTL in JSF2 Facelets... makes sense?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8213393",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Redshift Spectrum with Very Wide Column I am using Redshift spectrum with a Glue database. I have some columns which exceed Redshift max text size (64k). Is there a way handle very large columns? Ie if I do it with a parquet does it let me go a bit bigger or is it unavailable with CSV?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73993039",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Discord.py How to get previous track in a queue I created a discord.py music bot with lavalink
Now I want to send and Embed with the Informations about the previous song when you use the ,previous command
i think its very improvised with the lyrics function to get the Thumbnail but thats not the problem
I just want to ask how to replace the player.queue.current_track.title with something that says it have to use the informations of the previous title
@commands.command(name="previous", aliases=["zurück"])
async def previous_command(self, ctx, name: t.Optional[str]):
player = self.get_player(ctx)
name = name or player.queue.current_track.title
async with ctx.typing():
async with aiohttp.request("GET", LYRICS_URL + name, headers={}) as r:
if not 200 <= r.status <= 299:
raise NoLyricsFound
data = await r.json()
if not player.queue.history:
raise NoPreviousTracks
player.queue.position -= 2
await player.stop()
embed = discord.Embed(
title="Vorheriges Lied",
colour=ctx.author.colour,
timestamp=dt.datetime.utcnow(),
)
embed.set_thumbnail(url=data["thumbnail"]["genius"])
embed.set_author(name=data["author"]),
embed.set_footer(text=f"Angefordert von {ctx.author.display_name}", icon_url=ctx.author.avatar_url)
await ctx.send(embed=embed)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68929812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Reading file using Cordova File Plugin I'm using cordova file plugin - cordova file plugin
I'm actually reading the file from the textfile. Below is my code
document.addEventListener("deviceready", function () {
window.resolveLocalFileSystemURL(cordova.file.applicationDirectory + "sameple.txt", gotFile, fail);
}, true);
function gotFile(file) {
file.file(function (file) {
var reader = new FileReader();
reader.onloadend = function (evt) {
console.log(this.result);
}
reader.readAsText(file);
}, fail());
}
function fail(e) {
console.info("FileSystem Error : " + e);
}
So whenever i run this code, i'm getting the below error
deviceready has not fired after 5 seconds.
Channel not fired: onPluginsReady
Channel not fired: onCordovaReady
Could not get Cordova FileSystem: Error: deviceready has not fired after 5 seconds.
"Could not get Cordova FileSystem:"
{
[functions]: ,
__proto__: { },
description: "deviceready has not fired after 5 seconds.",
message: "deviceready has not fired after 5 seconds.",
name: "Error"
}
{"data":"data"}
After deviceready error later i'm able to get the exact data.. How do i resolve this error? do i have to wait for the device ready execution to complete?
A: It can happen for a number of reasons, see here more details.
You should try firs @bayanAbuawad suggestion that works most of the times:
*
*Add the platforms with cordova platform add ios android
*Remove them with cordova platform remove ios android
*Add them again.
It is super weird, but it’s related to a faulty android.json and ios.json inside the platforms folder.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45608080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: composer installation on wamp in window 7 OS I followed the steps in this website:
http://www.wikihow.com/Install-Laravel-Framework-in-Windows
But it's not working on the instructions. Step #11
It displays like this in the command window:
The "https"//packagist.org/packages.json" file could not be downloaded: php _network_getaddresses: getaddrinfo failed: No such host is known. failed to open stream: php_network_getaddresses: getaddrinfo failed: No such host is known.
I'm stuck on this, please help me on this. Thank you.
A: I never managed to get it working in WAMP server. I took my shot with XAMPP. Enormous gigantous (almost 1 GB), but heck yeah, it works!
So, try that, everything should work smoothly.
https://www.apachefriends.org/index.html
A: The solution can be found in internet connection, it is being interrupted that other components cannot be donwloaded.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24859320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I capture a picture from webcam and send it via flask I want to send an Image object in a flask response but it gives me an error. I tried also an approach with StringIO.
image = Image.open("./static/img/test.jpg")
return send_file(image, mimetype='image/jpeg')
This is just a test case. So the major problem is to capture an image from /dev/video0 and sent it (ideally without temporary storing on disk) to the client. I use v4l2capture for that. The test picture should also work if you may have a better solution for that task.
import select
import v4l2capture
video = v4l2capture.Video_device("/dev/video0")
size_x, size_y = video.set_format(1280, 1024)
video.create_buffers(1)
video.queue_all_buffers()
video.start()
select.select((video,), (), ())
image_data = video.read()
video.close()
image = Image.fromstring("RGB", (size_x, size_y), image_data)
Thanks.
EDIT
Works now. Better solutions as v4l2capture are welcome...
A: Did it with.
image = Image.open("./static/img/test.jpg")
img_io = StringIO()
image.save(img_io, 'JPEG', quality=70)
img_io.seek(0)
return send_file(img_io, mimetype='image/jpeg')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26915127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Change the Default Target Server for Entity Framework Code First Approach? I want to apply my code first migrations directly to SQL server or Azure Database instead of using the Default .sql server or Localdb/mssqllocaldb.. is there a way to do this from web.config and without editing code in context class?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38212567",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: java graphics create an N by N board I have this question I haven't solved left in my assignment, "cmps200: introduction to java programming". This is what I wrote but it gives a blank panel:
import java.awt.*;
public class Board {
public static void main(String[] args){
int N= Integer.parseInt(args[0]);
int x=0;
int y=0;
int m=(int)(300/5);
DrawingPanel panel= new DrawingPanel(300, 300);
Graphics g= panel.getGraphics();
for (int i=1; i<=N; i++){
for (int j=1; j<=N; j++){
square();
g.setColor(Color.RED);
circle();
g.setColor(Color.BLUE);
circle();
y+=m;
}
}
}
public static void square(){
int N;
int m= (int)(300/5);
int x=0; int y=0;
DrawingPanel panel= new DrawingPanel(300, 300);
Graphics g= panel.getGraphics();
g.setColor(Color.BLACK);
g.drawRect(x, y, N/300, N/300);
}
public static void circle(){
int x; int y; int m;
Graphics g= panel.getGraphics();
g.fillOval(x+y+(3/2)*m);
}
}
A: Properly pass parameters:
public class Board {
public static void main(String[] args){
...
for (int i=1; i<=N; i++){
for (int j=1; j<=N; j++){
square(N);
g.setColor(Color.RED);
circle(x, y);
g.setColor(Color.BLUE);
circle(x, y);
y+=m;
}
}
}
public static void square(int N){
//deleted first line
int m= (int)(300/5);
int x=0; int y=0;
DrawingPanel panel= new DrawingPanel(300, 300);
Graphics g= panel.getGraphics();
g.setColor(Color.BLACK);
g.drawRect(x, y, N/300, N/300);
}
public static void circle(int x, int y){
//deleted first line
Graphics g= panel.getGraphics();
g.fillOval(x+y+(3/2)*m);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29736210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can i set mark parity? I want test my serial communication between my Arduino and my PC, i want do that because when i connect my arduino to my serial bus i didn´t receive some data.
I have connected my PC over rs232 to my Arduino mega and from the Arduino back to the PC. Now i want send a 9-bit byte to the Arduino and back to the PC, when that works i know that my serial bus is the problem.
Question:
How can i set the mark parity?
My code to test a "normal" byte(8 bit) is written in Visual C# i hope i can use them again and must only fix a bit.
Here the code:
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
System.IO.Ports.SerialPort port = new SerialPort("COM5", 4800);
try
{
port.Open();
while (true)
{
//if (port.BytesToRead > 0)
{
port.Write("A");
}
}
}
catch (Exception) // Press CTRL-C to exit.
{
port.Close();
Console.WriteLine("C");
}
port.Close();
}
}
}
I hope someone can help me with friendly wishes sniffi
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38301874",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: pgrep -f command in ssh through script gives a wrong result. how to solve this issue When I am trying to use pgrep -f <proc_name> command in ssh through script gives a wrong result. How to solve this issue? (I used RSA key for not to ask p/w)
ssh -l $UNAME $HOST bash -c "'
pgrep -f name > p_id
'"
A: It's hard to tell without more details, but my guess is that it's detecting the bash process. The way you're doing it, the remote ssh daemon is running bash -c '<newline>pgrep -f name > p_id<newline>', which then runspgrep -f name(with output to the file "p_id"). Note thatps -fsearches the entire command line for matches, so the "name" part of the argument tobash` is probably matching itself.
One option is to use the old trick to keep ps | grep something from matching itself: use [n]ame instead of just name. But then you need quotes around it, so the quoting gets even more complicated than it already is. It looks simpler to me to just skip the bash -c part and one layer of quoting:
ssh -l $UNAME $HOST 'pgrep -f name >p_id'
A: You didn't include any code from the script, but first look at user permissions, they may be the reason for process command returning different results. Other potential trouble spots are:
Check script permissions and verify execute options. Make sure script user has the correct permissions for the directory where that process runs.
You ran the command via the command prompt, is that with the same user that is executing the script? If not it may be permissions.
Put the -u option in your pgrep command for the user who owns the process you are looking for. Or try inserting an sudo command into the script and run the pgrep as another user, one with admin/root-like privileges.
And don't forget to read the man pages, perhaps there's an option you need.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46866325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to create web service Api in rails 4? can anyone help me how to create a web service API in rails 4. I know how create web service API in ruby 1.8.7 and rails 2.3.5 with action web service gem. When I am trying to use https://github.com/datanoise/actionwebservice gem in rails 4, I am getting deprecated errors.I want to upgrade my web service app. Please help me.
A: Rails-API looks promising, because it will be part of Rails core in Rails 5.
Rails-API
Rails-API is a subset of a normal Rails application, because API only applications don't require all functionality that a complete Rails application provides. so, it compatible well with old Rails versions. I don't know compatibility exactly, but I'm using it with Rails 3.2.x
There are another proper framework for this purpose, for example, Sinatra, Grape, but If you familiar with Rails, Rails-API will be the best choice.
A: Actionwebservice is long deprecated, in favour of REST API's. At my previous job we used a fork of actionwebservice in a rails 3 project.
Since there is no maintainer anymore for the actionwebservice gem, that fork never got merged back. If you check the fork history, a lot of people are fixing and partially updating it, but it is scattered all over the place.
Afaik none of the forks were updated to use rails 4. But using a rails 3 fork might just work.
If you really need to build a SOAP API server with Rails, imho your best option is to take a look at Wash-out, but you will have to re-write your API code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32776399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the point of using custom exception class in php? In some libraries it is common practice to make custom Exception classes for every error condition, like:
class FileNotFound_Exception extends Exception {}
You can handle certain type of Exception, however you cannot read all source code of all libraries to remember each Exception class, and cannot take full advantage of using custom Exceptions. Most of time I just catching them with base Exception class:
catch (Exception $e)
{
// log and display friendly error
}
Is there other ways to have benefit of custom Exception classes, without writing long list of catch blocks?
I like Exceptions, but don't know how to use them properly. Thank you.
A: The benefit of having your own Exception class is that you, as the author of the library, can catch it and handle it.
try {
if(somethingBadHappens) {
throw MyCustomException('msg',0)
}
} catch (MyCustomException $e) {
if(IcanHandleIt) {
handleMyCustomException($e);
} else {
//InvalidArgumentException is used here as an example of 'common' exception
throw new InvalidArgumentException('I couldnt handle this!',1,$e);
}
}
A: Well, custom exception classes lets you route your errors properly for better handling.
if you have a class
class Known_Exception extends Exception {}
and a try catch block like this:
try {
// something known to break
} catch (Known_Exception $e) {
// handle known exception
} catch (Exception $e) {
// Handle unknown exception
}
Then you know that Exception $e is an unknown error situation and can handle that accordingly, and that is pretty useful to me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3735079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Rails 4: After updating an attribute post a message How do I go about posting or rendering a message after updating an attribute to reflect the changes?
(I couldn't find anything online in respect to this task)
For example: Once a user updates the ticket status there will be a message posted in the comment section reporting "Ticket has been closed". (No flash message, but a permanent one).
tickets_controller.rb
def open
@ticket = Ticket.find(params[:ticket_id])
@ticket.update_attributes(:ticket_status, "closed")
redirect_to ticket_path
end
A: You can use the session for this purspose.
def open
@ticket = Ticket.find(params[:ticket_id])
@ticket.update_attributes(:ticket_status, "closed")
session[:close_message] = "Ticket has been closed"
redirect_to ticket_path
end
After that diaplay it in the view like
<%= session[:close_message] %>
but make sure to clear the session like session[:close_message] = nil after displaying the message to free the memory
A: You need to store the message in database if you want it to persist. Say for ex- There is a ticket raised (Ticket model) and someone closes it. The attribute on backend will update attribute status for ticket model.
def update
tkt = Ticket.where(id: 1)
tkt.update_attributes(status: 1)
end
If this is an ajax call, you can send a response data with message like "Ticket closed " and display it accordingly on html page in the success callback of ajax call. If it's a server call, refresh the page and use the status attribute from Ticket model to create the message.
You can use some enums like
{0 => "Ticket Open", 1 => "Ticket closed", 2 => "Ticket in progress" }
In case messages are not generic and every time some more customization is required, better to create and save the entire message as an attribute in the related model and no need to have enums.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39503422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Reducing after filtering doesn't add up with jq I have the following data:
[
{
"name": "example-1",
"amount": 4
},
{
"name": "foo",
"amount": 42
},
{
"name": "example-2",
"amount": 6
}
]
I would like to filter objects with a .name containing "example" and reduce the .amount property.
This is what I tried to do:
json='[{"name":"example-1","amount":4}, {"name": "foo","amount":42}, {"name": "example-2","amount":6}]'
echo $json | jq '.[] | select(.name | contains("example")) | .amount | add'
I get this error:
jq: error (at :1): Cannot iterate over number (4)
I think that the output of .[] | select(.name | contains("example")) | .amount is a stream, and not an array, so I cannot add the values together.
But how could I do to output an array instead, after the select and the lookup?
I know there is a map function and map(.amount) | add works, but the filtering isn't here.
I can't do a select without .[] | before, and I think that's where the "stream" problem comes from...
A: As you say, add/0 expects an array as input.
Since it's a useful idiom, consider using map(select(_)):
echo "$json" | jq 'map(select(.name | contains("example")) | .amount) | add'
However, sometimes it's better to use a stream-oriented approach:
def add(s): reduce s as $x (null; . + $x);
add(.[] | select(.name | contains("example")) | .amount)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70342099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Fetch Autosys Job status through API API is displaying all the attribute values of a job (like status, job name, instance, start time, etc).
I just want to know in post method how should i write the code so that it can fetch the status from api and display output.
url="http://some.api.com"
def get_job_status():
try:
response=requests.post(url)
print(response.status_code)
if response.status_code==200:
// `enter code here`
dict_data=response.json()
print(dict_data["status'])
A: Load text into json object and fetch with keys
import requests
url = "http://some.api.com"
def get_job_status():
response = requests.request("POST", url)
if response.status_code == 200:
json_data = json.loads(response.text)
job_name = json_data["name"]
job_status = json_data["status"]
else:
return "Error with Request"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72882015",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: WWW::Netflix::API program and hiding the consumer_secret key I've written a Perl CLI program that uses the WWW::Netflix::API module. It's finished and I'd like to release it but w/o exposing my consumer_secret key. Any ideas how this can be done?
A: I think you have two options:
*
*Make the end users obtain their own Netflix key.
*Proxy all the traffic through your own server and keep your secret key on your server.
You could keep casual users away from your secret key while still distributing it with some obfuscation but you won't keep it a secret from anyone with a modicum of skill.
Proxying all the traffic would pretty much mean setting up your own web service that mimics the parts of the Netflix API that you're using. If you're only using a small slice of the Netflix API then this could be pretty easy. However, you'd have to carefully check the Netflix terms of use to make sure you're playing by the rules.
I think you'd be better off making people get their own keys and then setting up your tool to read the keys from a configuration file of some sort.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4847582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP stops execution when calling external function When the following PHP script executes:
<?php
include "imageManager.php";
include "imageHandling/spritesheet.php";
include "updateWindow.php";
include_once "dbConnection.php";
class deleteSoftware{
private $conn;
private $tableName;
public function __construct($name){
//Database Connection
$this->connectDatabase();
//Delete the Icon from the image pool
$tempFileManagerObject = new fileManager();
$tempFileManagerObject->setSrc("../ICONS/");
$deletedImageName = $tempFileManagerObject->getImageNameFromSoftwareName($name);
$tempFileManagerObject->delete("../ICONS/", $deletedImageName);
$tempFileManagerObject->deleteImageRenaming($deletedImageName);
//Deleting the record from the database
$prio = $tempFileManagerObject->getPriorityFromSoftwareName($name);
$subCategory = $tempFileManagerObject->getSubCategoryFromSoftwareName($name);
$this->tableName = $subCategory;
$this->conn->query("delete from ".$subCategory." where priority=".$prio);
$this->decrementPriorityInTable($prio);
//Delete from updateWindow if exist
$updateObject = new updateWindow();
$updateObject->deleteUpdate($name);
//Making sprite Sheet and moving to home directory
echo "step-0";
$spriteSheetObject = new spriteSheet(18, 18, 5, "../ICONS/", "../");
echo "step-1";
for ($x = 1; $x <= $spriteSheetObject->getImageCount(); $x++){ $tempFileManagerObject->copy("../ICONS/", "../Processing/", $x); }
echo "step-3";
$spriteSheetObject->setImagesFolder("../Processing/");
echo "step-4";
$spriteSheetObject->setOutPutFolder("../");
$spriteSheetObject->processSpriteSheet();
$spriteSheetObject->processSpriteSheetCss($this->getTotalSoftwaresCount());
for ($x = 1; $x <= $spriteSheetObject->getImageCount(); $x++){ $tempFileManagerObject->delete("../Processing/",$x); }
$tempFileManagerObject->setSrc("../Processing/");
$tempFileManagerObject->setDes("../");
$tempFileManagerObject->rename("tempArea", "home");
$tempFileManagerObject->move("../Processing/", "../", "home");
}
public function connectDataBase(){
$temp = new dbConnection();
$this->conn = $temp->connectDb();
}
public function getTheImageNameOfNewlyInsertedIcon($subCategory, $pri){
//First of all calculate the iconName of newly inserted image
//-Get the total number of rows for each subCategory table and add it untill we reach at the subCategory table where software to be inserted (Not add subCategory table rows count)
//- RowCounts + maxPriority in that table + 1
//- If there is already software for
//Calculating the total number of rows upto subCateogryTable excluding the subCategoryTable and then add up
$temp = false;
$rowCount = 0;
$this->tableName;
$this->conn->query("use windows");
$softwareTable = $this->conn->query("select * from software order by priority");
foreach ( $softwareTable as $row ) {
$categoryTable = $this->conn->query("select * from ".$row["tableName"]." order by priority");
foreach ( $categoryTable as $row2 ) {
$subCategoryTable = $this->conn->query("select * from ".$row2["tableName"]." order by priority");
if (!strcmp($row2["category"], $subCategory)){
$this->tableName = $row2["tableName"];
$temp = true;
break;
}
$rowCount = $subCategoryTable->rowCount() + $rowCount;
}
if ($temp){break;}
}
$rowCount = $pri + $rowCount;
return $rowCount;//This will be the name of the image
//Navigate to Tables
//According to priority set the iconName
//Record the iconName please
//Insert the record in table
//Execute the spritesheet
//make css
//finally iterate the whole database and send a string
}
public function decrementPriorityInTable($pri){
$this->conn->query("use windows");
$softwareTable = $this->conn->query("select * from ".$this->tableName." order by priority");
foreach ( $softwareTable as $row ) {
if($row["priority"] >= $pri+1){
$this->conn->query("update ".$this->tableName." set priority=".($row["priority"]-1)." where priority=".$row["priority"]);
}
}
}
public function getTotalSoftwaresCount(){
$softwareCount = 0;
$softwareTable = $this->conn->query("select * from software order by priority");
foreach ( $softwareTable as $row ) {
$categoryTable = $this->conn->query("select * from ".$row["tableName"]." order by priority");
foreach ( $categoryTable as $row2 ) {
$subCategoryTable = $this->conn->query("select * from ".$row2["tableName"]." order by priority");
foreach ($subCategoryTable as $row3){
$softwareCount++;
}
}
}
$softwareCount++;
return $softwareCount;
}
}
?>
The line $spriteSheetObject = new spriteSheet(18, 18, 5, "../ICONS/", "../"); stops executions without any error.
The spriteSheet class comes from this library:
<?php
require("lib/WideImage.php");
//All the images size must first be set to be placed on canvas
//Depends on only 1-Image "canvasArea.jpg"
//image processing folder is by default a "imagesToBeProcessed"
//output folder is empty by default
class spriteSheet{
private $canvasWidth;
private $canvasHeight;
private $eachImageWidth;
private $eachImageHeight;
private $imagesFolder = "";
private $outputFolder = "";
private $imageCount = 0;
private $maxImageInARow;
function __construct($imgW=43,$imgH=43, $maxInRow=5, $src, $des){
$this->imagesFolder = $src;
$this->outputFolder = $des;
$this->imageCounter();
$this->eachImageWidth = $imgW;
$this->eachImageHeight = $imgH;
$this->canvasWidth = $imgW * $maxInRow;
$this->canvasHeight = $imgH * ceil($this->imageCount/$maxInRow);
$this->maxImageInARow = $maxInRow;
}
public function setImagesFolder($src){
$this->imagesFolder = $src;
}
public function setOutPutFolder($des){
$this->outputFolder = $des;
}
public function imageCounter( ){
for ($x=1; true; $x++){
if (!file_exists($this->imagesFolder.$x.".jpg") and !file_exists($this->imagesFolder.$x.".png") and !file_exists($this->imagesFolder.$x.".gif")){
$this->imageCount = $x;
break;
}
}
$this->imageCount--;
}
public function setCanvasSize( ){
$canvas = WideImage::load($this->imagesFolder."canvasArea.jpg")->resize($this->canvasWidth, $this->canvasHeight, "fill");
$canvas->saveToFile($this->imagesFolder."tempArea.jpg");
}
public function resizeAllIcons( ){
$loopEnable = true;
for ($x=1; $loopEnable == true; $x++){
if (file_exists($this->imagesFolder.$x.".jpg")){
$iconImage = WideImage::load($this->imagesFolder.$x.".jpg")->resize($this->eachImageWidth, $this->eachImageHeight, "fill");
$iconImage->saveToFile($this->imagesFolder.$x.".jpg");
}
else if (file_exists($this->imagesFolder.$x.".png")){
$iconImage = WideImage::load($this->imagesFolder.$x.".png")->resize($this->eachImageWidth, $this->eachImageHeight, "fill");
$iconImage->saveToFile($this->imagesFolder.$x.".png");
}
else if (file_exists($this->imagesFolder.$x.".gif")){
$iconImage = WideImage::load($this->imagesFolder.$x.".gif")->resize($this->eachImageWidth, $this->eachImageHeight, "fill");
$iconImage->saveToFile($this->imagesFolder.$x.".gif");
}
else{
$loopEnable = false;
}
}
}
public function processSpriteSheet( ){
$this->resizeAllIcons();
$this->setCanvasSize();
$row=0; $col=0; $tempImageCounter = 1;
while ($tempImageCounter<=$this->imageCount){
$icon;
if (file_exists($this->imagesFolder.$tempImageCounter.".jpg")){
$icon = WideImage::load($this->imagesFolder.$tempImageCounter.'.jpg');
}
else if (file_exists($this->imagesFolder.$tempImageCounter.".png")){
$icon = WideImage::load($this->imagesFolder.$tempImageCounter.'.png');
}
else if (file_exists($this->imagesFolder.$tempImageCounter.".gif")){
$icon = WideImage::load($this->imagesFolder.$tempImageCounter.'.gif');
}
else{
break;
}
$canvas = WideImage::load($this->imagesFolder."tempArea.jpg");
$canvas->merge($icon, $row*$this->eachImageWidth, $col*$this->eachImageHeight, 100)->saveToFile($this->imagesFolder."tempArea.jpg");
$tempImageCounter++;
$row++;
if ($row == $this->maxImageInARow){
$row=0;
$col++;
}
}
}
public function processSpriteSheetCss($maxImageCss){
echo "maxImage:".$maxImageCss;
$imgCommon = "img.common{
width: ".$this->eachImageWidth."px;
height: ".$this->eachImageHeight."px;
background-image:url(home.jpg);
}";
$imgS=""; $y=0; $tempImageCounter = 1;
for($x=0; $tempImageCounter<=$maxImageCss; $x++){
$imgS = $imgS."img.s".$tempImageCounter."{background-position:".-1*($x*$this->eachImageWidth)."px ".-1*($y*$this->eachImageHeight)."px;}";
if ($tempImageCounter%$this->maxImageInARow == 0){
$x = -1;
$y++;
}
$tempImageCounter++;
}
echo "SpriteSheetCSS".$imgS;
$handle = fopen( "../css/sprite.css", "w" );
fwrite($handle, $imgS);
}
public function getImageCount(){
echo "total number of images-->".$this->imageCount;
return $this->imageCount;
}
}
?>
My script stops execution at that line without any error.
This file works perfectly on localhost but when I put this online and execute it then this problem happens.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29346389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to put recaptcha and submit in one line contact form 7 How to add these elements in one line:
[recaptcha] [submit "Send"]
So recaptcha will be on the left and submit button on the right
WordPress wraps each shortcode with div.
A: Give the fields class names in Contact Form 7:
<div class="clearfix">[recaptcha id:recaptchaform]<p class="cf7submitbtn">[submit "Send"]</p></div>
Then set your CSS to be:
.recaptchaform {float:left}
.cf7submitbtn {float:right}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48470220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How Can I migrate magento 1.9 code to magento 2.3 I created a newsletter checkbox on magento 1,9 checkout and it work fine. There is the code :
app/design/frontend/default theme/default/template/persistent/ Checkout/onepage/billing.phtml
Newsletter : <input type="checkbox" name="billing[is_subscribed]" title="" value="1" id="billing:is_subscribed" class="checkbox" checked="checked" />
And finaly : app/code/core/(le nom de ton Magento)/Checkout/controllers/Onepagecontroller.php
if (isset($data['is_subscribed'])) {
$status = Mage::getModel('newsletter/subscriber')->subscribe($data['email']);
}
It work like charm in magento 1.9 but I do not know how to put that in Magento 2.3 is not the same structure :/
Someone can help me ?
Best regards
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55328612",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Magento Product View Page: Add Layout Changes Depending on Product Search or Category Browsing Using Magento 1.7.0.2 CE, I would like to try to find a way to make XML layout changes to the Product View page, depending on if the product was searched in-site or found from the category view. Reason being, the custom vertical navigation on the left bar I made for our site uses the "current_category" key in the Magento registry to display correctly.
If there is no category set, it displays our 7 major base categories. If a category is set, it displays only the sub-categories of that base category (~34 sub-cats, expands with active sub-category). So naturally, I would like to even out my sidebar space when the vertical navigation bar is small.
If a product is browsed through a category, the registry keeps the "current_category" key, so my vertical navigation fills the left bar quite well on its own. If it is searched, the navigation bar approaches about 30% of the height when compared with the right bar.
My ideal solution would be a layout update to local.xml, but I'm not sure if there is anything already built in place with Magento to do so.
So my final question is in two parts: Is there a way within Magento's XML Layout to determine if the "catalog_product_view" page was loaded via category or search?
If not: What would be the most efficient way to code in moving a couple blocks from the right bar to the left from the product view page, depending on if the product was searched or browsed?
One possible solution (for the last bit): Would anyone know how to code in a new layout tag? I was thinking of instead of just "catalog_product_view", creating "catalog_product_view_browsed" and "catalog_product_view_searched" that are applied over the default product view.
Edit: I have it working and my answer has been posted below. :)
A: In order to use custom layout handles in your local.xml file, first you have to make an observer for it. To create an observer, you start out by adding it as an extension / module. Create the following files/folders if not present (The names Yourname and Modulename can be anything, just make sure it's the same where it shows up, including upper/lower case):
Directory View
/app/etc/modules/Yourname_Modulename.xml
/app/code/local/Yourname/Modulename/etc/config.xml
/app/code/local/Yourname/Modulename/Model/Observer.php
Now that you have the file structure, let's look at the first file, Yourname_Modulename.xml tucked in the app/etc/modules/ folder:
Yourname_Modulename.xml
<?xml version="1.0"?>
<config>
<modules>
<Yourname_Modulename>
<codePool>local</codePool>
<active>true</active>
</Yourname_Modulename>
<modules>
<config>
Now /app/code/local/Yourname/Modulename/etc/config.xml:
config.xml
<?xml version="1.0"?>
<config>
<global>
<models>
<yournamemodulename>
<class>Yourname_Modulename_Model</class>
</yournamemodulename>
</models>
</global>
<frontend>
<events>
<controller_action_layout_load_before>
<observers>
<yourname_modulename_model_observer>
<type>singleton</type>
<class>Yourname_Modulename_Model_Observer</class>
<method>controllerActionLayoutLoadBefore</method>
</yourname_modulename_model_observer>
</observers>
</controller_action_layout_load_before>
</events>
</frontend>
</config>
And lastly the file /app/code/local/Yourname/Modulename/Model/Observer.php. For this one, you'll need to know what you'd like to name "your_layout_handle" and also how to determine if your layout should be loaded via PHP.
Observer.php
<?php
class Yourname_Modulename_Model_Observer
{
public function controllerActionLayoutLoadBefore( Varien_Event_Observer $observer)
{
//Get Layout Object
$layout = $observer->getEvent()->getLayout();
/*
*Begin Logic to Determine If Layout Handle Should Be Applied.
*Below Determines If We Are On A Product View Page.
*Here is Where You Would Modify The Code For Different Layout Handles
*/
if( Mage::registry( 'current_product' ) ) {
//Check if current_category is set
if( Mage::registry( 'current_category' ) ) {
//Send Layout Update Handle If Product Was Browsed
$layout->getUpdate()->addHandle( 'your_layout_handle' );
}
else {
//Send Layout Update Handle If Product Was Linked or Searched
$layout->getUpdate()->addHandle( 'your_other_handle' );
}
}
}
}
I would say that is all, but of course you now need to do something with your layout handles in app/code/design/frontend/package/theme/layout/local.xml. How it behaves is up to you, but for an example here is the sections that apply in my local.xml. The names I used for my handles were "catalog_product_view_browsed" and "catalog_product_view_searched".
local.xml
<!-- Jump To Relevant Section -->
<catalog_product_view_browsed>
<reference name="left">
<action method="unsetChild">
<name>left.poll</name>
</action>
</reference>
<reference name="right">
<action method="insert">
<blockName>left.poll</blockName>
<siblingName>right.newsletter</siblingName>
<after>0</after>
</action>
</reference>
</catalog_product_view_browsed>
<catalog_product_view_searched>
<reference name="left">
<action method="insert">
<blockName>right.newsletter</blockName>
<siblingName>left.vertnav</siblingName>
<after>1</after>
</action>
</reference>
<reference name="right">
<action method="unsetChild">
<name>right.newsletter</name>
</action>
</reference>
</catalog_product_view_browsed>
<!-- End Relevant Section -->
You may need to refresh/clean your cache. That should be it.
A: There's unfortunately no way to track referring pages in Magento's layout XML, but you can tell if someone came to the product page from a search by checking $_SERVER['HTTP_REFERER'].
If a user comes to a product page from a search, the referring url will look like this: /catalogsearch/result/?q=[SEARCH TERM].
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17981514",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Linux Terminal Characters Show Up as Symbols Rather Than As Typed On Keyboard I am using Ocaml from a Linux terminal. Sometimes it gets stuck in a weird mode where it does not respond to my keyboard as expected. For example, if I press the arrows up, down, right, and left, it generates ^[[A^[[B^[[C^[[D in input. Alternatively, sometimes if I type a letter only once it might repeat that same letter three times in a row and/or if I type the delete button it types "^H" instead.
Does anyone know what is going on here? I assume that I am inadvertently doing something to switch the mode but I don't how to switch it back or why it is switching in the first place.
A: 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.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13372457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: While scraping the website through scrapy in python getting the following error:
Error: UnicodeEncodeError: 'charmap' codec can't encode character
u'\u201c' in position 0: character maps to
Code : # -- coding: utf-8 --
import scrapy
class Spider1Spider(scrapy.Spider):
name = 'spider_1'
allowed_domains = ["quotes.toscrape.com"]
start_urls = (
'http://quotes.toscrape.com/' ,
)
def parse(self, response):
x=response.xpath('//*[@class="quote"]')
for quotes in x:
text= x.xpath('.//*[@class="text"]/text()').extract_first()
author= x.xpath('.//*[@class="author"]/text()').extract_first()
Tags= x.xpath('.//*[@class="keywords"]/@content').extract_first()
print '\ n'
print text
print author
print Tags
print '\ n'
Problm: if i use extract_first only then it's throwing the error else we use only extract. it work fines.
Could anyone please help as i am new to programming world and looking forward for positive solution.
A: You need to .encode() your Unicode strings before print:
print text.encode('utf-8')
print author.encode('utf-8')
print Tags.encode('utf-8')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50290783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Mysql count columns I have a table for image gallery with four columns like:
foid | uid | pic1 | pic2 | pic3 | date |
-----------------------------------------------
104 | 5 | 1.jpg | 2.jpg | 3.jpg | 2010-01-01
105 | 14 | 8.jpg | | | 2009-04-08
106 | 48 | x.jpg | y.jpg | | 2010-08-09
Mysql query for the user's galleries looks like:
SELECT * FROM foto WHERE uid = $id order by foid DESC
The thing that I want to do is count the number of images (PIC1, PIC2, PIC3) in every of the listed galleries.
What is the best way for doing that?
A: I am assuming that each foid represents a gallery:
SELECT foid, uid, date,
(CASE WHEN pic1 IS NULL THEN 0 ELSE 1 END +
CASE WHEN pic2 IS NULL THEN 0 ELSE 1 END +
CASE WHEN pic3 IS NULL THEN 0 ELSE 1 END
) AS pic_count
FROM foto
WHERE uid = $id
ORDER BY foid DESC
Incidentally, this isn't a particularly sensible way to structure your schema. You really should split the pics out as a separate table:
foto:
foid | uid | date
-----------------------
104 | 5 | 2010-01-01
105 | 14 | 2009-04-08
106 | 48 | 2010-08-09
pic:
foid | pic
------------
104 | 1.jpg
104 | 2.jpg
104 | 3.jpg
105 | 8.jpg
106 | x.jpg
106 | y.jpg
Now, galleries can have more than three pics and querying is simpler:
SELECT foid, uid, date, COUNT(*)
FROM foto
JOIN pic USING (foid)
WHERE uid = $id
ORDER BY foid DESC
GROUP BY foid, uid, date
EDIT: You can split an existing database thus (just guessing at stuff like column types):
CREATE TABLE picture (foid INT, pic VARCHAR(255));
INSERT INTO picture (foid, pic)
SELECT foid, pic1 as pic FROM foto WHERE pic IS NOT NULL
UNION
SELECT foid, pic2 as pic FROM foto WHERE pic IS NOT NULL
UNION
SELECT foid, pic3 as pic FROM foto WHERE pic IS NOT NULL
;
ALTER TABLE foto
DROP COLUMN pic1,
DROP COLUMN pic2,
DROP COLUMN pic3
;
Obviously, one should exercise considerable care when dropping columns, and make a backup before you start!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2764672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.