text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: R: source_gist not working I am trying to use source_gist from the devtools package but I am encountering an error:
> library(devtools)
> source_gist("524eade46135f6348140")
Error in r_files[[which]] : invalid subscript type 'closure'
Thanks for any advice.
A: Agree this is a bug, which I see you've submitted.
A temporary workaround is to specify the filename option:
devtools::source_gist("524eade46135f6348140", filename = "ggplot_smooth_func.R")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38345894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Update Column using Row Number based on primary key column in SQL Server I have table in below format
UserID SeqID RowNum
1 8041 0
1 8045 0
1 8045 0
2 6587 0
2 5624 0
I want to update the RowNum column based on the userId column as follows
UserID SeqID RowNum
1 8041 1
1 8045 2
1 8045 3
2 6587 1
2 5624 2
How to use row number concept to update the RowNum column?
Note: it is just sample data. So I can't update using hardcoding the UserId values. I have millions of records in this table.
Thanks in advance.
A: In SQL Server, you would use row_number() and a CTE:
with toupdate as (
select t.*, row_number() over (partition by UserId order by SeqId) as seqnum
from table t
)
update toupdate
set rownum = seqnum;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29821645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: problem while creating table from maven spring mvc I am not able to auto-create table from maven spring mvc.
I was doing a spring mvc project using maven. By far i have got no errors but when i am trying to create table in my database using applicationconfig.xml it is not working. i have searched over the internet but my applicationconfig.xml seems fine to me. I have got no errors. Still the table is not created..
applicationconfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<bean id="entityManager" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.milan.entities" /><!--scans model/entity/domain(name 3 but same) and registers-->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create-drop</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/inventorymanagement" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManager" />
</bean>
<tx:annotation-driven />
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
</beans>
User Class
package com.milan.entities;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
public class User implements Serializable{
@Id
@Column(name = "USER_ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long userId;
@Column(name = "USERNAME")
private String userName;
@Column(name = "PASSWORD")
private String password;
@Column(name = "IS_ENABLEd")
private boolean isEnabled;
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isIsEnabled() {
return isEnabled;
}
public void setIsEnabled(boolean isEnabled) {
this.isEnabled = isEnabled;
}
}
There is no error while running the program however the table is not created automatically.
A: Put @Entity on your User class, if the table still not created try putting below annotations on the class:
@Entity
@Table(name = "`user`")
Could be happening because User is a reserve word in DB.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53790356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How does comparison operator works with null int? I am starting to learn nullable types and ran into following behavior.
While trying nullable int, i see comparison operator gives me unexpected result. For example, In my code below, The output i get is "both and 1 are equal". Note, it does not print "null" as well.
int? a = null;
int? b = 1;
if (a < b)
Console.WriteLine("{0} is bigger than {1}", b, a);
else if (a > b)
Console.WriteLine("{0} is bigger than {1}", a, b);
else
Console.WriteLine("both {0} and {1} are equal", a, b);
I was hoping any non-negative integer would be greater than null, Am i missing something here?
A: As MSDN says
When you perform comparisons with nullable types, if the value of one
of the nullable types is null and the other is not, all comparisons
evaluate to false except for != (not equal). It is important not to
assume that because a particular comparison returns false, the
opposite case returns true. In the following example, 10 is not
greater than, less than, nor equal to null. Only num1 != num2
evaluates to true.
int? num1 = 10;
int? num2 = null;
if (num1 >= num2)
{
Console.WriteLine("num1 is greater than or equal to num2");
}
else
{
// This clause is selected, but num1 is not less than num2.
Console.WriteLine("num1 >= num2 returned false (but num1 < num2 also is false)");
}
if (num1 < num2)
{
Console.WriteLine("num1 is less than num2");
}
else
{
// The else clause is selected again, but num1 is not greater than
// or equal to num2.
Console.WriteLine("num1 < num2 returned false (but num1 >= num2 also is false)");
}
if (num1 != num2)
{
// This comparison is true, num1 and num2 are not equal.
Console.WriteLine("Finally, num1 != num2 returns true!");
}
// Change the value of num1, so that both num1 and num2 are null.
num1 = null;
if (num1 == num2)
{
// The equality comparison returns true when both operands are null.
Console.WriteLine("num1 == num2 returns true when the value of each is null");
}
/* Output:
* num1 >= num2 returned false (but num1 < num2 also is false)
* num1 < num2 returned false (but num1 >= num2 also is false)
* Finally, num1 != num2 returns true!
* num1 == num2 returns true when the value of each is null
*/
A: To summarise: any inequality comparison with null (>=, <, <=, >) returns false even if both operands are null. i.e.
null > anyValue //false
null <= null //false
Any equality or non-equality comparison with null (==, !=) works 'as expected'. i.e.
null == null //true
null != null //false
null == nonNull //false
null != nonNull //true
A: Comparing C# with SQL
C#: a=null and b=null => a==b => true
SQL: a=null and b=null => a==b => false
A: According to MSDN - it's down the page in the "Operators" section:
When you perform comparisons with nullable types, if the value of one of the nullable types is null and the other is not, all comparisons evaluate to false except for !=
So both a > b and a < b evaluate to false since a is null...
A: If you do in your last else "else if (a == b)" you wont get any output at all. a is not greater than 1, is not less than 1 or equal to 1, is null
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15777745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "198"
}
|
Q: Task scheduler to execute powershell script does not get response to webRequest I have Powershell script that has below code
$instance_id=(Invoke-WebRequest -URI http://169.254.169.254/latest/meta-data/instance-id)
Write $_ "webrequest command output = " $instance_id >> C:/auto_register.log
$instance_id=$instance_id.Content
Write "instance_id is " $instance_id >> C:/auto_register.log
and output of the text file is
webrequest command output =
instance_id is
I have setup scheduled task to run this script on startup. When I execute this script manually in powershell then variable value gets set. However, It doesn't set value when I execute this script through TaskScheduler.
Does anybody know why?
A: “-UseBasicParsing” parameter worked like a charm for a unloginable account. I've used the following link for reference.
https://powershell.org/forums/topic/powershell-scripts-with-task-scheduler-failing/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50332964",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Overlap of DNA in Python programming The output should be the similarity length, in this case 15(length)
Can anyone helps me?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41323063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to run schedule task in c# blazor every 30 second I am writing a blazor server side application. I have like 100 Binance API or more to work with. How can I run a scheduled task that will monitor each API on given amount of time. Or is there any better way to approach approach to this?
A: You can add a background service. Nothing to do with Blazor, just Asp.Net:
It's just one line in the Startup class:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddHostedService<MyBackgroundService>();
}
and then implement your own MyBackgroundService with a loop or a Timer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65899465",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Convert a JavaScript import to an array? I have a NPM package that I need to load most of the modules for. I can do the import statement like this:
import * as primeng from 'primeng/primeng';
But in my @NgModule Angular declaration, I need to explicitly list out every single element in the imports section:
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule, FormsModule, HttpModule,
// primeNG
primeng.ButtonModule, primeng.ChipsModule, primeng.ContextMenuModule, primeng.DataTableModule,
primeng.DialogModule, primeng.DropdownModule, primeng.EditorModule, primeng.FieldsetModule,
primeng.GMapModule, primeng.GrowlModule, primeng.InputSwitchModule, primeng.InputTextModule,
primeng.PanelMenuModule, primeng.PanelModule, primeng.SharedModule, primeng.SpinnerModule, primeng.TreeModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
Is there any way to instead use something like primeng.keys() (which doesn't work) to my imports section of the NgModule?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42515223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to use keras model.predict with placeholders input? I'm trying to feed keras predict method with tf placeholders while providing real data later.
I do
z = model.predict(x*y, steps=1) where x and y are tf placeholders.
Then I do sess.run(tf.variables_initializer([z], feed_dict = {x: <x>, y: <y>})) where <x> and <y> are numpy arrays.
But I get error: Invalid argument: You must feed a value for placeholder tensor 'Placeholder' with dtype float and shape [1,1024,1024,3]
[[{{node Placeholder}}]]
I don't really understand - where do I need to feed placeholders with values?
A: model.predict() executes the actual prediction. You can't predict on placeholders, you need to feed that function real data. If you explicitly feed it None for input data, then the model must have been created with existing data tensor(s), and it still is what executes the actual prediction.
Normally, when a model is created, it has placeholder tensors for the input and output. However, you have the option of giving it real tensors, instead of placeholders. See an example of this here. In this case, and only this case, you can use fit, predict, or evaluate without feeding it data. The only reason you can do that is because the data already exists.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58645384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: wxPython hypertreelist set item to checked I'm trying to build a simple interface with hypertreelist. Basically, what I want to do, is set the item to a checked state. There is the function .IsChecked() to retrieve the checkbox status on an item, but no SetCheck() or SetValue(). Any idea on how to do this?
I suppose I need to access the checkbox object inside the TreeListItem, but I have no clue on how to do that. The documentation on that isn't really helpful.
Here's part of my code:
self.view.tree_list.AddColumn('Available columns')
root = self.view.tree_list.AddRoot('All columns', ct_type=1)
branches = {}
for item in self.possibleColumns:
branches[item] = self.columnsView.tree_list.AppendItem(root, item, ct_type=1)
if item in self.wantedColumns:
# set to checked
where wantedColumns and possibleColumns are array of strings. (the frame will help decide which columns to show in another tab)
Thanks,
A: HyperTreeList inherits from GenericTreeItem:
*
*http://wxpython.org/Phoenix/docs/html/lib.agw.customtreectrl.GenericTreeItem.html#lib.agw.customtreectrl.GenericTreeItem
It would appear that you can use its Check() method to toggle whether a tree item is checked or not.
A: Just been struggling with this also, here my solution:
import wx.lib.agw.hypertreelist as HTL
self.tree_list =self.createTree()
self.tree_list.AddColumn("File")
self.tree_list.AddColumn("Size")
#self.tree_list.AssignImageList(some image_list)
self.root =self.tree_list.AddRoot("abc", ct_type=1)
for my_text in [ 'def', 'ghi', 'jkl' ]:
node =self.tree_list.AppendItem( self.root, testware_path, ct_type =1)
self.tree_list.SetItemText( node, text=my_text, column=1)
self.tree_list.SetItemText( node, text=my_text, column=2)
if my_text.startswith('d'):
node.Check()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24811389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Manipulating audio to bypass content ID detection I'm using YouTube's "auto-generated" captions feature to generate transcripts of mp3 files. I do this by first converting the mp3 to a blank mp4, uploading to YouTube, waiting for the auto generated captions to appear, then extracting the SRT file.
The issue I'm having though is that a few of the mp3 files I've uploaded have been flagged as having copyrighted content, and as such no auto-generated captions have been made for them.
I have no desire to publish the mp3s on YouTube, they're uploaded as unlisted videos and all I require are the SRT files. Is there a way to manipulate the audio to bypass YouTube's content ID system? I've tried altering the pitch in Audacity, but it doesn't matter how subtle or extreme the pitch change is, they're still flagged as having copyrighted content. Is there anything else I can do to the audio other than adjusting the pitch that might work?
I'm hoping this post doesn't breach any rules on here, and I can't stress enough that I'm not looking to publish these mp3s, I just want the auto-generated SRTs.
A: No one can know how to cheat on Content ID
Obviously, as Content ID is a private algorithm developed by Google, no one can know for sure how do they detect copyrighted audio in a video.
But, we can assume that one of the first things they did was to make their algorithm pitch-independent. Otherwise, everyone would change the pitch of their videos and cheat on Content ID easily.
How to use Youtube to get your subtitles anyway
If I am not mistaken, Content ID blocks you because of musical content, rather than vocal content. Thus, to address your original problem, one solution would be to detect musical content (based on spectral analysis) and cut it from the original audio. If the problem is with pure vocal content as well, you could try to filter it heavily and that might work.
Other solutions
Youtube being made by Google, why not using directly the Speech API that Google offers and which most likely perform audio transcription on Youtube? And if results are not satisfying, you could try other services (IBM, Microsoft, Amazon and others have theirs).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45833389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: for loop not working in js the SelectSeat Function doesnt do anything.. cant figure our why...i have called it from the html onclick event.
<html>
<head><link rel="stylesheet" type="text/css" href="mandigo.css">
<center> <b><i><font size="25" color="Blue"> Ticket Booking </b></i> </font>
<script>
var seat = [true,false,true,false,false,false];
var sel_seat=-1;//for selecting a seat
function setHtml(){
alert("check");
for(var i=0;i<seat.length ;i++){
if(seat[i]){
document.getElementById("seat"+(i+1)).src ="Avail.png";
document.getElementById("seat"+(i+1)).alt ="Available";
}
else{
document.getElementById("seat"+(i+1)).src ="UnAvail.png";
document.getElementById("seat"+(i+1)).alt ="UnAvailable";
}
}
}
function SelectSeat(){
setHtml();
for(var i=0;i<seat.length;i++){
if(seat[i]){
sel_seat=i+1;
var accept=confirm("Seat "+(i+1)+" is Available. Book it ??");
if(accept){
Booking();// in Booking change the seat color using anothr picture.
break;//to break out of the loop
}
//if not true loop continues until it fins an empty seat
/*if(!accept){
}*/
if(sel_seat==-1&&i>=seat.length+1)
alert("No Seats Are Available");
}
}
}
function Booking(){
document.getElementById("seat"+sel_seat).src="SelectedSeat.png";
}
</script>
</head>
<body>
<div><pre>
<img src="Avail.png" alt="Available" id="seat1"width="90" height="90"><img src="Avail.png" alt="Available" id="seat2"width="90" height="90">
<img src="Avail.png" alt="Available" id="seat4"width="90" height="90"><img src="Avail.png" alt="Available" id="seat5"width="90" height="90">
<img src="Avail.png" alt="Available" id="seat3"width="90" height="90"><img src="Avail.png" alt="Available" id="seat6"width="90" height="90">
</pre></div>
<center>
<input type="Button" value="Find Me a Seat" onClick="SelectSeat();"/>
</body>
</html>
okay.. sorry abt that before should have given the full pgm from the start
By not working ... i mean nothing happens.. not getting any error msgs either...
A: You are never calling the function SelectSeat().
In order to run the function, you have to 'active' it somehow, for instance
when the page is loaded: window.onload=function(){SelectSeat()};
or when you click on something: <div onclick="SelectSeat()">click me</div>';
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30694391",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: Java ArrayList reference I am creating an ArrayList of objects using generics. Each thread does come calculating and stores the object in the the array list.
However when looking at the ArrayList which is static and volatile all the object attributes are set as null. My thoughts are something to do with the garbage collector removing the instances in the threads so once the threads have finished there is no reference to them.
Any help would be really helpful?
A: The garbage collector will not remove instances1 from an array list. That is not the problem.
The problem is most likely that you are accessing and updating the array list object without proper synchronization. If you do not synchronize properly, one thread won't always see the changes made by another one.
Declaring the reference to the ArrayList object only guarantees that the threads will see the same list object reference. It makes no guarantees about what happens with the operations on the list object.
1 - Assuming that the array list is reachable when the GC runs, then all elements that have been properly added to the list will also be reachable. Nothing that is reachable will be deleted by the garbage collector. Besides, the GC won't ever reach into an object that your application can still see and change ordinary references to null.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27083770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Mounting up number of calling move constructor? I'm new to C++14 and am experimenting a make_vector builder for constructing elements of std::vector in one line, and in place. For example the usage of the builder will look like:
make_vector<AnyStruct>()
<< AnyStruct(1)
<< AnyStruct(2)
<< AnyStruct(3);
So I created this simple builder as follow:
template <typename T>
class make_vector final
{
public:
make_vector<T> &operator<<(T &&t)
{
std::cerr << "operator<< for T" << std::endl;
data_.emplace_back(std::forward<T>(t));
return *this;
}
operator std::vector<T> &&()
{
std::cerr << "implicitly convert to std::vector<T>" << std::endl;
return std::move(data_);
}
private:
std::vector<T> data_;
};
And then supply the builder with a simple struct:
struct Foo
{
inline static size_t constructCount = 0;
inline static size_t moveCount = 0;
explicit Foo(int d) : data(d)
{
std::cerr << "Foo(int)" << std::endl;
++Foo::constructCount;
}
explicit Foo(Foo &&other) : data(other.data)
{
std::cerr << "Foo(Foo&&)" << std::endl;
++Foo::moveCount;
}
explicit Foo(const Foo &other) = delete;
const int data;
friend std::ostream &operator<<(std::ostream &os, const Foo &self)
{
os << "Foo(" << self.data << ")";
return os;
}
};
Finally, I test my make_vector with following code:
int main(...) {
make_vector<Foo>() << Foo(1) << Foo(2) << Foo(3);
}
And I'm seeing very strange logs:
Foo(int) // 1st Foo(1)
operator<< for T
Foo(Foo&&)
Foo(int) // 2nd Foo(2)
operator<< for T
Foo(Foo&&)
Foo(Foo&&)
Foo(int) // 3rd Foo(3)
operator<< for T
Foo(Foo&&)
Foo(Foo&&)
Foo(Foo&&)
It looks like the 2nd << Foo(2) is moved twice and 3rd << Foo(3) is moved for 3 times. It's not as I expect that move-ctor should occur once for each Foo(...).
I'm expecting the ideal logs be like this:
Foo(int) // 1st Foo(1)
operator<< for T
Foo(Foo&&)
Foo(int) // 2nd Foo(2)
operator<< for T
Foo(Foo&&)
Foo(int) // 3rd Foo(3)
operator<< for T
Foo(Foo&&)
Why is move-ctor called more than once?
A: data_.emplace_back(std::forward<T>(t));
will add elements to the vector. But if the vector runs out of space it will allocate a larger chunk of memory and copy or, if possible, move the existing objects into the new storage.
You need to be much more clever to cache all the objects, reserve enough space for them and only at the end emplace them all.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72833941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java MapStruct always convert boolean to false I have 2 classes.
First:
@Getter
@Builder
@Document("user")
public class UserDocument {
@Id
private String id;
private final String username;
private final String email;
private final String password;
private final Set<RoleDto> roles;
private final boolean active;
Second:
@Builder
@Getter
@Value
public class UserDto {
String id;
String username;
String email;
String password;
Set<RoleDto> roles;
boolean active;
And my mapStruct interface:
@Mapper(componentModel = "spring")
public interface UserConverter {
UserDocument toDocument(UserDto userDto);
UserDto toDto(UserDocument userDocument);
MapStruct always converts my boolean active to false. Is it a problem with Lombok? It generates getter isActive() and I don't know why it doesn't work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62269466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to pass parameters value from a template yaml file to main pipeline when i try to run this pipeline on azure devops, i got the error "Unexpected property RunChangeLogic". How can I troubleshoot this?
It seems it doesn't accept the parameter from the template EntryPoint.yaml. Is there anything else I need to do?
sorry for the simple question like this. I am completely new to Azure Devops
EntryPoint.yaml:
parameters:
- name: RunChangeLogic
displayName: Run change logic
type: boolean
default: false
....
Azure_pipeline.yaml:
trigger: none
pool:
vmImage: 'ubuntu-latest'
stages:
- template: "YamlTemplates/Stage/Entrypoint.yaml"
parameters:
RunChangeLogic: 'true'
A: I tried your yaml and it works for me with following yaml.
Entrypoint.yaml:
parameters:
- name: RunChangeLogic
displayName: Run change logic
type: boolean
default: false
steps:
- script: echo ${{ parameters.RunChangeLogic }}
Azure_pipeline.yaml:
trigger: none
pool:
vmImage: 'ubuntu-latest'
extends:
template: "YamlTemplates/Stage/Entrypoint.yaml"
parameters:
RunChangeLogic: 'true'
For more info please refer the official Doc Template types & usage.
Edit:
From your comment, I understand that you have a multi stage azure pipeline. Please refer to this stages.template definition.
You can define a set of stages in one file and use it multiple times in other files.
Here is my test yaml files for stages template.
Entrypoint.yaml:
parameters:
- name: RunChangeLogic
displayName: Run change logic
type: boolean
default: false
stages:
- stage: Teststage1
jobs:
- job: ${{ parameters.RunChangeLogic }}_testjob1
steps:
- script: echo ${{ parameters.RunChangeLogic }}
- stage: Teststage2
jobs:
- job: ${{ parameters.RunChangeLogic }}_testjob2
steps:
- script: echo ${{ parameters.RunChangeLogic }}
Azure_pipeline.yaml:
trigger: none
pool:
vmImage: 'ubuntu-latest'
stages:
- template: "YamlTemplates/Stage/Entrypoint.yaml"
parameters:
RunChangeLogic: 'true'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72094645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to remove embeded objects from word using c# interop? I am trying to get pdf/word/excel embeded documents & remove it.
but, instead of embededOleObject it detects is as an MSOPicture type.
I am using document.InlineShapes & iterating it inlineshape and checking it's type.
It detects as MSOPicture insted of embdedOleObject or embededLinkedOleObject.
can anyone suggest how can I detect correct inlineshape type?
A: Try this
WdInlineShapeType.wdInlineShapeEmbeddedOLEObject
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65826437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get full message including header from Grails JMS? I want to get the full message (header & body) from an ActiveMQ connection using Grails and JMS.
The code below just returns the message body. When I uncomment the "static adapter = " line, I get the header and an abbreviated version of the header. How do I get the full message?
class NrodTmListenerService {
static exposes = ["jms"]
static destination = "SOMEDESTINATION"
static isTopic = true
// static adapter = "zeroConversionAdapter"
def onMessage(msg) {
// handle message
// explicitly return null to prevent unwanted replyTo attempt
return null
}
}
In my config.groovy:
jms {
adapters {
zeroConversionAdapter {
meta {
parentBean = 'standardJmsListenerAdapter'
}
messageConverter = null
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27113771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to access sapply output including lmer I'm trying to estimate and simulate various models. I can fit many models with sapply but somehow, I'm unable to access the output.
models <- sapply("accept.progov ~ ptot_dev+swacceptcn+(swacceptcn|coal.general)", FUN = function(X) lmer(X, data=dbq))
I got that far, that I can work with the model by further applying sapply, for example, to simulate:
sims <- sapply(X = models , FUN = function(X) sim(X, n=10))
However, now I need to extract the fixef and ranef of sims. By printing models or sims they look fairly like lmer outputs, but they are not. It seems logical that I get such an error message when trying to access fixed effects as with lmer output:
sims@fixef
Error: trying to get slot "fixef" from an object of a basic class ("list") with no slots
class(sims)
[1] "list"
Any idea on how to access the output (or convert it to be able to access it)?
Thanks
Here's the output of sims:
sims
$`accept.progov ~ ptot_dev+swacceptcn+(swacceptcn|coal.general)`
An object of class "sim.merMod"
Slot "fixef":
(Intercept) ptot_dev swacceptcn
[1,] 71.26230 -0.5967700 -5.125157
[2,] 72.31654 -0.3331660 -13.210371
[3,] 72.73718 -0.3910768 -15.319903
[4,] 68.60344 -0.5775278 -10.106682
[5,] 70.36609 -0.3897952 -7.883180
[6,] 70.11542 -0.3413212 -10.959867
[7,] 73.26847 -0.4599989 -10.302523
[8,] 73.46677 -0.4627529 -14.547429
[9,] 69.99146 -0.5947487 -8.681075
[10,] 71.97546 -0.4976680 -10.109415
Slot "ranef":
$coal.general
, , (Intercept)
1 2 3 4 5 6 7 8 9
[1,] -0.3275480720 -10.93724811 12.692639 -3.727188 -0.2119881 1.63602645 1.4972587 -0.4007792 1.354840
[2,] -2.9357382258 -8.47344764 9.832591 -15.602822 -2.0867660 -3.32143496 7.1446528 -7.2902852 10.593827
[3,] -0.5738514837 -6.58777257 7.189278 3.272100 -3.7302182 -2.77115752 4.6410860 -6.9497532 7.013610
[4,] 0.0008799287 -9.42620987 7.733388 -8.888649 -2.7795506 -1.98193393 -3.1739529 2.4603618 1.307669
[5,] 1.5177874134 -10.51052960 10.816926 -4.103975 -8.2232044 0.43857146 4.5353983 -8.1371223 -5.734714
[6,] 0.3591081598 -4.71170518 11.391860 -15.928789 -10.3654403 5.13397114 -1.9557418 3.6573842 7.846707
[7,] -0.1520099025 -9.97569519 5.973820 -6.601445 -5.8213534 -5.97398796 9.1813633 12.0905868 -2.689435
[8,] -3.2966495558 -3.88700417 12.069134 3.972661 -1.3056792 -5.41674684 -0.7940412 3.3800106 6.113203
[9,] 0.9239716129 -0.03016792 -4.695256 -5.092695 -1.4194101 5.82820816 6.7456858 9.4024483 7.683213
[10,] 1.8038318596 -6.69924367 9.612527 -7.118014 -13.3545691 0.03555004 7.5745529 1.6765752 8.020667
, , swacceptcn
1 2 3 4 5 6 7 8 9
[1,] -10.799839 7.400621 3.835463 -7.5630236 -4.112801 -1.108058 -9.648384 -1.729799 -0.5488257
[2,] -4.962062 4.103715 11.493087 6.1079040 -4.432072 6.097044 -5.972890 5.072467 -2.7055490
[3,] -3.831015 0.486487 13.724554 -16.0322440 -5.487974 6.453326 -1.208757 13.072152 -3.1340066
[4,] -3.053745 8.054387 12.682886 2.8787329 3.365597 2.195597 4.271775 5.460537 2.9898383
[5,] -8.098502 4.055499 3.944880 -3.8708456 -14.567725 3.413494 -10.604984 12.821358 7.1130135
[6,] -6.626984 3.892675 7.205407 6.3425843 9.328326 -4.693105 5.304151 11.150812 -3.4270667
[7,] -13.920626 7.548634 9.682934 -5.3058276 -1.991851 4.429253 -16.905243 -10.927869 -2.0806977
[8,] -3.863126 2.470756 9.284932 -20.1617879 -5.352519 8.871024 -1.122215 -1.211589 -0.1492944
[9,] -7.229178 -5.695966 25.527378 -1.7627386 -8.622444 -2.557726 -8.459804 -7.526883 -3.7090101
[10,] -11.098350 3.598449 7.642130 0.2573062 2.701967 5.834333 -14.552764 4.590748 -12.1888232
Slot "sigma":
[1] 11.96711 11.93222 11.93597 11.35270 11.31093 11.23100 11.89647 11.62934 11.61448 11.74406
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30766521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: DeprecationWarning: use options instead of chrome_options error using Brave Browser With Python Selenium and Chromedriver on Windows I want to use Selenium (installed: ver 3.141.0.dist-info) on Python (3.8) which is installed on my Windows 7 64,
I Use Brave Browser Version 1.17.73 Chromium: 87.0.4280.67 (Official Build) (64-bit)
and
Chromedriver (chromedriver_win32-87.0.4280.20) for it,
when running the following Py file which I got the code from here, new Brave browser opens up, but I get errors.
Any solution to make this works?
Appreciate your help.
when running this file:
from selenium import webdriver
driver_path = 'C:/python/Python38/chromedriver.exe'
brave_path = 'C:/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe'
option = webdriver.ChromeOptions()
option.binary_location = brave_path
browser = webdriver.Chrome(executable_path=driver_path, chrome_options=option)
browser.get("https://www.google.es")
get these errors:
c:/Users/mycomp/Desktop/Python/test/getwebdriver.py:12: DeprecationWarning: use options instead of
chrome_options
browser = webdriver.Chrome(executable_path=driver_path, chrome_options=option)
[7132:3952:1127/003249.595:ERROR:os_crypt_win.cc(93)] Failed to decrypt: The parameter is incorrect.
(0x57)
[7132:3952:1127/003249.596:ERROR:brave_sync_prefs.cc(114)] Decrypt sync seed failure
DevTools listening on ws://127.0.0.1:51576/devtools/browser/a048c130-e608-4ec6-a388-ad67fc32d97a
[1127/003250.360:ERROR:gl_surface_egl.cc(773)] EGL Driver message (Error) eglQueryDeviceAttribEXT:
Bad attribute.
[1127/003250.452:ERROR:gl_surface_egl.cc(773)] EGL Driver message (Error) eglQueryDeviceAttribEXT:
Bad attribute.
[1127/003250.455:ERROR:gl_surface_egl.cc(773)] EGL Driver message (Error) eglQueryDeviceAttribEXT:
Bad attribute.
[1127/003250.457:ERROR:gl_surface_egl.cc(773)] EGL Driver message (Error) eglQueryDeviceAttribEXT:
Bad attribute.
[1127/003250.458:ERROR:gl_surface_egl.cc(773)] EGL Driver message (Error) eglQueryDeviceAttribEXT:
Bad attribute.
[1127/003250.711:ERROR:gl_surface_egl.cc(773)] EGL Driver message (Error) eglQueryDeviceAttribEXT:
Bad attribute.
[1127/003250.821:ERROR:gl_surface_egl.cc(773)] EGL Driver message (Error) eglQueryDeviceAttribEXT:
Bad attribute.
[1127/003252.062:ERROR:gl_surface_egl.cc(773)] EGL Driver message (Error) eglQueryDeviceAttribEXT:
Bad attribute.
[1127/003254.498:ERROR:gl_surface_egl.cc(773)] EGL Driver message (Error) eglQueryDeviceAttribEXT:
Bad attribute.
C:\Users\mycomp\Desktop\Python\test>[1127/003304.647:ERROR:gl_surface_egl.cc(773)] EGL Driver message
(Error) eglQueryDeviceAttribEXT: Bad attribute.
Edited:
I found a solution to this from another place, to add the following to the code, but I still get errors, fewer errors
option.add_argument('--disable-gpu')
I run it and got this error:
c:/Users/mycomp/Desktop/Python/test/getwebdriver.py:12: DeprecationWarning:
use options instead of chrome_options
browser = webdriver.Chrome(executable_path=driver_path,
chrome_options=option)
[6208:8532:1127/021046.062:ERROR:os_crypt_win.cc(93)] Failed to decrypt: The
parameter is incorrect. (0x57)
[6208:8532:1127/021046.063:ERROR:brave_sync_prefs.cc(114)] Decrypt sync seed
failure
DevTools listening on ws://127.0.0.1:53262/devtools/browser/adb0a87d-298a-
4b9c-ad00-132a607cb9bd
%20%20browser-with-python-selenium-and-chromedriver
A: The key chrome_options was deprecated sometime back. Instead you have to use options and your effective code block will be:
from selenium import webdriver
driver_path = 'C:/python/Python38/chromedriver.exe'
brave_path = 'C:/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe'
option = webdriver.ChromeOptions()
option.binary_location = brave_path
browser = webdriver.Chrome(executable_path=driver_path, options=option)
browser.get("https://www.google.es")
References
You can find a couple of relevant detailed discussion in:
*
*DeprecationWarning: use options instead of chrome_options error using ChromeDriver and Chrome through Selenium on Windows 10 system
*How to initiate Brave browser using Selenium and Python on Windows
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65029629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Javascript Module pattern and closures I'm trying to get my head around the module pattern in Javascript and have come across various different ways that I can see to do it. What is the difference (if any) between the following:
Person = function() {
return {
//...
}
};
person1 = Person();
function Person2() {
return {
//...
}
}
person2 = Person2();
person3 = function() {
return {
//...
}
}();
person4 = (function() {
return {
// ...
}
})();
person5 = (function() {
return {
// ...
}
}());
They all seem to do the same thing to me.
A: // This creates a function, which then returns an object.
// Person1 isn't available until the assignment block runs.
Person = function() {
return {
//...
}
};
person1 = Person();
// Same thing, different way of phrasing it.
// There are sometimes advantages of the
// two methods, but in this context they are the same.
// Person2 is available at compile time.
function Person2() {
return {
//...
}
}
person2 = Person2();
// This is identical to 'person4'
// In *this* context, the parens aren't needed
// but serve as a tool for whoever reads the code.
// (In other contexts you do need them.)
person3 = function() {
return {
//...
}
}();
// This is a short cut to create a function and then execute it,
// removing the need for a temporary variable.
// This is called the IIFE (Immediate Invoked Function Expression)
person4 = (function() {
return {
// ...
}
})();
// Exactly the same as Person3 and Person4 -- Explained below.
person5 = (function() {
return {
// ...
}
}());
In the contexts above,
*
*= function() {}();
*= (function() {}());
*= (function() {})();
All do exactly the same thing.
I'll break them down.
function() {}();
<functionExpression>(); // Call a function expression.
(<functionExpression>()); // Wrapping it up in extra parens means nothing.
// Nothing more than saying (((1))) + (((2)))
(<functionExpression>)();
// We already know the extra parens means nothing, so remove them and you get
<functionExpression>(); // Which is the same as case1
Now, all of that said == why do you sometimes need parens?
Because this is a *function statement)
function test() {};
In order to make a function expression, you need some kind of operator before it.
(function test() {})
!function test() {}
+function test() {}
all work.
By standardizing on the parens, we are able to:
*
*Return a value out of the IIFE
*Use a consistent way to let the reader of the code know it is an IIFE, not a regular function.
A: The first two aren't a module pattern, but a factory function - there is a Person "constructor" that can be invoked multiple times. For the semantic difference see var functionName = function() {} vs function functionName() {}.
The other three are IIFEs, which all do exactly the same thing. For the syntax differences, see Explain the encapsulated anonymous function syntax and Location of parenthesis for auto-executing anonymous JavaScript functions?.
A: I've found a extremely detail page explaining this kind of stuff
Sth called IIFE
Hope will help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25325019",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Trouble With Classes and Functions I'm basically writing a module for a basic pygame drawing app. im using a Tk window to get the three color values for a custom color. i have a file that opens a Tk window and askes for 3 color values made but i cant figure how to get it all to work well and im starting to get confused
Here is my code for the Tk window:
from Tkinter import *
class Custom():
def get_color(self):
root = Tk()
root.configure(background='black')
root.wm_title("Custom")
label1 = Label(root, text='Red Value:',bg="black", fg="white")
label1.grid(row=2, column=0,columnspan=2)
enter1 = Entry(root, bg='white')
enter1.grid(row=3, column=0,columnspan=2)
label2 = Label(root, text='Green Value:',bg="black", fg="white")
label2.grid(row=4, column=0,columnspan=2)
enter2 = Entry(root, bg='white')
enter2.grid(row=5, column=0, columnspan=2)
label3 = Label(root, text='Blue Value:',bg="black", fg="white")
label3.grid(row=6, column=0,columnspan=2)
enter3 = Entry(root, bg='white')
enter3.grid(row=7, column=0, columnspan=2)
btn1 = Button(root, text='OK', command= self.return_color, bg="black",activebackground="green", fg="white")
btn1.grid(row=14, column=0, columnspan=2)
label7 = Label(root, bg="black", fg = "white")
label7.grid(row=15, column=0, columnspan=2)
enter1.focus()
root.mainloop()
def return_color(self):
try:
r = str(self.enter1.get())
g = str(self.enter2.get())
b = str(self.enter3.get())
except ValueError:
window.label7.config(text='Enter Numbers!', fg = "red")
root.destroy()
return (r,g,b)
c = Custom()
c.get_color()
it works but im trying to be able to import it so i made two functions and put them in a class but now im getting confused i need to run get_color then when i click the OK button i need to run return_color i dont know if this is the way to do it ive just been trying all kinds of differnt things its saying that return_color cant get the self.enter1.get() same with enter2 and 3
here is where im giving to my draw pad program:
if key[pygame.K_c]:
import CustomColor
c = CustomColor.Custom()
c.get_color()
self.color = c.return_color()
im starting to get really confused if someone could clear this all up i would be so thank ful!!
A: The problem is that the return value of return_color is not used, since the reference to the function passed as a command option is used to call it but not to store the result. What you can do is to store the values as attributes of the class in return_color and add a return statement in get_color after the call to start the mainloop:
def get_color()
# Initialize the attributes with a default value
self.r = ''
self.g = ''
self.b = ''
# ...
root.mainloop()
return self.r, self.g, self.b
def return_color(self):
# Entry.get returns a string, don't need to call to str()
self.r = self.enter1.get()
self.g = self.enter2.get()
self.b = self.enter3.get()
root.destroy()
Before using the color, you can check that the format is correct. Then I suggest you to rename the functions with more meaningful names; and create a Tk element, withdraw it and use a Toplevel in your class (if you create more than one Custom object, you are actually creating multiple Tk elements, and that's something which should be avoided).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16877242",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: remove laravel cache by asterix I create cache like this:
@foreach ($menu->items as $key => $item)
<div class="{{ $itemclass or 'menu-item'}}">
@switch($item->type)
@case("CustomUrlItem")
<a href="{{ $item->meta }}">{{ $item->title }}</a>
@break
@case("PageItem")
@php
$page = Cache::rememberForever('menu-item-'.$item->meta, function() use($item) {
return Content::find($item->meta);
});
@endphp
<a href="{{ $page->slug }}">{{ $item->title }}</a>
@break
@endswitch
</div>
@endforeach
if we focus specifically on this part:
@case("PageItem")
@php
$page = Cache::rememberForever('menu-item-'.$item->meta, function() use($item) {
return Content::find($item->meta);
});
@endphp
<a href="{{ $page->slug }}">{{ $item->title }}</a>
@break
When I want to remove cache for all 'menu-item-*' how could I do that.
Right now if I want to remove cache for menu-item-*
Cache::forget('menu-item-1');
Cache::forget('menu-item-2');
Cache::forget('menu-item-3');
I would have to iterate through all of menu-item-1, menu-item-2 etc to remove them? Could I do something like this instead:
Cache::forget('menu-item-*');
And that would wipe out all of menu-item-* cache?
I am using Laravel 5.6 and file driver to save cached items.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49102614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: React memo prevProps is giving initial value always, not actual previous props Main component:
const AProfileFilter = ({ data = []) => {
const [getData, setData] = useState([]);
const [getStore, setStore] = useState([]);
useEffect(() => {
setData(prepareFilterData(data));
}, [data]);
useEffect(() => {
setStore({ "addMoreOptions": getData.filter((flr) => flr.isShow === false), "displayFields": getData.filter((flr) => flr.isShow === true) })
}, [getData]);
// AProfileFilter logic here
// (getStore) addMoreOptions state will be update based on some condition.
return <ASelect defaultValues={getStore.addMoreOptions}>
}
export default ZListingProfileFilter;
Sub Component:
const ASelect = (props) => {
// ASelect logic here
}
function areEqual(prevProps, nextProps) {
console.log("prevProps > ",prevProps.defaultValues, "nextProps > ",nextProps.defaultValues);
return _.isEqual(prevProps.defaultValues, nextProps.defaultValues);
}
export default memo(ASelect, areEqual);
Current Result:
Expected Result:
*
*Initially it fine to have (Blank Array) [] and then update it to (Filled Array) [{...}]
*Second time I want previous should be (Filled Array) [{...}] and update one should be (Blank Array) [], because I have made it as blank from AProfileFilter component.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66345959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to share a common object between separate solutions while they still need same Having trouble serializing object from one C# solution, then persisting it and picking it up with another solution, and then de-serializing directly to the same object type in a different solution.
When transferring the object to it's persisted location, it also persists it's object type with the original namespace, which is obviously different that the namespace for the shared common object that I am trying to re-de/serialize it to because they are different solutions (even though the class is the same with the same properties and same name).
Sharing classes, referencing common class, and/or linking classes doesn't seem to be the solution (unless I am doing it incorrectly), because when it picks it back up it still sees the parent namespace as different since they are from different solutions, so it gives an error when trying to de-serialize it because it thinks it is a different type.
Reason - for being able to directly de-serialize it into it's original object type but in a different project's solution.
Any insight or advice is appreciated. Thank you
Environment: Visual Studio 2015, .NET Core, C# (Testing in console app)
A: You can either create a class library and share it between projects or you can serialize the object to JSON and have equivalent classes on each side.
You don't mention what mechanism you are using to serialize but I am assuming it's a binary serialization you are using. If binary serialization is required a class library that is shared is your best choice.
A: Create Class Library(for .Net Core) project. Create there classes (or interfaces or something else you want to share) you want to transfer among projects.
Then add reference to that library in every project that needs that class. Add using directive with library namespace and you can use these classes.
A: If you don't want to share classes, or if you need another options, then you can use Serializatoin/Deserialization mechanisms that doesn't care about the original type, but rather for it compatibility with the Data. Like Json.Net by default.
Serialization in one solution:
var jsonSerializedString = JsonConvert.SerializeObject(myObjectInAssemblyA);
Deserialization in the other solution:
objectInAssemblyB = JsonConvert.DeserializeObject<ObjectClassName>(jsonSerializedString);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41766659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Code to make div appear after a certain amount of time I'm looking for code that makes a div appear after a certain amount of time on a site. Here's the sort of thing I'm talking about:
<div class="container">
<div class="secretpopout">
This is the div I want to pop out after a couple of minutes.
</div>
</div>
I'm relatively new to javascript and jQuery, but I'm assuming I will need to use the setTimeout or something similar. I've tried finding the answer online, but if someone could explain it in a way a designer (as opposed to a programmer) would get it, that would be great - ANY LIGHT shed on this would be greatly appreciated.
Thank you.
A: You can do this with very little code in jQuery 1.4+ using .delay(), like this:
$(function() {
$(".secretpopout").delay(120000).fadeIn();
});
This would show it after 2 minutes, just give it some CSS so it's hidden initially:
.secretpopout { display: none; }
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2567832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Ruby: Should strings in a frozen array also be individually frozen? Ruby 2.2.3, Rails 4.2.1
I have a large number of arrays of strings that I define as constants for use throughout an application. They are various sets of ISO country codes, language codes, that sort of thing, so two to four characters, numbered in the hundreds of unique values each.
The different arrays are collections of these, so NORTH_AMERICA_COUNTRY_CODES might be an array of a dozen of so country codes, AFRICA_COUNTRY_CODES might be an array of around 60. Many of them overlap (various versions of the Commonwealth countries, for example).
The arrays are used in comparison with other arbitrary arrays of country codes for logic such as "Subtract this list of countries from Africa".
So I'm wondering whether, when I generate these constants, I ought to freeze the strings within the arrays, so instead of:
WORLD_COUNTRIES = Countries.pluck(:country_code).freeze
... maybe ...
WORLD_COUNTRIES = Countries.pluck(:country_code).map{|c| c.freeze}.freeze
Is there a way of quantifying the potential benefits?
I considered using arrays of symbols instead of arrays of strings, but the arbitrary arrays that these are used with are stored in PostgreSQL text arrays, and it seems like I'd need to serialise those columns instead, or maybe override the getter and setter methods to change the values between arrays of strings and arrays of symbols. Ugh.
Edit
Testing results, in which I've attempted to benchmark three situations:
*
*Comparing a frozen array of unfrozen strings with an unfrozen array of unfrozen strings
*Comparing a frozen array of frozen strings with an unfrozen array of unfrozen strings
*Comparing a frozen array of symbols with an unfrozen array of symbols (in case I bit the bullet and went all symbolic on this).
Any thoughts on methodology or interpretation gratefully received. I'm not sure whether the similarity in results between the first two indicates that they are in all respects the same, but I'd be keen on anything that can directly point to differences in memory allocation.
Script:
require 'benchmark'
country_list = ["AD", "AE", "AF", "AG", "AI", "AL", "AM", "AN", "AO", "AQ", "AR", "AS", "AT", "AU", "AW", "AX", "AZ", "BA", "BB", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BL", "BM", "BN", "BO", "BQ", "BR", "BS", "BT", "BV", "BW", "BY", "BZ", "CA", "CC", "CD", "CF", "CG", "CH", "CI", "CK", "CL", "CM", "CN", "CO", "CR", "CS", "CU", "CV", "CW", "CX", "CY", "CZ", "DE", "DJ", "DK", "DM", "DO", "DZ", "EC", "EE", "EG", "EH", "ER", "ES", "ET", "FI", "FJ", "FK", "FM", "FO", "FR", "GA", "GB", "GD", "GE", "GF", "GG", "GH", "GI", "GL", "GM", "GN", "GP", "GQ", "GR", "GS", "GT", "GU", "GW", "GY", "HK", "HM", "HN", "HR", "HT", "HU", "ID", "IE", "IL", "IM", "IN", "IO", "IQ", "IR", "IS", "IT", "JE", "JM", "JO", "JP", "KE", "KG", "KH", "KI", "KM", "KN", "KP", "KR", "KW", "KY", "KZ", "LA", "LB", "LC", "LI", "LK", "LR", "LS", "LT", "LU", "LV", "LY", "MA", "MC", "MD", "ME", "MF", "MG", "MH", "MK", "ML", "MM", "MN", "MO", "MP", "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA", "NC", "NE", "NF", "NG", "NI", "NL", "NO", "NP", "NR", "NU", "NZ", "OM", "PA", "PE", "PF", "PG", "PH", "PK", "PL", "PM", "PN", "PR", "PS", "PT", "PW", "PY", "QA", "RE", "RO", "RS", "RU", "RW", "SA", "SB", "SC", "SD", "SE", "SG", "SH", "SI", "SJ", "SK", "SL", "SM", "SN", "SO", "SR", "SS", "ST", "SV", "SX", "SY", "SZ", "TC", "TD", "TF", "TG", "TH", "TJ", "TK", "TL", "TM", "TN", "TO", "TR", "TT", "TV", "TW", "TZ", "UA", "UG", "UM", "US", "UY", "UZ", "VA", "VC", "VE", "VG", "VI", "VN", "VU", "WF", "WS", "YE", "YT", "YU", "ZA", "ZM", "ZW"]
FROZEN_ARRAY = country_list.dup.freeze
puts FROZEN_ARRAY.size
FROZEN_ARRAY_AND_STRINGS = country_list.dup.map{|x| x.freeze}.freeze
FROZEN_ARRAY_AND_SYMBOLS = country_list.dup.map{|x| x.to_sym}.freeze
comp_s = %w(AD AT BE CY EE FI FR DE ES GR IE IT LU LV MC ME MT NL PT SI SK SM VA)
comp_sym = %w(AD AT BE CY EE FI FR DE ES GR IE IT LU LV MC ME MT NL PT SI SK SM VA).map{|x| x.to_sym}
Benchmark.bm do |x|
x.report("frozen string" ) { 10000.times {|i| c = (FROZEN_ARRAY_AND_STRINGS & comp_s.dup) }}
x.report("unfrozen string") { 10000.times {|i| c = (FROZEN_ARRAY & comp_s.dup) }}
x.report("symbols" ) { 10000.times {|i| c = (FROZEN_ARRAY_AND_SYMBOLS & comp_sym.dup) }}
end
Benchmark.bmbm do |x|
x.report("frozen string" ) { 10000.times {|i| c = (FROZEN_ARRAY_AND_STRINGS & comp_s.dup) }}
x.report("unfrozen string") { 10000.times {|i| c = (FROZEN_ARRAY & comp_s.dup) }}
x.report("symbols" ) { 10000.times {|i| c = (FROZEN_ARRAY_AND_SYMBOLS & comp_sym.dup) }}
end
Result:
2.2.3 :001 > require 'benchmark'
=> false
2.2.3 :002 >
2.2.3 :003 > country_list = ["AD", "AE", "AF", "AG", "AI", "AL", "AM", "AN", "AO", "AQ", "AR", "AS", "AT", "AU", "AW", "AX", "AZ", "BA", "BB", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BL", "BM", "BN", "BO", "BQ", "BR", "BS", "BT", "BV", "BW", "BY", "BZ", "CA", "CC", "CD", "CF", "CG", "CH", "CI", "CK", "CL", "CM", "CN", "CO", "CR", "CS", "CU", "CV", "CW", "CX", "CY", "CZ", "DE", "DJ", "DK", "DM", "DO", "DZ", "EC", "EE", "EG", "EH", "ER", "ES", "ET", "FI", "FJ", "FK", "FM", "FO", "FR", "GA", "GB", "GD", "GE", "GF", "GG", "GH", "GI", "GL", "GM", "GN", "GP", "GQ", "GR", "GS", "GT", "GU", "GW", "GY", "HK", "HM", "HN", "HR", "HT", "HU", "ID", "IE", "IL", "IM", "IN", "IO", "IQ", "IR", "IS", "IT", "JE", "JM", "JO", "JP", "KE", "KG", "KH", "KI", "KM", "KN", "KP", "KR", "KW", "KY", "KZ", "LA", "LB", "LC", "LI", "LK", "LR", "LS", "LT", "LU", "LV", "LY", "MA", "MC", "MD", "ME", "MF", "MG", "MH", "MK", "ML", "MM", "MN", "MO", "MP", "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA", "NC", "NE", "NF", "NG", "NI", "NL", "NO", "NP", "NR", "NU", "NZ", "OM", "PA", "PE", "PF", "PG", "PH", "PK", "PL", "PM", "PN", "PR", "PS", "PT", "PW", "PY", "QA", "RE", "RO", "RS", "RU", "RW", "SA", "SB", "SC", "SD", "SE", "SG", "SH", "SI", "SJ", "SK", "SL", "SM", "SN", "SO", "SR", "SS", "ST", "SV", "SX", "SY", "SZ", "TC", "TD", "TF", "TG", "TH", "TJ", "TK", "TL", "TM", "TN", "TO", "TR", "TT", "TV", "TW", "TZ", "UA", "UG", "UM", "US", "UY", "UZ", "VA", "VC", "VE", "VG", "VI", "VN", "VU", "WF", "WS", "YE", "YT", "YU", "ZA", "ZM", "ZW"]
=> ["AD", "AE", "AF", "AG", "AI", "AL", "AM", "AN", "AO", "AQ", "AR", "AS", "AT", "AU", "AW", "AX", "AZ", "BA", "BB", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BL", "BM", "BN", "BO", "BQ", "BR", "BS", "BT", "BV", "BW", "BY", "BZ", "CA", "CC", "CD", "CF", "CG", "CH", "CI", "CK", "CL", "CM", "CN", "CO", "CR", "CS", "CU", "CV", "CW", "CX", "CY", "CZ", "DE", "DJ", "DK", "DM", "DO", "DZ", "EC", "EE", "EG", "EH", "ER", "ES", "ET", "FI", "FJ", "FK", "FM", "FO", "FR", "GA", "GB", "GD", "GE", "GF", "GG", "GH", "GI", "GL", "GM", "GN", "GP", "GQ", "GR", "GS", "GT", "GU", "GW", "GY", "HK", "HM", "HN", "HR", "HT", "HU", "ID", "IE", "IL", "IM", "IN", "IO", "IQ", "IR", "IS", "IT", "JE", "JM", "JO", "JP", "KE", "KG", "KH", "KI", "KM", "KN", "KP", "KR", "KW", "KY", "KZ", "LA", "LB", "LC", "LI", "LK", "LR", "LS", "LT", "LU", "LV", "LY", "MA", "MC", "MD", "ME", "MF", "MG", "MH", "MK", "ML", "MM", "MN", "MO", "MP", "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA", "NC", "NE", "NF", "NG", "NI", "NL", "NO", "NP", "NR", "NU", "NZ", "OM", "PA", "PE", "PF", "PG", "PH", "PK", "PL", "PM", "PN", "PR", "PS", "PT", "PW", "PY", "QA", "RE", "RO", "RS", "RU", "RW", "SA", "SB", "SC", "SD", "SE", "SG", "SH", "SI", "SJ", "SK", "SL", "SM", "SN", "SO", "SR", "SS", "ST", "SV", "SX", "SY", "SZ", "TC", "TD", "TF", "TG", "TH", "TJ", "TK", "TL", "TM", "TN", "TO", "TR", "TT", "TV", "TW", "TZ", "UA", "UG", "UM", "US", "UY", "UZ", "VA", "VC", "VE", "VG", "VI", "VN", "VU", "WF", "WS", "YE", "YT", "YU", "ZA", "ZM", "ZW"]
2.2.3 :004 > FROZEN_ARRAY = country_list.dup.freeze
=> ["AD", "AE", "AF", "AG", "AI", "AL", "AM", "AN", "AO", "AQ", "AR", "AS", "AT", "AU", "AW", "AX", "AZ", "BA", "BB", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BL", "BM", "BN", "BO", "BQ", "BR", "BS", "BT", "BV", "BW", "BY", "BZ", "CA", "CC", "CD", "CF", "CG", "CH", "CI", "CK", "CL", "CM", "CN", "CO", "CR", "CS", "CU", "CV", "CW", "CX", "CY", "CZ", "DE", "DJ", "DK", "DM", "DO", "DZ", "EC", "EE", "EG", "EH", "ER", "ES", "ET", "FI", "FJ", "FK", "FM", "FO", "FR", "GA", "GB", "GD", "GE", "GF", "GG", "GH", "GI", "GL", "GM", "GN", "GP", "GQ", "GR", "GS", "GT", "GU", "GW", "GY", "HK", "HM", "HN", "HR", "HT", "HU", "ID", "IE", "IL", "IM", "IN", "IO", "IQ", "IR", "IS", "IT", "JE", "JM", "JO", "JP", "KE", "KG", "KH", "KI", "KM", "KN", "KP", "KR", "KW", "KY", "KZ", "LA", "LB", "LC", "LI", "LK", "LR", "LS", "LT", "LU", "LV", "LY", "MA", "MC", "MD", "ME", "MF", "MG", "MH", "MK", "ML", "MM", "MN", "MO", "MP", "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA", "NC", "NE", "NF", "NG", "NI", "NL", "NO", "NP", "NR", "NU", "NZ", "OM", "PA", "PE", "PF", "PG", "PH", "PK", "PL", "PM", "PN", "PR", "PS", "PT", "PW", "PY", "QA", "RE", "RO", "RS", "RU", "RW", "SA", "SB", "SC", "SD", "SE", "SG", "SH", "SI", "SJ", "SK", "SL", "SM", "SN", "SO", "SR", "SS", "ST", "SV", "SX", "SY", "SZ", "TC", "TD", "TF", "TG", "TH", "TJ", "TK", "TL", "TM", "TN", "TO", "TR", "TT", "TV", "TW", "TZ", "UA", "UG", "UM", "US", "UY", "UZ", "VA", "VC", "VE", "VG", "VI", "VN", "VU", "WF", "WS", "YE", "YT", "YU", "ZA", "ZM", "ZW"]
2.2.3 :005 > puts FROZEN_ARRAY.size
252
=> nil
2.2.3 :006 > FROZEN_ARRAY_AND_STRINGS = country_list.dup.map{|x| x.freeze}.freeze
=> ["AD", "AE", "AF", "AG", "AI", "AL", "AM", "AN", "AO", "AQ", "AR", "AS", "AT", "AU", "AW", "AX", "AZ", "BA", "BB", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BL", "BM", "BN", "BO", "BQ", "BR", "BS", "BT", "BV", "BW", "BY", "BZ", "CA", "CC", "CD", "CF", "CG", "CH", "CI", "CK", "CL", "CM", "CN", "CO", "CR", "CS", "CU", "CV", "CW", "CX", "CY", "CZ", "DE", "DJ", "DK", "DM", "DO", "DZ", "EC", "EE", "EG", "EH", "ER", "ES", "ET", "FI", "FJ", "FK", "FM", "FO", "FR", "GA", "GB", "GD", "GE", "GF", "GG", "GH", "GI", "GL", "GM", "GN", "GP", "GQ", "GR", "GS", "GT", "GU", "GW", "GY", "HK", "HM", "HN", "HR", "HT", "HU", "ID", "IE", "IL", "IM", "IN", "IO", "IQ", "IR", "IS", "IT", "JE", "JM", "JO", "JP", "KE", "KG", "KH", "KI", "KM", "KN", "KP", "KR", "KW", "KY", "KZ", "LA", "LB", "LC", "LI", "LK", "LR", "LS", "LT", "LU", "LV", "LY", "MA", "MC", "MD", "ME", "MF", "MG", "MH", "MK", "ML", "MM", "MN", "MO", "MP", "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA", "NC", "NE", "NF", "NG", "NI", "NL", "NO", "NP", "NR", "NU", "NZ", "OM", "PA", "PE", "PF", "PG", "PH", "PK", "PL", "PM", "PN", "PR", "PS", "PT", "PW", "PY", "QA", "RE", "RO", "RS", "RU", "RW", "SA", "SB", "SC", "SD", "SE", "SG", "SH", "SI", "SJ", "SK", "SL", "SM", "SN", "SO", "SR", "SS", "ST", "SV", "SX", "SY", "SZ", "TC", "TD", "TF", "TG", "TH", "TJ", "TK", "TL", "TM", "TN", "TO", "TR", "TT", "TV", "TW", "TZ", "UA", "UG", "UM", "US", "UY", "UZ", "VA", "VC", "VE", "VG", "VI", "VN", "VU", "WF", "WS", "YE", "YT", "YU", "ZA", "ZM", "ZW"]
2.2.3 :007 > FROZEN_ARRAY_AND_SYMBOLS = country_list.dup.map{|x| x.to_sym}.freeze
=> [:AD, :AE, :AF, :AG, :AI, :AL, :AM, :AN, :AO, :AQ, :AR, :AS, :AT, :AU, :AW, :AX, :AZ, :BA, :BB, :BD, :BE, :BF, :BG, :BH, :BI, :BJ, :BL, :BM, :BN, :BO, :BQ, :BR, :BS, :BT, :BV, :BW, :BY, :BZ, :CA, :CC, :CD, :CF, :CG, :CH, :CI, :CK, :CL, :CM, :CN, :CO, :CR, :CS, :CU, :CV, :CW, :CX, :CY, :CZ, :DE, :DJ, :DK, :DM, :DO, :DZ, :EC, :EE, :EG, :EH, :ER, :ES, :ET, :FI, :FJ, :FK, :FM, :FO, :FR, :GA, :GB, :GD, :GE, :GF, :GG, :GH, :GI, :GL, :GM, :GN, :GP, :GQ, :GR, :GS, :GT, :GU, :GW, :GY, :HK, :HM, :HN, :HR, :HT, :HU, :ID, :IE, :IL, :IM, :IN, :IO, :IQ, :IR, :IS, :IT, :JE, :JM, :JO, :JP, :KE, :KG, :KH, :KI, :KM, :KN, :KP, :KR, :KW, :KY, :KZ, :LA, :LB, :LC, :LI, :LK, :LR, :LS, :LT, :LU, :LV, :LY, :MA, :MC, :MD, :ME, :MF, :MG, :MH, :MK, :ML, :MM, :MN, :MO, :MP, :MQ, :MR, :MS, :MT, :MU, :MV, :MW, :MX, :MY, :MZ, :NA, :NC, :NE, :NF, :NG, :NI, :NL, :NO, :NP, :NR, :NU, :NZ, :OM, :PA, :PE, :PF, :PG, :PH, :PK, :PL, :PM, :PN, :PR, :PS, :PT, :PW, :PY, :QA, :RE, :RO, :RS, :RU, :RW, :SA, :SB, :SC, :SD, :SE, :SG, :SH, :SI, :SJ, :SK, :SL, :SM, :SN, :SO, :SR, :SS, :ST, :SV, :SX, :SY, :SZ, :TC, :TD, :TF, :TG, :TH, :TJ, :TK, :TL, :TM, :TN, :TO, :TR, :TT, :TV, :TW, :TZ, :UA, :UG, :UM, :US, :UY, :UZ, :VA, :VC, :VE, :VG, :VI, :VN, :VU, :WF, :WS, :YE, :YT, :YU, :ZA, :ZM, :ZW]
2.2.3 :008 > comp_s = %w(AD AT BE CY EE FI FR DE ES GR IE IT LU LV MC ME MT NL PT SI SK SM VA)
=> ["AD", "AT", "BE", "CY", "EE", "FI", "FR", "DE", "ES", "GR", "IE", "IT", "LU", "LV", "MC", "ME", "MT", "NL", "PT", "SI", "SK", "SM", "VA"]
2.2.3 :009 > comp_sym = %w(AD AT BE CY EE FI FR DE ES GR IE IT LU LV MC ME MT NL PT SI SK SM VA).map{|x| x.to_sym}
=> [:AD, :AT, :BE, :CY, :EE, :FI, :FR, :DE, :ES, :GR, :IE, :IT, :LU, :LV, :MC, :ME, :MT, :NL, :PT, :SI, :SK, :SM, :VA]
2.2.3 :010 >
2.2.3 :011 >
2.2.3 :012 > Benchmark.bm do |x|
2.2.3 :013 > x.report("frozen string" ) { 10000.times {|i| c = (FROZEN_ARRAY_AND_STRINGS & comp_s.dup) }}
2.2.3 :014?> x.report("unfrozen string") { 10000.times {|i| c = (FROZEN_ARRAY & comp_s.dup) }}
2.2.3 :015?> x.report("symbols" ) { 10000.times {|i| c = (FROZEN_ARRAY_AND_SYMBOLS & comp_sym.dup) }}
2.2.3 :016?> end
user system total real
frozen string 0.190000 0.000000 0.190000 ( 0.194141)
unfrozen string 0.170000 0.010000 0.180000 ( 0.174675)
symbols 0.080000 0.000000 0.080000 ( 0.081507)
=> [#<Benchmark::Tms:0x007f810c3aca70 @label="frozen string", @real=0.1941408810671419, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.1899999999999995, @total=0.1899999999999995>, #<Benchmark::Tms:0x007f810c82b538 @label="unfrozen string", @real=0.1746752569451928, @cstime=0.0, @cutime=0.0, @stime=0.010000000000000009, @utime=0.16999999999999993, @total=0.17999999999999994>, #<Benchmark::Tms:0x007f810af2cfa0 @label="symbols", @real=0.08150708093307912, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.08000000000000007, @total=0.08000000000000007>]
2.2.3 :017 >
2.2.3 :018 >
2.2.3 :019 > Benchmark.bmbm do |x|
2.2.3 :020 > x.report("frozen string" ) { 10000.times {|i| c = (FROZEN_ARRAY_AND_STRINGS & comp_s.dup) }}
2.2.3 :021?> x.report("unfrozen string") { 10000.times {|i| c = (FROZEN_ARRAY & comp_s.dup) }}
2.2.3 :022?> x.report("symbols" ) { 10000.times {|i| c = (FROZEN_ARRAY_AND_SYMBOLS & comp_sym.dup) }}
2.2.3 :023?> end
Rehearsal ---------------------------------------------------
frozen string 0.180000 0.000000 0.180000 ( 0.183846)
unfrozen string 0.200000 0.000000 0.200000 ( 0.196311)
symbols 0.080000 0.000000 0.080000 ( 0.082794)
------------------------------------------ total: 0.460000sec
user system total real
frozen string 0.160000 0.000000 0.160000 ( 0.167051)
unfrozen string 0.170000 0.000000 0.170000 ( 0.171601)
symbols 0.080000 0.000000 0.080000 ( 0.078746)
=> [#<Benchmark::Tms:0x007f811022a388 @label="frozen string", @real=0.1670510449912399, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.16000000000000014, @total=0.16000000000000014>, #<Benchmark::Tms:0x007f811022a4c8 @label="unfrozen string", @real=0.17160122003406286, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.16999999999999993, @total=0.16999999999999993>, #<Benchmark::Tms:0x007f8108eb1c58 @label="symbols", @real=0.07874645793344826, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.08000000000000007, @total=0.08000000000000007>]
2.2.3 :024 >
2.2.3 :025 >
2.2.3 :026 >
A: Since you're dealing with a small number of values, and since the performance benefits of symbols are evident from your testing, just go with symbols.
BTW, you can use map(&:to_sym) instead of map {|x| x.to_sym}.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33777440",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Getting fonts, sizes, bold,...etc I'm having trouble finding stuff on accessing Windows fonts or predefined fonts, and sizes. So for my java program I have a JComboBox with fonts, sizes, and colors. The problem is that I need to pre-Enter the fonts, sizes and colors. How would I be able to get the predefined fonts, colors, and sizes? So far this is what I have for this font but its not in the correct way.
if (font.equals("Arial")) {
if (size.equals("8")) {
setSize = 8;
} else if (size.equals("10")) {
setSize = 10;
} else if (size.equals("12")) {
setSize = 12;
}
if (color.equals("Black")) {
setColor = Color.BLACK;
} else if (color.equals("Blue")) {
setColor = Color.BLUE;
} else if (color.equals("Red")) {
setColor = Color.red;
}
Font font = new Font("Arial", setAttribute, setSize);
Writer.setFont(font);
Writer.setForeground(setColor);
A: GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fonts = ge.getAvailableFontFamilyNames();
The sizes and styles can be set at run-time.
E.G.
import java.awt.*;
import javax.swing.*;
public class ShowFonts {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fonts = ge.getAvailableFontFamilyNames();
JComboBox fontChooser = new JComboBox(fonts);
fontChooser.setRenderer(new FontCellRenderer());
JOptionPane.showMessageDialog(null, fontChooser);
});
}
}
class FontCellRenderer extends DefaultListCellRenderer {
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
JLabel label = (JLabel)super.getListCellRendererComponent(
list,value,index,isSelected,cellHasFocus);
Font font = new Font(value.toString(), Font.PLAIN, 20);
label.setFont(font);
return label;
}
}
JavaDoc
The JDoc for GraphicsEnvironment.getAvailableFontFamilyNames() state in part..
Returns an array containing the names of all font families in this GraphicsEnvironment localized for the default locale, as returned by Locale.getDefault()..
See also:
getAllFonts()..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6965038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Accept parameters of URL in .NET CORE I'm new in .NET CORE and I would like if its possible to change the default format for request urls. Let me explain. I have two get method on a controller for get a list and get info of 1 element
[Route("api/[controller]/")]
[ApiController]
public class Department : ControllerBase
{
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
[HttpGet("{id:int}")]
public string GetDepartamento(int id)
{
return "value";
}
[HttpPost]
public void Post([FromBody] string value)
{
}
}
}
In order to call these resource u use
https://localhost:44309/api/department
https://localhost:44309/api/department/1
But I need to use this format not just for this controller but all the controllers
GET:https://localhost:44309/api/department
GET:https://localhost:44309/api/department?id=1
POST:https://localhost:44309/api/department (data on the body of http call)
PUT:https://localhost:44309/api/department?id=1 (data on the body of http call)
DELETE:https://localhost:44309/api/department?id=1
I'm working over a new project (.net core web application MVC)so Startup and Program files were not modified.
A:
I have two get method on a controller for get a list and get info of 1 element
I need to use this format
GET:https://localhost:44309/api/department
GET:https://localhost:44309/api/department?id=1
If you'd like to match request(s) to expected action(s) based on the query string, you can try to implement a custom ActionMethodSelectorAttribute and apply it to your actions, like below.
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class CheckQueryStingAttribute : ActionMethodSelectorAttribute
{
public string QueryStingName { get; set; }
public bool CanPass { get; set; }
public CheckQueryStingAttribute(string qname, bool canpass)
{
QueryStingName = qname;
CanPass = canpass;
}
public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action)
{
StringValues value;
routeContext.HttpContext.Request.Query.TryGetValue(QueryStingName, out value);
if (QueryStingName == "" && CanPass)
{
return true;
}
else
{
if (CanPass)
{
return !StringValues.IsNullOrEmpty(value);
}
return StringValues.IsNullOrEmpty(value);
}
}
}
Apply it to actions
[HttpGet]
[CheckQuerySting("id", false)]
[CheckQuerySting("", true)]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
[HttpGet]
[CheckQuerySting("id", true)]
[CheckQuerySting("", false)]
public string GetDepartamento(int id)
{
return "value";
}
Test Result
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64251829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Save and call random variables I'm attempting to have my code create a number of random values, save those values, then allow me to manipulate those random values to create a number of profiles.
I'm currently having issues with both saving the numbers and with global and local values.
I have tried this so far:
import random
HP = random.randint(30,70)
Strength = random.randint (30,70)
M_HP = random.randint(30,70)-10
M_Strength = random.randint (30,70)-10
def pilot_print():
print ("Your pilot HP is " +str(HP))
print ("Your pilot Strength is " +str(Strength))
def mech_print():
print ("Your Mech HP is " +str(M_HP))
print ("Your Mech Strength is " +str(M_Strength))
My issue is that I'm also attempting to put something like
def combine():
HP+(M_HP/2) = C_HP
Strength+(M_Strength/2) = C_Strength
My aim is to eventually create a game with character profiles generated randomly.
Would anyone be kind enough to point me in the right direction?
Thank you
A:
I'm attempting to have my code create a number of random values, save those values, then allow me to manipulate those random values to create a number of profiles
This is, in general, wrong approach. Right one is to have RNG internal state saved, so then after restoring it you'll get the same sequence of random numbers
Along the lines:
import random
state = random.getstate()
# save it, pickle it, ...
...
# restore state, unpickle it, ...
random.setstate(state)
# call to random.randint() will produce controllable sequence of numbers
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50862710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Dynamically create a class inherited from neomodel.StructuredNode Python's library neomodel provides the ability to define a relationship with a class that hasn't been defined yet, by using its name as string, which works fine as follows:
from neomodel import StructuredNode, RelationshipTo
# if Foo is already defined
class Bar (structuredNode):
rel = RelationshipTo(Foo, 'REL')
# if Foo isn't defined
class Bar(StructuredNode):
rel = RelationshipTo('Foo', 'REL')
I want to create a class in the runtime and provide it with the attribute RelationshipTo, which should make a relationship with undefined yet class, so I did:
Bar = type('Bar', (StructuredNode,), {'rel': RelationshipTo('Foo', 'REL')})
In some point in the runtime later, I define Foo:
Foo = type('Foo', (StructuredNode,), {})
Now if I want to use the class I've just made:
bar = Bar()
The next error still pops up as if I haven't defined Foo:
AttributeError: module '_pydevd_bundle.pydevd_exec2' has no attribute
'Foo'
Note: This error doesn't appear if I at least define Bar statically (not in the runtime)
Would someone explain why that happens and how to define them properly in runtime, please?
I appreciate any help!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71510797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to use cd command properly in batch file? I am new to batch scripting, just trying to write a simple batch file that would go to the directory that I frequently use, without having to do cd everytime.
@ECHO OFF
CD /
CD D:
CD programming/
when I save and try to run this it gives error:
the system cannot find the file specified path
Even though these commands run fine while doing it directly on prompt
A: First off, the Windows path separator is \ but not /.
Then you need to get aware that there is a current directory for every drive to fully understand what is going on.
But anyway, here is an adapted version of your code with some explanations:
rem /* This changes to the root directory of the drive you are working on (say `C:`);
rem note that I replaced `/` by `\`, which is the correct path separator: */
cd \
rem /* This changes the current directory of drive `D:` to the current directory of drive `D:`,
rem note that this does NOT switch to the specified drive as there is no `/D` option: */
cd D:
rem /* This is actually the same as `cd programming` and changes to the sub-directory
rem `programming` of your current working directory: */
cd programming\
rem /* The final working directory is now `C:\programming`, assuming that the original
rem working drive was `C:`. */
However, what I think you are trying to achieve is the following:
rem // This switches to the drive `D:`; regard that there is NO `cd` command:
D:
rem // This changes to the root directory of the drive you are working on, which is `D:`:
cd \
rem // This changes into the directory `programming`:
cd programming
rem // The final working directory is now `D:\programming`.
This can be shortened to:
D:
cd \programming
Or even this:
rem // Note the `/D` option that is required to also switch to the given drive:
cd /D D:\programming
A: When you use
cd d:
the current directory of D: may not be D:\
To set the root you need to use CD D:\
In Windows, use backslashes
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62064095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Automated installation with Brew/cask in apps folder I want create an automated script to use on a post installation.
For this reason i want use brew and cask to make it all.
So, i think that my script should start with that to install brew:
echo << "Installing homebrew..."
if test ! $(which brew); then
echo "Homebrew not found, Installing..."
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
fi
Then i need to install some useful stuff as i see here:
http://lapwinglabs.com/blog/hacker-guide-to-setting-up-your-mac
So i put this too on my script:
# Install GNU core utilities (those that come with OS X are outdated)
brew install coreutils
# Install GNU `find`, `locate`, `updatedb`, and `xargs`, g-prefixed
brew install findutils
# Install Bash 4
brew install bash
# Install more recent versions of some OS X tools
brew tap homebrew/dupes
brew install homebrew/dupes/grep
$PATH=$(brew --prefix coreutils)/libexec/gnubin:$PATH
After that, the guide on the link says to install all the apps with cask and clean.
Here is my question.
I wish install and can update them in future using the classical Application folder of mac
How i can do that?
Maybe i should put this line:
export HOMEBREW_CASK_OPTS="--appdir=/Applications --caskroom=/usr/local/Caskroom"
Before all the commands to install the apps? May it works? (I have found this line here around)
If this line is correct can I update my apps using a brew/cask command?
Sorry for the dumbs questions, I've just discovered brew and cask yesterday :)
Any suggestion or example for this script is well accepted :)
A: brew cask install <formula> is supposed to symlink your app in Applications automatically.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34384384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: how can I add admonition in angular-markdown-editor Directive How can I add admontiton in markdown editor.
like this.
https://python-markdown.github.io/extensions/admonition/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50904225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How could I select a column based on another column in mySQL? The following script works fine. But I want to write it in one line rather than three lines. 'Size" is passed from my main program and its used here to test. Simply I want to get Price based on size.
Table columns :
LISTING_ID, PRICE_LARGE_PRICE, PRICE_SMALL_PRICE.
SET @Size = 'SMALL';
SELECT
PRICE_LARGE_PRICE,PRICE_SMALL_PRICE
INTO
@PRICE_LARGE_PRICE,@PRICE_SMALL_PRICE
FROM
prices
WHERE
PRICE_LISTING_ID = 60;
SET @ITEM_PRICE = (CASE @Size WHEN 'REGULAR' THEN @PRICE_LARGE_PRICE
WHEN 'SMALL' THEN @PRICE_SMALL_PRICE
ELSE null
END);
SELECT @ITEM_PRICE;
Any help is appreciated.
A: I think you want
SELECT
IF(@size == 'SMALL', PRICE_SMALL_PRICE, PRICE_LARGE_PRICE) AS ITEM_PRICE
FROM prices;
A: Following may work.
SET @Size = 'SMALL';
SELECT
PRICE_LARGE_PRICE,
PRICE_SMALL_PRICE,
CASE WHEN @Size = 'REGULAR' THEN PRICE_LARGE_PRICE
WHEN @Size = 'SMALL' THEN PRICE_SMALL_PRICE
END AS ITEM_PRICE
INTO
@PRICE_LARGE_PRICE,
@PRICE_SMALL_PRICE,
@ITEM_PRICE
FROM
prices
WHERE
PRICE_LISTING_ID = 60;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53415405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to run multiple locusts each with different parameters? I am trying to load our online gaming platform which has many games in it that can be accessed/played via RESTful endpoints.
I want to use locust to simulate players where each player plays a certain kind of a game. I want to have a player locust class something like:
class Player(HttpLocust):
def __init__(self, host, config, delay_between_plays):
super().__init__()
self.task_set = Game(config)
self.wait_time = delay_between_plays
self.host = host
My game taskset is like this:
class Game(TaskSet):
def __init__(self, config, parent):
super().__init__(parent)
self.config = config
@task
def play(self):
...
...
I don't see anywhere in docs where it mentions how to do this. Would appreciate some inputs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60535363",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Changing welcome screen of Nginx Hi i have setup nginx and works fine. I have added some config to accept the subdomain and that is also working fine no problem. My major concern is i have a meteor app that takes the username and creates nginx subdomain config in the fly. and currently i have listed * in my A/AAAA record in server so it accepts all subdomain. now i wanna show different view if the user request the subdomain that is not created in nginx config.
for eg,
i have setup subdomain A,B in nginx config pointing different application
A.example.com //works fine
B.example.com //works fine
if i Enter
C.example.com // shows me welcome to nginx screen
I wanna show my custom page there
Thanks in advance
A: This has nothing to do with Meteor, rather it is about setting up your nginx's default page. Try the below links
http://gpiot.com/blog/setup-default-server-landing-page-with-nginx/
NGinx Default public www location?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30630398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: SWT incorrectly detects key combinations I have two languages on my Windows 10 (english and russian). I run the following code snippet:
public static void main(String[] args) throws Exception {
Display display = new Display();
Shell shell = new Shell(display);
shell.setSize(640, 480);
shell.setLocation(500, 250);
shell.setText("SWT");
FillLayout layout = new FillLayout();
shell.setLayout(layout);
shell.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
List<String> keys = new ArrayList<>();
if ((e.stateMask & SWT.CTRL) != 0) {
keys.add("Ctrl");
}
if ((e.stateMask & SWT.ALT) != 0) {
keys.add("Alt");
}
if ((e.stateMask & SWT.SHIFT) != 0) {
keys.add("Shift");
}
keys.add(Character.toString((char) e.keyCode));
System.out.println(keys);
}
});
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
When the language is set to english and I press Right Alt + T, the program correctly prints [Alt, t].
However, when I switch the language to russian and press Right Alt+T, the program prints [Ctrl, Alt, t]. This is incorrect because I didn't press Ctrl.
This is annoying because our Eclipse RCP key bindings (such as Alt+F7 or Alt+Shift+F5) do not work correctly.
Any ideas why SWT incorrectly detects Ctrl?
I'm using SWT from the latest Eclipse 4.6 (SWT 3.105.0).
A: For historical reasons, the AltGr (right Alt) key used in non-US keyboard layouts is automatically converted by the operating system as Ctrl + Alt (see Wikipedia about this).
So this is not specifically related to SWT.
To avoid this problem users should just use the standard Alt (left Alt) key.
A: Have you tried disabling shortcut to change language in windows 10.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38783375",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: JAXB serializer from java objects to xml I'm a newbie of XML programming, I'm trying to write some java objects to a well formed and valid XML file (with respect to a DTD file),
I found out that I can do this kind of things using JAXP with Java.
My application is going to retrieve some data using an interface, and then I need to write that data into an XML file with respect of a DTD I previously and already created.
I tried to find some informations about this operations but I failed.
How am I supposed to do this operation?
EDIT: Please note that I need to stick with DTD (Can't switch to a XML schema) and that I need to go FROM Java Objects TO XML, and not viceversa.
I found that the Duplicated Answer is not applying for my question.
Don't know if the DTD can be of any help, but here it is.
DTD
<!ELEMENT AIRCRAFTS (AIRCRAFT+)>
<!ELEMENT AIRCRAFT (MODEL, SEATS)>
<!ELEMENT MODEL (#PCDATA)>
<!ELEMENT SEATS (SEAT+)>
<!ELEMENT SEAT (#PCDATA)>
<!ELEMENT FLIGHTS (FLIGHTREADER+)>
<!ELEMENT FLIGHTREADER (DEPARTURE, TIME, DESTINATION)>
<!ELEMENT DEPARTURE (#PCDATA)>
<!ELEMENT TIME (HOUR, MINUTE)>
<!ELEMENT HOUR (#PCDATA)>
<!ELEMENT MINUTE (#PCDATA)>
<!ELEMENT DESTINATION (#PCDATA)>
<!ELEMENT FLIGHTINSTANCES (FLIGHTINSTANCEREADER+)>
<!ELEMENT FLIGHTINSTANCEREADER (AIRCRAFTID, DATE, DELAY, DEPARTUREGATE, FLIGHTREADERID, PASSENGERREADER+, STATUS)>
<!ELEMENT AIRCRAFTID (#PCDATA)>
<!ELEMENT DATE (#PCDATA)>
<!ELEMENT DELAY (#PCDATA)>
<!ELEMENT DEPARTUREGATE (#PCDATA)>
<!ELEMENT FLIGHTREADERID (#PCDATA)>
<!ELEMENT PASSENGERREADER (NAME, FLIGHTINSTANCEID, SEATID, BOARDED)>
<!ELEMENT FLIGHTINSTANCEID (#PCDATA)>
<!ELEMENT BOARDED (#PCDATA)>
<!ELEMENT NAME (#PCDATA)>
<!ELEMENT SEATID (#PCDATA)>
<!ELEMENT STATUS (#PCDATA)>
<!ATTLIST FLIGHTINSTANCEREADER id ID #REQUIRED>
<!ATTLIST FLIGHTREADER id ID #REQUIRED>
<!ATTLIST AIRCRAFT id ID #REQUIRED>
A: It's basically the same way to convert Java Object to XML with JAXBContext and Marshaller with an addition of validation the XML validation with DTD.
See the sample code:
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
JAXBContext jc = JAXBContext.newInstance("blog.log4j");
Unmarshaller unmarshaller = jc.createUnmarshaller();
UnmarshallerHandler unmarshallerHandler = unmarshaller.getUnmarshallerHandler();
xr.setContentHandler(unmarshallerHandler);
FileInputStream xmlStream = new FileInputStream("src/blog/log4j/sample1.xml");
InputSource xmlSource = new InputSource(xmlStream);
xr.parse(xmlSource);
Log4JConfiguration config = (Log4JConfiguration) unmarshallerHandler.getResult();
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(config, System.out);
Source.
A: First you need to serialize object to xml, then you need validate id against dtd.
Here
you have example how to serialzie classes to xml.
This one shows how to validate xml file with dtd that is outside or inside xml file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28198055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Make radio buttons Sorry for this question, but is it possible to make radio buttons instead of select list from this piece of code?
function _nodereview_form_review(&$form, $axis, $node) {
static $options;
if (!isset($options)) {
$options = array(
20 => -2,
40 => -1,
60 => 0,
80 => 1,
100 => 2,
);
}
$form['reviews'][$axis->aid] = array(
'#type' => 'fieldset',
'#title' => $axis->tag,
'#collapsible' => TRUE,
'#collapsed' => FALSE,
);
$form['reviews'][$axis->aid]['score'] = array(
'#type' => 'select',
'#title' => t('Score'),
'#options' => $options,
'#default_value' => $node->reviews[$axis->aid]['score'] ? $node->reviews[$axis->aid]['score'] : 50,
'#description' => $axis->description,
'#required' => TRUE,
);
if (NODEREVIEW_FIVESTAR_ENABLE) {
$form['reviews'][$axis->aid]['score']['#type'] = 'fivestar';
$form['reviews'][$axis->aid]['score']['#stars'] = variable_get('nodereview_fivestar_stars', 5);
}
$form['reviews'][$axis->aid]['review'] = array(
'#type' => 'textarea',
'#title' => t('Review'),
'#default_value' => $node->reviews[$axis->aid]['review'],
'#required' => TRUE,
);
}
I know that '#type' => 'select' should be '#type' => 'radio', but something else also should be changed. I don't know what exactly.
Any suggestions are gratefully accepted.
A: Well, for starters, the #options will need to be converted to the value for each radio button. You'll also probably need to add labels for each button as well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1266711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to do something at the end of a Youtube video I'm currently launching a Youtube video using this piece of code:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube://"+token));
activity.startActivityForResult(intent, SmartBrowserWebViewActivity.ACT_YOUTUBE);
It works great. But I would like at the end of the video play to get the capability to do what I want. For example how to change activity when the video is over ?
Currently the user has to click back and I can handle it through the onActivityResult, but is there a way to avoid the user click on "back"?
Maybe I should play flash video to do it or HTML5 video ?
Thank you!
A: Implement and OnCompletionListener. Here is an example of my code. It should work the same as a RAW file video.
final VideoView vs = (VideoView) findViewById(R.id.imlsplash);
// Set video link (mp4 format )
Uri video = Uri.parse("android.resource://"+getPackageName() +"/" +R.raw.iphonesplashfinal);
vs.setVideoURI(video);
vs.requestFocus();
vs.start();
vs.setOnCompletionListener(new OnCompletionListener(){
@Override
public void onCompletion(MediaPlayer mp) {
startActivity(new Intent(CurrentActivity.this, NextActivity.class));
CurrentActivity.this.finish();
}
});
}
you may have to replace the videoView with whatever you are using.
If you are using a URL change URI to URL and add URL in place of "android.resource://"+getPackageName() +"/" +R.raw.iphonesplashfinal
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586083",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Smart shell script to search for text in file name with error handling I am trying to get a shell script built with some error handling but I have limited knowledge. I am searching for any files with a string say tests in it. However if this string is found I would to report an error. I can use the find . -name "*tests*" -print to list the files that contain the string but how do I list the file then report an error in the output if there are results, if it's null then it passes?
Thanks
A: The manual page has this to say:
find exits with status 0 if all files are processed
successfully, greater than 0 if errors occur.
This is deliberately a very broad
description, but if the return value is non-zero,
you should not rely
on the correctness of the results of find.
This is a bit of a conundrum, but if you can be reasonably sure that there will be no unrelated errors, you could do something like
find . -name '*tests*' -print -exec false \;
If you want the list of found files on standard error, add a redirection >&2
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22553962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: In angular form how to get an array of Client object and use the id value as a value in a form group's member We have an API POST method called CreateEvent(obj) that takes an object. One of the properties in the object is an int ClientId
We have a GET method called GetClients() that returns the list of Client objects in the database.
In our angular reactive form's ts and html we want to be able to have a dropdown with the returned array of the GetClients. Like so: {{clnt.id}} - {{clnt.FirstName}} {{clnt.LastName}}.
How would I go about mapping the selected clnt.id value to the form's ClientId value.
You might be able to see the idea I have so far with the code below:
<select [(ngModel)]="clientsClone" formControlName="clientId" (change)="doSomething()">
<option *ngFor="let clnt of clientsClone" [ngValue]="clnt.id">{{clnt.id}} - {{clnt.pointOfContact}} </option>
</select>
A: having the [{ngModel}] in there was bad.
the code below allowed me to make it so that: 'clientsClone' is an array of objects returned from the server and the [value]="clnt.id" with the formControlName="clientId" lets me say "hey this id int is what you need for that form's value!"
code here:
<select formControlName="clientId" (change)="onOptionsChanged(2)">
<option *ngFor="let clnt of clientsClone" [value]="clnt.id">{{clnt.id}} - {{clnt.pointOfContact}} </option>
</select>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65360316",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it possible to convert this Delphi function to a C# Method? and How? I have been working on a conversion from Delphi to C#. This is not normally something I deal with. So, I come here humbly to ask for some help.
Here is what I have so far:
Delphi code:
program Project1;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
Console in 'Console.pas';
const
CKEY1 = 11111;
CKEY2 = 22222;
function EncryptStr(const s: WideString; Key: word): String;
var
i: integer;
RStr: RawByteString;
RStrB: TBytes Absolute RStr;
begin
Result := '';
RStr := UTF8Encode(s);
for i := 0 to Length(RStr) - 1 do
begin
RStrB[i] := RStrB[i] xor (Key shr 8);
Key := (RStrB[i] + Key) * CKEY1 + CKEY2;
end;
for i := 0 to Length(RStr) - 1 do
begin
Result := Result + IntToHex(RStrB[i], 2);
end;
end;
function DecryptStr(const s: String; Key: word): String;
var
i, tmpKey: integer;
RStr: RawByteString;
RStrB: TBytes Absolute RStr;
tmpStr: string;
begin
tmpStr := UpperCase(s);
SetLength(RStr, Length(tmpStr) div 2);
i := 1;
try
while (i < Length(tmpStr)) do
begin
RStrB[i div 2] := StrToInt('$' + tmpStr[i] + tmpStr[i + 1]);
Inc(i, 2);
end;
except
Result := '';
Exit;
end;
for i := 0 to Length(RStr) - 1 do
begin
tmpKey := RStrB[i];
RStrB[i] := RStrB[i] xor (Key shr 8);
Key := (tmpKey + Key) * CKEY1 + CKEY2;
end;
Result := UTF8Decode(RStr);
end;
var myEncrypted: string;
begin
try
myEncrypted := EncryptStr('TheTestString', 4444);
WriteLn('Encrypted: '+myEncrypted);
ExitCode := 1;
Console.WaitAnyKeyPressed('Press any key to continue ...');
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
Part of the reason I am putting this out here is that this code originated here (not mine) delphi-simple-string-encryption.
Here is what I have attempted thus far:
C# code:
private const int CKEY1 = 11111;
private const int CKEY2 = 22222;
public static string EncryptAString(string s, int Key)
{
try
{
var encryptedValue = string.Empty;
// Create a UTF-8 encoding.
UTF8Encoding utf8 = new UTF8Encoding();
// Encode the string.
byte[] RStrB = utf8.GetBytes(s);
for (var i = 0; i <= RStrB.Length - 1; i++)
{
RStrB[i] = Convert.ToByte(RStrB[i] ^ (Key >> 8));
Key = (RStrB[i] + Key) * CKEY1 + CKEY2;
//I have a problem right here. See screen shot for values
}
for (var i = 0; i <= RStrB.Length - 1; i++)
{
encryptedValue = encryptedValue + RStrB[i].ToString("X2");
}
return encryptedValue;
}
catch (Exception)
{
throw;
}
}
Delphi
C#
The C# code ultimately gives this error:
Error:
System.OverflowException: Value was either too large or too small for
an unsigned byte. at System.Convert.ToByte(Int32 value) at
ChronicleConvertText.Program.EncryptAString(String s, Int32 Key) in
C:\Users\todd7\source\repos\ChronicleConvertText\ChronicleConvertText\Program.cs:line
70 at ChronicleConvertText.Program.Main(String[] args) in
C:\Users\todd7\source\repos\ChronicleConvertText\ChronicleConvertText\Program.cs:line
17
In the process of researching this a few things came into focus.
*
*In Delphi the I have this warning: [dcc32 Warning] Project1.dpr(58): W1000 Symbol 'UTF8Decode' is deprecated: 'Use UTF8ToWideString or UTF8ToString'. Bear in mind this is in use existing code. So, I have not looked directly at what if any impact switching to 'UTF8ToWideString or UTF8ToString' would have. My job as this point is to see if I can duplicate it if possible.
*Another issue is this: hazards-of-converting-binary-data-to-a-string.
I suspect that this may be my lack of understanding of what is going on in the "xor" in Delphi verses "^" in C#. The main question remains can this be done? and How? Thanks for any assistance.
A: Your constants CKEY1 and CKEY2 and argument Key have int type. So expression
Key = (RStrB[i] + Key) * CKEY1 + CKEY2;
is calculated using 32-bit values. For example:
(4444 + 84) * 11111 + 22222 = 50 332 830
is close to your shown value, isn't it?
Delphi code uses 16-bit unsigned variables and corresponding arithmetics, C# equivalent for Delphi word is ushort
A: Here is what I ended up with:
private const short CKEY1 = 11111;
private const short CKEY2 = 22222;
public static string EncryptAString(string s, ushort Key)
{
try
{
var encryptedValue = string.Empty;
// Create a UTF-8 encoding.
UTF8Encoding utf8 = new UTF8Encoding();
// Encode the string.
byte[] RStrB = utf8.GetBytes(s);
for (var i = 0; i <= RStrB.Length - 1; i++)
{
RStrB[i] = Convert.ToByte(RStrB[i] ^ (Key >> 8));
Key = (ushort)(((RStrB[i] + Key) * CKEY1) + CKEY2);
}
for (var i = 0; i <= RStrB.Length - 1; i++)
{
encryptedValue = encryptedValue + RStrB[i].ToString("X2");
}
return encryptedValue;
}
catch (Exception)
{
throw;
}
}
Tested against the Delphi code and it works marvelously.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55957723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Are there different types of race conditions? I know there are data races, can other race conditions be broken down into distinct categories?
Ultimately all race conditions are due to data being accessed in the wrong order, therefore leading threads to misbehave, but data races are a very specific case where data is read, changed, and written all at once, correct?
What else can cause a race condition?
A: Threading problems can be categorized like this:
Correctness (nothing bad happens)
*
*race condition
Liveness (something good happens eventually)
*
*deadlock
*starvation
*livelock
I do not know of a further categorization of race conditions.
A data race is a more lower level problem and happens if you have conflicting memory accesses (so at least one of them is a write) on the same memory location and these are not ordered by a happens before relation. Data races are part of memory models like the Java Memory Model and that of C++ 11. A race condition and a data race are different types of problems.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61963836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: setInterval, clearInterval, setTimeout conflict messing up slideshow I've got a slideshow that autoplays on document.ready by triggering my left arrow click on setInterval. I'm trying to stop the autoplay when the nav arrows are clicked, while still allowing the arrows to navigate the slides.
This accomplishes that.
var intervalId = window.setInterval(switchLeft, 4000);
$("#leftarrow, #rightarrow").click(function() {
window.clearInterval(intervalId);
});
But I want the autoplay to kick back in if the arrows haven't been clicked in 8 seconds. I have tried turning the setInterval back in by adding this setTimeout into the click function, but it counts all the clicks of user navigation during the pause and starts throwing my slides around like crazy. (I've got two layers of images moving on every click.)
setTimeout(function() {
intervalId = window.setInterval(switchLeft, 4000)
}, 8000);
I've tried wrapping stuff in a setTimeout function but I just end up getting different weirdness.
Thanks for any help,
Charlie Magee
A: You need to cancel the setTimeout() if the arrows are clicked before it fires so you don't get multiple timers going at once (which will certainly exhibit weirdness).
I don't follow exactly what you're trying to do on the arrows, but this code should manage the timers:
var intervalId = setInterval(switchLeft, 4000);
var timeoutId;
$("#leftarrow, #rightarrow").click(function() {
// clear any relevant timers that might be going
// so we never get multiple timers going
clearInterval(intervalId);
clearTimeout(timeoutId);
// restart the interval in 8 seconds
timeoutId = setTimeout(function() {
intervalId = window.setInterval(switchLeft, 4000)
}, 8000);
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20156097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Databricks - Reduce delta version compute time I've got a process which is really bogged down by the version computing for the target delta table.
Little bit of context - there are other things that run, all contributing uniform structured dataframes that I want to persist in a delta table. Ultimately these are all compiled into lots_of_dataframes to be logged.
for i in lots_of_dataframes:
i.write.insertInto("target_delta_table")
# ... take a while to compute version
I've got in to the documentation but couldn't find any setting to ignore the version compute. I did see vacuuming, but not sure that'll do the since there will still be a lot of activity in a small window of time.
I know that I can union all of the dataframes together and just do the insert once, but I'm wondering if there is a more Databricks-ian way to do it. Like a configuration to only maintain 1 version at a time and not worry about computing for a restore.
A: Most probably, but it's hard to say exactly without details, the problem arise from the following facts:
*
*Spark is lazy - the actual data processing doesn't happen until you perform action, like writing data into a destination table. So if you have a lot of transformations, etc., they will happen when you're writing data.
*You're writing data in the loop - you can potentially speedup it a bit by doing a union of all tables into a single dataframe, that will be written into one go:
import functools
unioned = functools.reduce(lambda x,y: x.union(y), lots_of_dataframes)
unioned.write.insertInto("target_delta_table")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74306338",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: overloading primitive variables code is
public class TestOverload {
public static void print(Float f, double d) {
System.out.println("Float,double");
}
public static void print(float f, double d) {
System.out.println("float,double");
}
public static void print(int f, double d) {
System.out.println("int,double");
}
// public static void print(int f, float d) {
// System.out.println("int,float");
// }
public static void print(double d1, double d) {
System.out.println("double,double");
}
public static void print(float d1, float d) {
System.out.println("float,float");
}
public static void main(String[] args) {
TestOverload.print(2, 3.0);
TestOverload.print(2, 3.0f);//Compiler error:The method print(float, double) is ambiguous for the type TestOverload
}
}
why it is giving error , instead it should pick print(float d1, float d)
PS:
in the above code,if i comment :
// public static void print(int f, double d) {
// System.out.println("int,double");
// }
then print(float d1, float d) is called...
A: print(2, 3.0f);
Could be both print(int, float) and print(float, double) since implicit type conversions are done in the backgound. An int can be converted to a float. Javac (or the compiler) cannot know for sure which one you meant.
If you want to choose for your self you can add casts:
print((float) 2, (float) 3.0f);
(Note that the second cast (float => float) isn't necessary.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10479234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Not reading utf-8 marks I have a .txt file on my sdcard with utf-8 marks e.g.:
"Jak przetrwać wśród czarnych dziur"
And this is how I try to read them from this file:
public static void readBooksFromTxtFile(Context context, String filePath, ArrayList<SingleBook> books) {
BufferedReader in;
try {
in = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));
String line = null;
while ((line = in.readLine()) != null) {
String title = line;
String author = in.readLine();
String pages = in.readLine();
String date = in.readLine();
// just for debugging
System.out.println(title);
books.add(new SingleBook(title, author, pages, date));
}
} catch (Exception e) {
Toast.makeText(context, "Error during reading file.", Toast.LENGTH_LONG).show();
return;
}
}
But it doesn't read the file correctly:
What am I doing wrong?
A: I believe your issue is here:
in = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));
Instead it should be
in = new BufferedReader(new FileReader(new File(filePath));
This should read it correctly. If not, you can just use RandomAccessFile:
public static void readBooksFromTxtFile(Context context, String filePath, ArrayList<SingleBook> books) {
RandomAccessFile in;
try {
in = new RandomAccessFile(new File(filePath), "r");
String line = null;
while ((line = in.readUTF8()) != null) {
String title = line;
String author = in.readUTF8();
String pages = in.readUTF8();
String date = in.readUTF8();
// just for debugging
System.out.println(title);
books.add(new SingleBook(title, author, pages, date));
}
} catch (Exception e) {
Toast.makeText(context, "Error during reading file.", Toast.LENGTH_LONG).show();
return;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35297566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Visual C++: ATL Implementation of an Interface I guess this is a real dumb question, but I couldn't find an answer. I'm trying to implement an COM interface using ATL. According to this I should use the Implement Interface Wizard. My question is how can I find the desired interface in this wizard. Do I have to go over all the libraries? Does is specified somewhere in the documentation of the interface (IOleCommandTarget)
A: To implement an interface you need:
*
*inherit your class from it
*add it onto interface map
*implement its methods
For example:
class CFoo :
// regular COM object base class, esp. those generated by ATL Simple Object Class Wizard
public IOleCommandTarget
{
BEGIN_COM_MAP(CFoo)
// ...
COM_INTERFACE_ENTRY(IOleCommandTarget)
END_COM_MAP()
// ...
public:
// IOleCommandTarget
STDMETHOD(Exec)(...) // IOleCommandTarget methods go here
{
// ...
}
};
A: To implement you need to do:
*
*In the *h file let your CoClass inherit from interface.
2.In the *h file ,add an interface entry in the COM Map.
In the *h file ,add the prototype of interface methods.
In the *cpp file, implement the method of interface.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14180516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: VBScript Search Excel Workbook for Value from another Workbook I am new to VB scripting, so please, bear with me! I am trying to create a script that uses worksheets from two different excel workbooks. It opens the first worksheet and iterates through a specified range. I want it to then take the value of each cell in that range and search the second worksheet (in a different workbook) and search for the value that was found in the first worksheet, and if the value is found, return the address of the cell it was found in. For example:
Worksheet1
╔══════╦═════╗
║ Name ║ Age ║
╠══════╬═════╣
║ Matt ║ 22 ║
║ Jeff ║ 13 ║
╚══════╩═════╝
Worksheet2
╔═══════╦════════════╗
║ Name ║ DOB ║
╠═══════╬════════════╣
║ Dave ║ 09/12/2001 ║
║ Frank ║ 01/25/1992 ║
║ Jeff ║ 10/10/2013 ║
╚═══════╩════════════╝
So the script would output: A4
Because it found one of the values from the specified range (A2:A3) of the first worksheet in the second worksheet and is returning the location of that cell.
Here is the code I have:
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Dim val
Set objWorkbook = objExcel.Workbooks.Open("C:\Users\username\file.xlsx")
Set objWorksheet = objWorkbook.Worksheets("Sheet1")
Set objWorkbook2 = objExcel.Workbooks.Open("C:\Users\username\file2.xlsx")
Set objWorksheet2 = objWorkbook2.Worksheets("Sheet1")
For Each c In objworksheet.Range("A2:A3").Cells
val = c.value
Set objRange = objWorksheet2.UsedRange
Set found = objRange.Find(val)
Wscript.Echo found.AddressLocal(False,False)
Next
When I run this code, I get the following error:
Error: Object required: 'found'
I am sure there is something obvious I am missing here but I have been spinning my wheels for quite some time and was hoping someone could provide some feedback. Any help is greatly appreciated!
A: The Find() function returns a Range object if successful or Nothing if not. So you need to test the return value to ensure it's a Range object before you try accessing its properties and methods.
For Each c In objworksheet.Range("A2:A3").Cells
val = c.value
Set objRange = objWorksheet2.UsedRange
Set found = objRange.Find(val)
' Test for success!
If Not found Is Nothing Then
Wscript.Echo found.AddressLocal(False,False)
End If
Next
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32484268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Best way to unset a flag in C when using Enum that is signed I'm trying to use enum in C to create a flags variable, as discussed here: Flags, enum (C)
How should I reset a single enum flag, when the compiler represents the enum as signed?
Problem:
Say I declare my flags type like this:
typedef enum {
FLAGS_A = 1 << 0,
FLAGS_B = 1 << 1,
FLAGS_C = 1 << 2,
FLAGS_D = 1 << 3
} flags_t;
flags_t flags;
I would like to reset a flag like this:
flags |= FLAGS_A; // Set A
flags &= (~FLAGS_A); // Reset A
However the compiler (Microchip XC8 Compiler V2.32) throws an error because bitwise operators should only be used on unsigned types. It looks like the enum is actually a signed integer under the hood.
Based on this question, it looks like there's no good way to force the compiler to use unsigned for enum: Is there a way to make an enum unsigned in the C90 standard? (MISRA-C 2004 compliant)
Things I've Tried:
One workaround I found was to add a special enumerated variable that has all the other flags set. I can use that as a mask to reset flag A:
typedef enum {
....
FLAGS_RESET_A = (FLAGS_B | FLAGS_C | FLAGS_D)
} flags_t
flag_t flags &= (FLAGS_RESET_A); // Reset A
This workaround is cumbersome. Any time I modify the flags type, such as adding a flag, I also have to remember to modify all the reset masks. I'm hoping there is a method that preserves the enum as a "single source of truth" for the flag definitions.
Another workaround is type casting to an unsigned integer, but that defeats the safety of using an enumerated type.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70551075",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to get time difference between two ZonedDateTimes and pretty print it like "4 hours, 1 minute, 40 seconds ago"? This is how I call getTimeBetween function:
getTimeBetween(ZonedDateTime.now().minusHours(4).minusMinutes(1).minusSeconds(40), ZonedDateTime.now());
And I expect this output:
4 hours, 1 minute, 40 seconds ago
This is my getTimeBetween function:
private String getTimeBetween(ZonedDateTime zonedDateTime1, ZonedDateTime zonedDateTime2) {
Duration timeDifference = Duration.between(zonedDateTime1, zonedDateTime2);
if (timeDifference.getSeconds() == 0) return "now";
String timeDifferenceAsPrettyString = "";
Boolean putComma = false;
if (timeDifference.toDays() > 0) {
if (timeDifference.toDays() == 1) timeDifferenceAsPrettyString += timeDifference.toDays() + " day";
else timeDifferenceAsPrettyString += timeDifference.toDays() + " days";
putComma = true;
}
if (timeDifference.toHours() > 0) {
if (putComma) timeDifferenceAsPrettyString += ", ";
if (timeDifference.toHours() == 1) timeDifferenceAsPrettyString += timeDifference.toHours() + " hour";
else timeDifferenceAsPrettyString += timeDifference.toHours() % 24 + " hours";
putComma = true;
}
if (timeDifference.toMinutes() > 0) {
if (putComma) timeDifferenceAsPrettyString += ", ";
if (timeDifference.toMinutes() == 1) timeDifferenceAsPrettyString += timeDifference.toMinutes() + " minute";
else timeDifferenceAsPrettyString += timeDifference.toMinutes() % 60 + " minutes";
putComma = true;
}
if (timeDifference.getSeconds() > 0) {
if (putComma) timeDifferenceAsPrettyString += ", ";
if (timeDifference.getSeconds() == 1) timeDifferenceAsPrettyString += timeDifference.getSeconds() + " second";
else timeDifferenceAsPrettyString += timeDifference.getSeconds() % 60 + " seconds";
}
timeDifferenceAsPrettyString += " ago";
return timeDifferenceAsPrettyString;
}
This function works as expected but is it really necessary to do it like this? Perhaps there is a better way to achieve this?
I'm using Java 8.
A: How about this?
static String getTimeBetween(ZonedDateTime from, ZonedDateTime to) {
StringBuilder builder = new StringBuilder();
long epochA = from.toEpochSecond(), epochB = to.toEpochSecond();
long secs = Math.abs(epochB - epochA);
if (secs == 0) return "now";
Map<String, Integer> units = new LinkedHashMap<>();
units.put("day", 86400);
units.put("hour", 3600);
units.put("minute", 60);
units.put("second", 1);
boolean separator = false;
for (Map.Entry<String, Integer> unit : units.entrySet()) {
if (secs >= unit.getValue()) {
long count = secs / unit.getValue();
if (separator) builder.append(", ");
builder.append(count).append(' ').append(unit.getKey());
if (count != 1) builder.append('s');
secs %= unit.getValue();
separator = true;
}
}
return builder.append(epochA > epochB ? " ago" : " in the future").toString();
}
You could probably store the LinkedHashMap instead of instantiating it every method call, but this should work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41447096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ios: Wrong image loading from php script In my app, I use a php script that redirects to an image. After I changed the picture on the server, the app on only one device continued to load the older picture. I don't save the picture locally anywhere, and I load the picture from the server every time. The right picture was loading correctly on other devices and after I deleted and re-built the app on my current device. What could have caused the problem?
my php code looks like this:
$userid = $_POST['userid'];
$query = "SELECT image FROM Users WHERE userid='$userid'";
$results = mysql_query($query);
$user = mysql_fetch_array($results);
$image = $user['image'];
header("Location:../profile_images/".$image);
A: Try something like this to do a force reload of the image. So every time the image is requested a new one will appear. Change your header like this.
header("Location:../profile_images/".$image."?".rand(1,3000));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19205718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Given a sample of random variables, and n, how do I find the ecdf of the sum of n Xs? I can't fit X to a common distribution so currently I just have X ~ ecdf(sample_data).
How do I calculate the empirical distribution of sum(X1 + ... + Xn), given n? X1 to Xn are iid.
A: To estimate the distribution of that sum, you can repeatedly sample with replacement (and then take the sum of) n variates from sample_data. (sample() places equal probability mass on each element of sample_data, just as the ecdf does, so you don't need to calculate ecdf(sample_data) as an intermediate step.)
# Create some example data
sample_data <- runif(100)
n <- 10
X <- replicate(1000, sum(sample(sample_data, size=n, replace=TRUE)))
# Plot the estimated distribution of the sum of n variates.
hist(X, breaks=40, col="grey", main=expression(sum(x[i], i==1, n)))
box(bty="l")
# Plot the ecdf of the sum
plot(ecdf(X))
A: First, generalize and simplify: solve for step function CDFs X and Y, independent but not identically distributed. For every step jump xi and every step jump yi, there will be a corresponding step jump at xi+yi in the CDF of X + Y, So the CDF of X + Y will be characterized by the list:
sorted(x + y for x in X for y in Y)
That means if there are k points in X's CDF, there will be kn in (X1 + ... + Xn). We can cut that down to a manageable number at the end by throwing away all but k again, but clearly the intermediate calculations will be costly in time and space.
Also, note that even though the original CDF is an ECDF for X, the result will not be an ECDF for (X1 + ... + Xn), even if you keep all kn points.
In conclusion, use Josh's solution.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10651170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to load Notes for Projects in Salesforce I have notes in my Pipedrive tool for each deals. Now i need to migrate those notes for each deal in Pipedrive to my Salesforce. How can I get the notes for each project loaded to its corresponding project. I try loading notes by giving project ID through Data Loader Wizard. Even-though the tool says that the data is loaded successfully, When I go to my Project in Salesforce, I am not able to see the Notes for the project.
Please help.
Thanks
Niki
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50718804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: hide tabs in Access 2010 with vba I'm using Access 2010 and I'd like to hide the tabs, when the person is not admin. My admin variable is stored Temp Variable.
How can I do that?
Best regards
Matthias
A: Hiding and showing the tabs (ie a tab for an open access object - ie a form, query, report, etc) is a setting for the current database project, that only takes effect once the database file is closed and re-opened. Although the value can be set by code, it is not practical as it would apply to all users who then open the the file. (and you would need to set it, close, repoen ...)
You might like to have two copies of the database front end file held on a server with windows file permissions such that admin opens a different file to plebs, the admin file shows the tabs and other users open a file that doesn't.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31854360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to login on divshot cli inside a vagrant box? Divshot has a nice command line interface. The first thing you should do after installing it with npm is to login.
divshot login
It should open a browser tab/window, you login on the divshot website and you authorise the CLI client by pressing a button at the end of the process.
But I have all my development environment on a vagrant box. When I type "divshot login" nothing happens. No browser tab appears.
What should I do?
A: *
*Run "divshot login" from your command line on you local machine and
follow the instructions to login.
*Run "divshot auth:token" to get
your auth token from the command line.
*When running commands that
interact with the Divshot API, use the flag "--token " to
give it authorization (on the vagrant box)
A: Another solution:
*
*Run divshot login on your local computer
*Inspect $HOME/.divshot/config/user.json, check it has a key token
*Copy that file to the corresponding path on the other computer
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29150307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Scala: Is it possible to indicate a generic class which implements a certain method I thinks it's easier to explain it with a simple example. (help rephrasing the title is welcome ;-)
I'd like to implement a squared method and, using implicit def, automatically add it to any class that supports the *-operator.
With an Int it's very easy:
class EnhancedInt(x: Int) { def squared = x * x }
implicit def IntToEnchancedInt(x: Int) = new EnhancedInt(x)
But with Any or AnyVal I get the following error:
scala> class EnhanceAny(x: AnyVal) { def squared = x * x }
<console>:7: error: value * is not a member of AnyVal
class EnhanceAny(x: AnyVal) { def squared = x * x }
I'd like to know how I could apply it to any numeric class, or, even better, to any class supporting the *-operator.
A: It's not possible to have solution that works on any type with a * method without writing a boilerplate conversion for each type you want to deal with. Essentially to do that you would need a recursive structural type, and Scala does not support those because of JVM type erasure. See this post for more details.
You can get fairly close to what you want using a type class along with the Numeric type class, (inspired by the answers to this and this question). This will work with most primitives:
//define the type class
trait Multipliable[X] { def *(x: X): X}
//define an implicit from A <% Numeric[A] -> Multipliable[Numeric[A]]
implicit def Numeric2Mult[A](a: A)(implicit num: Numeric[A]): Multipliable[A] = new Multipliable[A]{def *(b: A) = num.times(a, b)}
//now define your Enhanced class using the type class
class EnhancedMultipliable[T <% Multipliable[T]](x: T){ def squared = x * x}
//lastly define the conversion to the enhanced class
implicit def Mult2EnhancedMult[T <% Multipliable[T]](x: T) = new EnhancedMultipliable[T](x)
3.squared
//Int = 9
3.1415F.squared
//Float = 9.869022
123456789L.squared
//Long = 15241578750190521
A: Go visit Scala: How to define “generic” function parameters?
A: Think about it. Multiplication have different properties on different objects. Integer multiplication, for example, is associative and commutative, scalar multiplication is not commutative. And multiplication on floating point numbers...
But, of course, you can have what you want with trait or with "trait and implicit" construction which resembles a typeclass.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8866030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: c# how can return value from class? I have class !
class Reg_v_no_string
{
public static string key_place = "";
public static string key = "";
public static string value = "";
public string reg_value(string key_place, string key)
{
string value = string.Empty;
RegistryKey klase = Registry.CurrentUser;
klase = klase.OpenSubKey(key_place);
value = klase.GetValue(key).ToString();
klase.Close();
return value;
}
}
and this returns blank message box.
How can solve this problem !?
Thanks !
how can i return value from this class ?
I tryed
private void kryptonButton1_Click(object sender, EventArgs e)
{
Reg_v_no_string.key_place = @"Control Panel\Desktop";
Reg_v_no_string.key_place = "WheelScrollLines";
MessageBox.Show(Reg_v_no_string.value);
}
A: You need to actually call the method:
private void kryptonButton1_Click(object sender, EventArgs e)
{
var value = reg_value(@"Control Panel\Desktop", "WheelScrollLines");
MessageBox.Show(value);
}
Also consider some changes to your class:
public static class Reg_v_no_string
{
public static string reg_value(string key_place, string key)
{
string value = string.Empty;
RegistryKey klase = Registry.CurrentUser;
// todo: add some error checking to make sure the key is opened, etc.
klase = klase.OpenSubKey(key_place);
value = klase.GetValue(key).ToString();
klase.Close();
return value;
}
}
And then when you call this static class it is like this:
// you don't need to `new` this class if it is static:
var value = Reg_v_no_string.reg_value(@"Control Panel\Desktop", "WheelScrollLines");
Or, to keep it so that it is not static:
public class Reg_v_no_string
{
public string reg_value(string key_place, string key)
{
string value = string.Empty;
RegistryKey klase = Registry.CurrentUser;
// todo: add some error checking to make sure the key is opened, etc.
klase = klase.OpenSubKey(key_place);
value = klase.GetValue(key).ToString();
klase.Close();
return value;
}
}
Then call it like this:
Reg_v_no_string obj = new Reg_v_no_string ();
var value = reg_value(@"Control Panel\Desktop", "WheelScrollLines");
A: There is no code that calls reg_value.
As result you are getting default (also shared between instances) value of value field.
A: Reg_v_no_string.value is not set yet.
You have to call reg_value(string key_place, string key) function that will return the value.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11621672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: New elements vanish when function ends I have created a simple form that allows the user to create a number of blank tables with a variable number of rows and columns. The code generates no errors, and briefly creates the new table elements, but when the function ends the tables vanish. What am I doing wrong?
function genTable(){
var numRows = parseInt(document.getElementById("numRows").value); // Number of rows per table
var numCols = parseInt(document.getElementById("numCols").value); // Number of columns per table
var numTabs = parseInt(document.getElementById("numTabs").value); // number of tables
var startDiv = document.getElementById("start");
var oneCell = "<td class=\"cell\"></td>"; // HTML for a single cell
var myHTML = ""; // An empty string to contain the tables
for(i=0; i<numTabs; i++){
myHTML += "<div><table class=\"linesTab\" id=\"winLine" + (i+1) + "\">";
for(k=0; k<numRows; k++){
myHTML += "<tr>";
for(j=0; j<numCols; j++){
myHTML += oneCell;
}
myHTML += "</tr>";
}
myHTML += "</table><br><span class=\"tabSpan\">" + (i+1) + "</span></div>";
}
startDiv.innerHTML= myHTML;
}
A: It sounds like you have a trigger built into a hyperlink or a form... so although your script runs, the browser navigates and refreshes the page.
If you have a click event, you need to stop the event from propagating.
Short example:
HTML
<div id="example">
</div>
<form>
<input type="number" id="num" />
<button id="clicker">
Go
</button>
</form>
JavaScript
document.getElementById('clicker').onclick = function () {
document.getElementById('example').innerHTML = 'Content';
// return false; // <-- without this (or an alternative) the form posts
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46477056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Placing a revolution slider on a wordpress woocommerce store So I am trying to place a Revolution slider on top of our Wocommerce shop pages, a lot like we already have on all of our other pages bar the shop.
I've provided the screenshots of how it is now and how I'd like it to look.
We're using a custom theme.
I know how to update my .PHP code if I'm pointed to the right file with the right bit of code!
Suggestions most welcome :)
This is what our shop currently looks like:
This is what our homepage looks like with the revolution slide (mid transition):
This is how we'd like the shop to look with the revolution slider:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47249208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Formatting error in NPOI I'm developing an accountancy software, which will also create a report in Excel format (.xls).
I've used NPOI in almost every project that requires an Excel report, without any major problem.
But i'm now facing a problem, and can't seem to find any solution browsing the Internet.
As you can see, midway the report, the Currency column automatically changes format, not formatting properly currency, border, and everything in that column.
I've been working on it for several time, with no success.
Here's the code I've used to create the style (C#):
var baseStyle = workBook.CreateCellStyle();
baseStyle.VerticalAlignment = VerticalAlignment.Top;
baseStyle.FillForegroundColor = IndexedColors.White.Index;
baseStyle.FillPattern = FillPattern.SolidForeground;
baseStyle.BorderTop = BorderStyle.Thin;
baseStyle.BorderBottom = BorderStyle.Thin;
baseStyle.BorderLeft = BorderStyle.Thin;
baseStyle.BorderRight = BorderStyle.Thin;
baseStyle.WrapText = true;
private static void SetCellValuePrice(IRow row, ICellStyle cellStyle, int colIndex, decimal value)
{
var xlCell = row.CreateCell(colIndex);
xlCell.SetCellValue(Convert.ToDouble(value));
var newStyle = row.Sheet.Workbook.CreateCellStyle();
newStyle.CloneStyleFrom(cellStyle);
newStyle.DataFormat = row.Sheet.Workbook.CreateDataFormat().GetFormat("€ #,##0.00");
xlCell.CellStyle = newStyle;
}
And an example of the usage (that seems to give no problems in other cells:
SetCellValue(row, baseStyle, colIndex++, data.Description);
Any guesses?
Thanks in advance!
A: The problem is that you're creating a style for each cell, while you should create just ONE style for each type of cell.
var baseStyle = workBook.CreateCellStyle();
...
var priceStyle = workBook.CreateCellStyle();
priceStyle.CloneStyleFrom(numberStyle);
priceStyle.DataFormat = workBook.CreateDataFormat().GetFormat("€ #,##0.00");
private static void SetCellValuePrice(IRow row, ICellStyle cellStyle, int colIndex, decimal value)
{
var xlCell = row.CreateCell(colIndex);
xlCell.SetCellValue(Convert.ToDouble(value));
xlCell.CellStyle = cellStyle;
}
Usage:
SetCellValue(row, priceStyle, colIndex++, data.Description);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43662756",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Google Cloud Build GitHub App - auto trigger for all projects in organization Up until a few weeks ago, when installing the Google Cloud Build GitHub app in a GitHub organization, it was possible to specify that all GitHub projects within that organization would create a build trigger.
Yesterday I noticed that this no longer happens, and new projects added to the GitHub organizations don't trigger a build and I can see a message on the specific commit saying that "this repository is not mapped to a Google Cloud platform project".
Is this an intentional change in spec - so one needs to manually link every new repo via the Console/API - or something I'm missing?
A: yes. for a new project, you have to manually set up on the cloud build page by "Connect repository". then you can use gcp cli comamnd set the trigger,
gcloud beta builds triggers create github
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55257410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Django Haystack faceting multivalued strings -- unknown field tags_exact The content on my site is tagged with strings of variable length, and I want to do faceted search on these tags. For example, a story might have tags, "civil war," "general grant," and "battle of gettysburg." I want to be able to do faceted search on the exact, non-tokenized strings.
Within my search_index.py, I defined:
tags = MultiValueField(faceted=True, indexed=True)
and I edited the schema.xml generated by build_solr_schema to make tags a string instead of text:
<field name="tags" type="string" indexed="true" stored="true" multiValued="true" />
Unfortunately when I get an error about tags_exact:
Failed to add documents to Solr: [Reason: None]
ERROR: [doc=treelines_stories.story.1] unknown field 'tags_exact'
I understand that the tags_exact field has something to do w/ Haystack's internal implementation of faceting, but how can I work around this?
Thanks!
A: search_index.py:
tags = MultiValueField(faceted=True)
schema.xml:
<field name="tags" type="text" indexed="true" stored="true" multiValued="true" />
<field name="tags_exact" type="string" indexed="true" stored="true" multiValued="true" />
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12967184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Python: How to get CSV to write colums (using API) I am trying to create a spreadsheet out of API data, but I am having trouble getting it to work. The .csv file will only contain the last line of information it collected. What I want is 2 columns, both with about 2800 items in each. Instead I have 2 columns with one line in each. Is there a way to write columns instead? I think my problem is that since the myFile = open('AutoCSV.csv', "w") is in a for loop it just continues to "open and close" the file? Im pretty new to python and brand new to API and CSV files so any suggestions are appreciated.
for x in range(0,5):
string1 = "https://api.rainforestcloud.com/rest/device?networkName=Company&take=500&skip="+str(x*500)
response = requests.get(string1,headers=headers).json()
for y in range (0,499):
myData = [(response[y]['deviceGuid']),(response[y]['status'])]
myFile = open('AutoCSV.csv', "w")
with myFile:
writer = csv.writer(myFile)
writer.writerow(myData)
A: This has nothing to do with API nor with the csv format actually, it's just that:
since the myFile = open('AutoCSV.csv', "w") is in a for loop it just continues to "open and close" the file
Indeed - and not only that but it clears the file each time it reopens it, as documented here:
'w' for writing (truncating the file if it already exists)
Also, you're not using with open() correctly, you want:
with open("path/to/your/file.ext") as f:
# your code using the file here
Hopefully the fix is simple: open the file before your outer loop. Now may I ask why you didn't tried this directly instead of posting here ?
A: Since you don't provide any input data, I'll have to do this blindly. Does this works for you?:
import csv
import requests
headers = {} #something
with open('AutoCSV.csv', "w", , newline='') as csv_output_file:
file_writer = csv.writer(csv_output_file)
for current_page_start in range(0, 2500, 500):
url_to_retrieve = f"https://api.rainforestcloud.com/rest/device?networkName=Company&take=500&skip={current_page_start}"
json_response = requests.get(url_to_retrieve, headers=headers).json()
for response_element in json_response:
data_to_write = (response_element['deviceGuid'], response_element['status'])
file_writer.writerow(data_to_write)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50351426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: step by step solr katta integration I am trying to find the solr and katta integration.
But didn't find any good tutorial for the same.
Could you please give me step by step integration of katta and solr.
Many thanks in advance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6076182",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: how to show warning of empty field on form validation? these are my code for form validation :
<form action="<?php echo base_url().'data_laporan/tambah_aksi';?>"method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Jenis Laporan</label>
<select class="form-control" name="jenis_laporan">
<option>Penemuan hewan</option>
<option>Kehilangan Hewan</option>
</select>
</div>
<div class="form-group">
<label>Jenis Hewan</label>
<input type="text" name="jenis_hewan" class="form-control">
</div>
<div class="form-group">
<label>Lokasi</label>
<input type="text" name="lokasi" class="form-control">
</div>
<div class="form-group">
<label>Deskripsi</label>
<input type="text" name="deskripsi" class="form-control">
</div>
<div class="form-group">
<label>Nama Pelapor</label>
<input type="text" name="nama_pelapor" class="form-control">
</div>
<div class="form-group">
<label>No Hp</label>
<input type="text" name="no_hp" class="form-control">
</div>
<div class="form-group">
<label>Gambar Hewan</label>
<input type="file" name="gambar" class="form-control">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
</form>
i want to show a simple warning when i click "Save Changes" as a submit button like this :
image for example warning
and these are my code for tambah_aksi() function :
public function tambah_aksi()
{
$jenis_laporan = $this->input->post('jenis_laporan');
$jenis_hewan = $this->input->post('jenis_hewan');
$deskripsi = $this->input->post('deskripsi');
$lokasi = $this->input->post('lokasi');
$nama_pelapor = $this->input->post('nama_pelapor');
$no_hp = $this->input->post('no_hp');
$gambar = $_FILES['gambar']['name'];
if ($gambar = '') {} else{
$config ['upload_path'] = './upload';
$config ['allowed_types'] = 'jpg|jpeg|png|gif';
$this->load->library('upload', $config);
if(!$this->upload->do_upload('gambar')){
echo "Gambar gagal di Upload";
}else{
$gambar=$this->upload->data('file_name');
}
}
$data = array (
'jenis_laporan' => $jenis_laporan,
'jenis_hewan' => $jenis_hewan,
'deskripsi' => $deskripsi,
'lokasi' => $lokasi,
'nama_pelapor' => $nama_pelapor,
'no_hp' => $no_hp,
'gambar' => $gambar,
);
$this->model_laporan->tambah_aksi($data, 'tb_laporan');
redirect('data_laporan/index');
}
i tried using if-else form validation run checking but it does not goes well, could you please help me to fix this with another way or the efficient way of if-else checking?
A: You can do this many ways
Via codeigniter 3.x
then first load form validation library in controller function and set rules and place holder for showing errors in view file. See for reference
https://codeigniter.com/userguide3/libraries/form_validation.html#the-controller
https://codeigniter.com/userguide3/libraries/form_validation.html#showing-errors-individually
Via HTML
You can simply do this by adding required attribute to all html elements which are required, browser will show warning automatically after clicking on submit button for required fields. see example for input html element
<input type="text" name="nama_pelapor" required class="form-control">
See for dropdown
<select class="form-control" required name="jenis_laporan">
<option>Penemuan hewan</option>
<option>Kehilangan Hewan</option>
</select>
Via Jquery
If you want to customize error messages then you do this via your own code in jquery or jquery validator library. See this documentation for jquery validation
https://jqueryvalidation.org/validate/
A: Comparison operator should be double == not single =. Edit your line of code to this.
if ($gambar =='') {} else{
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68350159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Create table on cluster of clickhouse error When I create table as follows:
CREATE TABLE partition_v3_cluster ON CLUSTER perftest_3shards_3replicas(
ID String,
URL String,
EventTime Date
) ENGINE = MergeTree()
PARTITION BY toYYYYMM(EventTime)
ORDER BY ID;
I get errors:
Query id: fe98c8b6-16af-44a1-b8c9-2bf10d9866ea
┌─host────────┬─port─┬─status─┬─error───────────────────────────────────────────────────────────────────────────────────────────────────────────── ──────────────────────────────────────────────────────────────────────────┬─num_hosts_remaining─┬─num_hosts_active─┐
│ 10.18.1.131 │ 9000 │ 371 │ Code: 371, e.displayText() = DB::Exception: There are two exactly the same ClickHouse instances 10.18.1.131:9000 i n cluster perftest_3shards_3replicas (version 21.6.3.14 (official build)) │ 2 │ 0 │
│ 10.18.1.133 │ 9000 │ 371 │ Code: 371, e.displayText() = DB::Exception: There are two exactly the same ClickHouse instances 10.18.1.133:9000 i n cluster perftest_3shards_3replicas (version 21.6.3.14 (official build)) │ 1 │ 0 │
│ 10.18.1.132 │ 9000 │ 371 │ Code: 371, e.displayText() = DB::Exception: There are two exactly the same ClickHouse instances 10.18.1.132:9000 i n cluster perftest_3shards_3replicas (version 21.6.3.14 (official build)) │ 0 │ 0 │
└─────────────┴──────┴────────┴─────────────────────────────────────────────────────────────────────────────────────────────────────────────────── ──────────────────────────────────────────────────────────────────────────┴─────────────────────┴──────────────────┘
← Progress: 0.00 rows, 0.00 B (0.00 rows/s., 0.00 B/s.) 0%
3 rows in set. Elapsed: 0.149 sec.
Received exception from server (version 21.6.3):
Code: 371. DB::Exception: Received from localhost:9000. DB::Exception: There was an error on [10.18.1.131:9000]: Code: 371, e.displayText() = DB:: Exception: There are two exactly the same ClickHouse instances 10.18.1.131:9000 in cluster perftest_3shards_3replicas (version 21.6.3.14 (official build)).
And here is my metrika.xml:
<?xml version="1.0" encoding="utf-8"?>
<yandex>
<remote_servers>
<perftest_3shards_3replicas>
<shard>
<replica>
<host>10.18.1.131</host>
<port>9000</port>
</replica>
<replica>
<host>10.18.1.132</host>
<port>9000</port>
</replica>
<replica>
<host>10.18.1.133</host>
<port>9000</port>
</replica>
</shard>
<shard>
<replica>
<host>10.18.1.131</host>
<port>9000</port>
</replica>
<replica>
<host>10.18.1.132</host>
<port>9000</port>
</replica>
<replica>
<host>10.18.1.133</host>
<port>9000</port>
</replica>
</shard>
<shard>
<replica>
<host>10.18.1.131</host>
<port>9000</port>
</replica>
<replica>
<host>10.18.1.132</host>
<port>9000</port>
</replica>
<replica>
<host>10.18.1.133</host>
<port>9000</port>
</replica>
</shard>
</perftest_3shards_3replicas>
</remote_servers>
<zookeeper>
<node>
<host>10.18.1.131</host>
<port>2181</port>
</node>
<node>
<host>10.18.1.132</host>
<port>2181</port>
</node>
<node>
<host>10.18.1.133</host>
<port>2181</port>
</node>
</zookeeper>
<macros>
<shard>01</shard>
<replica>01</replica>
</macros>
</yandex>
I don't know where is wrong, can someone help me? Thank u
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68114856",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Returning generated HTML from .NET Core controller I have a .NET Core 2 app that needs to be able to return generated HTML from a controller. I've been able to get it returning the HTML as plain text, but not to persuade the browser that it's HTML and render that; as soon as an HTML content type is provided, the content type negotiation appears to break it and it just renders a 406 Not Acceptable.
(Simplified) options I've tried -
[HttpGet]
[Produces("text/html")]
public string Display()
{
return "<html><head><title>Testing</title><head><body>Hello, world!</body></html>";
}
[HttpGet]
[Produces("text/html")]
public HttpResponseMessage Display()
{
try
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("<html><head><title>Testing</title><head><body>Hello, world!</body></html>")
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
return response;
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return new HttpResponseMessage(HttpStatusCode.InternalServerError);
}
}
[HttpGet]
[Produces("text/html")]
public IActionResult Display()
{
var pageHtml = "<html><head><title>Testing</title><head><body>Hello, world!</body></html>";
var result = StatusCode(200, pageHtml);
result.ContentTypes.Add(new MediaTypeHeaderValue("text/html"));
return StatusCode(200, pageHtml);
}
The Startup.ConfigureServices method has been tried with all combinations I can think of of the RespectBrowserAcceptHeader and ReturnHttpNotAcceptable properties, but they didn't seem to make a difference.
Can anyone see what I've missed to persuade the server to just return the generated HTML?
A: How/why are you generating html yourself? I think an eaiser solution might be to make an ASP.NET Core 2 MVC app. That will allow you to use ViewModels. I'd take a look into that.
Anyways, try returning Content... this returns a Http Status code of 200, and will allow you to return a string with other details of how the content is formatted.
[HttpGet]
[Produces("text/html")]
public IActionResult Display()
{
return Content("<html><h1>hello world!</h1></html>", "text/html", Encoding.UTF8);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56120838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Month number to month name in php I think the title is clear!
I want to make to take a number between 1-12 and give back the name of the month in that number (and if possible I want to have custom names for months).
A: Make an array for your month names like so
$montnames = ['', "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dez"];
Trick is to leave first one empty, because months begin with 1 and arrays count at 0.
echo $month[2]; // feb
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51999716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
}
|
Q: Testing Parse Server Cloud Code on Node.js fails "Parse.Cloud.beforeSave is not a function" I'm attempting to implement automated tests in my parse server repository that I run in node.js in my development environment. However, it appears that some of the functions available in the parse cloud code SDK are not available in the NPM parse library. In particular, test code imports
Parse = require('parse/node');
And then my code calls Parse.Cloud.beforeSave. This causes the error Parse.Cloud.beforeSave is not a function. How can I get around this?
A: Edit:
I published an NPM library called parse-node-with-cloud that provides a Parse.Cloud object in node.js. I hope this will enable node.js unit tests of Parse cloud code.
===========
My solution to this is to use the parse-cloud-express library on NPM. Import it with
const Parse = require('parse-cloud-express').Parse;
Then Parse.Cloud functions will work as expected.
Unfortunately, the source code is no longer available on github and the module is likely no longer maintained.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41967668",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can't get div height when including javascript in Django template I'm trying to use the flot plugin for jquery and it keeps on complaining that a div has a width/height of zero. I'm actually including the javascript for this in a Django template. So my template file looks like:
<style>
#graph {
width: 100px;
height: 100px;
}
</style>
<script>
$.plot(stuff)
console.log($(#graph).width())
</script>
<div id="#graph">
</div>
This template code is inserted into the DOM of another page with AJAX.
$.ajax({
url: 'something',
success: function(data){ $("#content").html(data);
console.log($("#graph").width()) }
});
For some reason, I can't get the width to be non-zero, but if I test the width in the "success" function from the ajax call, it returns correctly. Is something wrong with the order that commands are being run/placed into the DOM?
A: Well, in your first code block, you are checking the width of your DIV before you actually create the DIV in your markup, and sense you aren't using a DOMReady event or Window Loaded event, it will come up 0 or null at best.
So, if you just move your script block below the div in your first example that will fix that.
I imagine you will find a similar situation in your second example but I can't be sure without seeing more code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1467288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Adding to instance based on if statements? I'm a new coder trying to create a simple "Sword crafting" terminal app in ruby.
So I've got a class with a few instanced variables I want to iterate upon depending on the users input (@strength and @speed). So here, if the user inputs that the grip is "straight" i want it to increase the instance variable "strength" by 5 - but for some reason it's not editing it no matter what I do. I've already set "strength" as attr_accessor, and i've tried making the method manually as well - but I still can't iterate upon it. What am i doing wrong?
class Weapon
attr_reader :id, :weapon_name, :guard, :blade
attr_accessor :grip, :strength, :speed
SWORDS = []
def initialize(weapon_name, grip, guard, blade)
@id = SWORDS.length + 1
@weapon_name = weapon_name
@grip = grip.to_str
@guard = guard
@blade = blade
@strength = 0
@speed = 0
SWORDS << self
end
def strength=(strength)
if @grip == "straight"
@strength = strength + 5
end
end
def to_s
"Your weapon is called: #{@weapon_name}
The grip is: #{@grip}
The guard is: #{@guard}
The blade is: #{@blade}
Total stats are: Strength = #{@strength} and Speed = #{@speed}"
end
end
A: Accessors are only called if you refer to a name on the class.
@strength = 0
This doesn't call an accessor. Ever. Even if one is defined.
self.strength = 0
This will call an accessor. Now, attr_accessor defines strength and strength=. If you're planning to write strength= yourself, then you want attr_reader, which does not define strength= for you.
class Weapon
attr_reader :strength
def initialize()
...
self.strength = 0
end
...
def strength=(value)
...
end
end
A: It might be easier to modify the getter:
class Weapon
attr_accessor :grip, :strength
# ...
def strength
if grip == 'straight'
@strength + 5
else
@strength
end
end
end
w = Weapon.new
w.strength = 10
w.strength
#=> 10
Since the getter always re-calculates the value, you can modify both, strength and grip and it will instantly reflect the change:
w.grip = 'straight'
w.strength
#=> 15
w.strength = 12
w.strength
#=> 17
w.grip = 'curved'
w.strength
#=> 12
To avoid confusion, you could call the initial strength base_strength.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66948006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How to prevent PyMongo from mutating inserted dict? If a document doesn't have an _id field, MongoDB automatically assigns a proper _id field for inserted document, I get that and that's fine for me.
But why pymongo mutates the inserted dict by adding _id field?
I want to use the inserted dict after it gets inserted and that extra _id field is a little bit problem.
I know I can use dict.pop('_id') to drop _id field, but if it is a list of documents(for insert_many) then that need an extra effort.
My question is, is there a way to prevent the inserted dict or List[dict] being mutated by _id field?
A: You could prevent this by inserting a copy of the dictionary or list of dictionary
In [1]: from copy import deepcopy
In [2]: from pymongo import MongoClient
In [3]: data = [{'a': 2}, {'a': 3}]
In [4]: with MongoClient() as client:
...: client.test.collection.drop()
...: result = client.test.collection.insert_many(deepcopy(data))
...:
In [5]: result.inserted_ids
[ObjectId('5a819d34d99e830381e025b0'), ObjectId('5a819d34d99e830381e025b1')]
In [6]: data
Out[6]: [{'a': 2}, {'a': 3}]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48732280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Initializing class object I am new to Java. I apologize if I ask a simple thing.
I wrote the below code but it seems that it doesn't initialize properly. because when I print the size of list1 it show the size = 0!! However, it should be 4!
public static class MyClass{
public List <Integer> list1
// Class Constructor
public MyClass(int n){
list1 = new ArrayList <Integer> (n);
System.out.println("Size = " + list1.size() );
// prints Size = 0 !!!why???
}
public void init(int n){
for(int cnt1 = 0; cnt1 < list1.size(); cnt1++){
list1.set(cnt1 , cnt1);
}
}
...}
public static List<Integer> Func1(int n){
MyClass = new myclass (n);
myclass.init(n);
... }
public static void main(String args[]){
int n = 4;
result = Func1 (n);
...}
Why the size of the list1 is 0? It should be 4, because I pass 4 to Func1, and then it creates MyClass object with size n.
I would be thankful if someone can help me about this problem.
A: Array lists in Java have both a size and a capacity.
*
*Size tells you how many items are there in the list, while
*Capacity tells you how many items the list can hold before it needs to resize.
When you call ArrayList(int) constructor, you set the capacity, not the size, of the newly created array list. That is why you see zero printed out when you get the size.
Having a capacity of 4 means that you can add four integers to the list without triggering a resize, yet the list has zero elements until you start adding some data to it.
A: You have used the ArrayList constructor that determines its initial capacity, not its initial size. The list has a capacity of 4, but nothing has been added yet, so its size is still 0.
Quoting from the linked Javadocs:
Constructs an empty list with the specified initial capacity.
Also, don't use set to add to the list. That method replaces an element that is already there. You must add to the list first (or use the other overloaded add method).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19502577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is this a proper way of using AJAX with jQuery and PHP? I need some help. I'm going use AJAX (for the first time) and I'd like you to tell me whether the way I am going to show you is optimal.
Let's say that I have a select element.
<select class="update-db" data-id="25" data-original-value="2">
<option value="1">Yellow</option>
<option value="2" selected="selected">Red</option>
<option value="3">Blue</option>
</select>
So here is what I do:
$(document).on('change', 'select.update-db', function() {
// Get needed data
var select = $(this);
var id = select.attr('data-id');
var originalValue = select.attr('data-original-value');
var newValue = select.val();
// Perform the request
$.ajax({
method: 'POST',
url: 'update-db.php',
data: { id: id, 'original-value': originalValue, 'new-value': newValue }
});
// Then, if everything is okay, change the "original value" of the select element
// so that we can perform the updating operation again without having to refresh the page
.done(function() {
select.attr('data-original-value', newValue);
});
});
Then, on the other side, a PHP script validates everything and updates the database.
Is this the correct way of using AJAX? I feel it's not. What am I doing wrong?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32314969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Convert array of objects into number for inject sum I am using Ruby 1.9.2, Rails 3.1. I have the following:
# review.rb
def calculate_rating
all_rating = Review.select("rating").where("reviewable_id = ?", self.reviewable_id)
all_rating.inject(:+)
end
# reviews_controller.rb
def create
@reviewable = find_reviewable
@review = @reviewable.reviews.where("user_id = ?", current_user).first
if @review.save
@review.calculate_rating
redirect_to :id => nil
else
flash[:error] = 'Error saving review. Please try again.'
redirect_to :id => nil
end
end
The idea behind this is that when a new review with rating is submitted and saved, it will find all ratings for all @reviewable, sum all the ratings and divide by the total number of ratings.
Problem that I am facing currently is this line: all_rating = Review.select("rating").where("reviewable_id = ?", self.reviewable_id) where all_rating returns an array of objects, like below:
[#<Review rating: #<BigDecimal:1050f0a40,'0.3E1',9(18)>>, #<Review rating: #<BigDecimal:1050f0928,'0.1E1',9(18)>>]
which I can't do any arithmetic calculation to it. I need it to be an array of numbers before I could use the inject to sum it and divide by the number of ratings.
Please advise me how I can get the inject to work. Many thanks!
A: AR/SQL (faster):
Review.select("rating").where(:reviewable_id => self.reviewable_id).sum(:rating)
Ruby (slower):
Review.select("rating").where(:reviewable_id => self.reviewable_id).map(&:rating).sum
A: How about just doing this:
def calculate_rating
all_rating = Review.select(:rating).where(:reviewable_id => reviewable_id).map(&:rating)
all_rating.inject(:+) # or you could just do all_rating.sum
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8564174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I select specific parts of an image in android? If you have used photoshop, they have a tool that allows you to select parts of an image in order to edit specific locations within an image. Such as having a picture of a basketball and selecting that basketball with the use of the lasso tool in photoshop so you can make the rest of the image black and white.
I was wondering if there is any pre-defined class in the Android resource library that can make this sort of selection. Or would i have to make my own class that would look for a pattern in an image? Basically is there a tool available in android that can make these image selections that I can use inside my app?
It would also be helpful if someone can point me towards a reading on the subject of image selection programming or a third party library. I can't seem to find anything specific.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12290271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What is good naming form for variables in loops JS? Hi so as I mentioned in the title I have a bunch of loops within loops in my code and most of them use a variable to loop through stuff. I call my variables ia, then ib then ic and so on. What is good form for the naming of these variables?
Here is some code that might help make sense of what I am saying
for (var ic = 0; ic <= currState.length; ic++) { //loop the columns and check if there is a
if (currState[ic] == 0) {
for (var id = 1; id <= currState.length; id++) { //loop the rows of a column
tryPos = [id, ic + 1]; //id -> row | ic -> column
if (checkClash(currState, tryPos) == false) {
currState[ic] = id
break;
}
}
}
}
A: The name of your variables requires good descriptive skills and a shared cultural background.
In this case you should use row and col but don't forget the scope of your variables.
I would like recommend you read the Book: Clean Code.
Especially you can review some of the proposed rules on this post (http://www.itiseezee.com/?p=83).
A: looping over a table or grid, row and column are perfectly fine variable names.
for more generic nested loops i, j, and k (in that order) are typical counter variables even though they are less aptly named
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34076316",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C++ code execution time depends on code structre I came across this great youtube tutorial and in one of the slides I saw something I didn't understand. Why is this happening? Is this compiler related?
Version #1 looks like this:
const int N = 5000;
float a [N*N];
for (int x=0; x<n; ++x)
for(int y=0; y<N; ++y)
sum+=a[x+y*N];
and takes about 239.4ms to execute.
And version #2 looks like this:
const int N = 5000;
float a [N*N];
for (int y=0; y<n; ++y)
for(int x=0; x<N; ++x)
sum+=a[x+y*N];
and takes about 79.5ms to execute.
Why is this happening?
A: The second example demonstrates better data locality since it accesses elements in the same row. Basically it performs sequential memory read, while first example jumps over sizeof(float) * N bytes on each iteration putting extra stress on CPU cache / memory.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52905839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using where clause for R Variable in R script to use it in SQL statement I have two tables; viz
table1 = PID (primary key) + 20 other columns & 200 records from database1 AND
table2 = [Serial no] (primary key) + 10 other columns & 300 records from database2.
I am trying to extract values from table2 where PID = [Serial no].
Note: PID = [SCK34ICV7, NSCK876DL, ......].
I refered "Pass string Variable in R script to use it in SQL statement"
t1 <- sqlquery(db1, "select * from table1")
r1 <- t1$PID
class(r1) = 'factor'
t2 <- sqlquery(db2, "select * from table2 where [Serial no] = '(",r1,")' ",sep ="")
I also tried other functions viz paste0(), fn$ from gsubfn and sprintf() and getting error like - 'c is not a recognized built in function name' ; 'Incorrect syntax'.
Please suggest the best way to do it.
Reg,
Mrutyunjaya
A: Your query is off. See here for what the proper format should be.
r1 <- c("PID1","PID2","PID3")
wrong
paste("select * from table2 where [Serial no] = '(",r1,")' ",sep ="")
output:
[1] "select * from table2 where [Serial no] = '(PID1)' " "select * from table2 where [Serial no] = '(PID2)' " "select * from table2 where [Serial no] = '(PID3)' "
correct
paste("select * from table2 where [Serial no] IN (",paste(r1,collapse=", "),") ",sep ="")
Output:
[1] "select * from table2 where [Serial no] IN (PID1, PID2, PID3) "
So the query becomes:
t2 <- sqlquery(db2,paste0("select * from table2 where [Serial no] IN (",paste(r1,collapse=", "),") ",sep =""))
Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45544722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: PGM image not opening I have a pgm file which is well formatted like this
P2
# CREATOR: GIMP PNM Filter Version 1.1
19 19
0 71 73 74 73 73 74 73 71 70 71 74 72 69 68 71 72 66 69
70 70 74 70 69 69 69 69 71 68 70 72 66 70 71 69 65 68 69
66 72 73 74 74 73 70 73 72 66 70 68 67 68 68 68 67 66 69
66 72 78 74 74 73 71 71 70 70 68 70 66 69 66 65 66 62 62
62 72 76 72 73 75 72 71 68 74 71 68 66 70 65 67 62 56 57
66 70 72 71 72 69 72 73 74 69 65 66 60 64 68 93 99 139 225
240 68 71 70 70 69 70 71 64 64 46 60 57 86 153 206 233 240 244
245 72 69 70 68 67 68 68 68 61 58 82 178 229 236 236 229 238 244
245 74 67 67 70 68 66 69 65 64 97 218 240 242 235 234 240 243 244
244 75 74 73 72 69 68 73 74 128 223 239 242 239 242 243 242 244 241
244 72 76 74 72 69 71 68 83 155 234 242 240 237 242 237 241 240 245
243 72 75 75 71 68 69 65 68 127 237 241 240 241 243 245 244 244 245
244 72 71 69 71 66 66 63 63 107 239 240 244 245 245 246 245 246 246
246 72 70 70 67 64 63 60 74 218 242 245 245 245 245 246 246 247 246
245 73 72 71 70 70 66 61 201 241 244 245 246 245 246 247 246 247 246
247 71 69 71 68 63 61 115 236 239 244 244 245 245 246 246 246 246 246
245 78 72 73 73 68 63 167 243 244 244 245 245 245 246 246 246 246 246
245 75 72 69 71 67 61 218 245 245 246 246 246 246 246 246 246 247 246
246 76 72 72 68 65 74 238 246 246 246 247 246 246 246 246 246 246 246
But trying to open it with "visionneur d'images" on ubuntu i get an error :
Please help me.. I don't know what is the issue.
A: The number after image dimensions is supposed to be the maximum value in the image. You have it as '0'. Scanning quickly through the data, the value should be 247. Just replace the 0 with 247, using a text editor.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52790205",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there a destructor for a pointer in c++? string * str=new string;
delete str;
when I delete 'str' which points to an object, do two destructors get called - one for the pointer itself, and one for the object it points to?
What would the pointer's destructor do?
A: The concept of destructor is applicable only to objects (i.e. entities defined with class or struct), not to plain types, like a pointer is. A pointer lives just like a int variable does.
A: The pointer it self doesn't been destructed by the delete statement. but as any scope variable it's been destroyed when the scope ends.
Example:
void Function()
{
string * str=new string;
delete str; // <-- here the string is destructed
} // <-- here the pointer is "destructed", which is mean it's memory freed from the stuck but no actual destruction function is called..
A: delete just causes the object that the given pointer is pointing at to be destroyed (in this case, the string object. The pointer itself, denoted by str, has automatic storage duration and will be destroyed when it goes out of scope like any other local variable.
Note, however, that non-class types do not have destructors. So even when you use delete with non-class types, no destructor is called, but when the pointer goes out of scope, it gets destroyed as normally happens with any other automatic variable (means the pointer just reaches the end of its lifetime, though the memory pointed to by the pointer is not deallocated until you use delete to explicitly deallocate it.).
A:
when I delete 'str' which points to an object, do two destructors get called - one for the pointer itself, and one for the object it points to?
No. delete takes a pointer argument. It destroys the object that's pointed to (using its destructor, if it has one, and doing nothing otherwise), and deallocates the memory that's pointed to. You must previously have used new to allocate the memory and create the object there.
The pointer itself is not affected; but it no longer points to a valid object, so you mustn't do anything with it. This is sometimes known as a "dangling pointer".
What would the pointer's destructor do?
Nothing. Only class types have destructors.
A: The destructor for a raw pointer, like your example of std::string*, is trivial (just like the destructors for other primitive types: int, double, etc.)
Smart pointer classes have non-trivial destructors that do things like free resources, adjust reference counts, etc.
A: I like the simplification you get from the notion that every type has a destructor. That way you don't have a mental glitch with a template that explicitly destroys a stored value, even if the type of that stored value is an int or a pointer:
template <class T> struct wrapper {
unsigned char data[sizeof(T)];
wrapper(T t) { ptr = new (data) T; }
~wrapper() { (T*)&data->~T(); } // ignore possible alignment problem
wrapper<int> i(3);
However, the destructors for ints and pointers are utterly trivial: they don't do anything, and there is no place you can go to see the definition of the destructor, because the definition doesn't exist. So it's also reasonable to say that they don't have destructors.
Either way, when a pointer goes out of scope it simply disappears; no special code runs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16436797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Prevent table cells from breaking across page when converting html to pdf Using Google Apps Script, I have an html template that I fill and then send out (via fax and/or email) as a pdf. The template includes a two-column table with questions/answers.
If there are enough rows, the table breaks across pages in the pdf, and the page breaks usually happen in the middle of cells; I'd like to avoid this.
I've tried using break-inside: avoid; in both the <tr> and <td> elements, with no effect.
Here's the template:
<table style="border-collapse: collapse; border: 1px solid black; table-layout: fixed; width: 100%;">
<tbody>
<tr>
<th style="border: 1px solid black; width: 30%; padding: 5px;">Question</th>
<th style="border: 1px solid black; width: 70%; padding: 5px;">Response</th>
</tr>
<? rows.forEach(function(row){ ?>
<tr style="break-inside: avoid;">
<td style="break-inside: avoid; border: 1px solid black; padding: 5px; line-height: 1.5rem;"> <?= row.question ?> </td>
<td style="break-inside: avoid; border: 1px solid black; padding: 5px; line-height: 1.5rem;"> <?!= row.answer ?> </td>
</tr>
<? }) ?>
</tbody>
</table>
and here's the Apps Script code that converts it to pdf:
var html = '<h3>' + subject + '</h3>'
var tableTemplate = HtmlService.createTemplateFromFile('response-table-template')
tableTemplate.rows = rows;
html += tableTemplate.evaluate().getContent();
var blob = Utilities.newBlob(html, MimeType.HTML, subject).getAs(MimeType.PDF);
and then the blob is attached to an email/fax. All of that works fine except for my question: Is there a way to avoid breaking table rows over the pages? Possibly another way to convert the html to pdf that respects the break-inside property? Or an html/css solution that will be respected by Apps Script when converting the html blob to pdf?
A: Unfortunately, in the current stage, it seems that break-inside is not reflected to Utilities.newBlob(html, MimeType.HTML, subject).getAs(MimeType.PDF). But I'm not sure whether this is the current specification. So as a workaround, in your case, how about the following flow?
*
*Prepare HTML data.
*
*This has already been prepared in your script.
*Convert HTML data to Google Document.
*
*In this case, Drive API is used.
*Convert Google Document to PDF data.
*Create blob as a file.
When your script is modified, it becomes as follows.
Modified script:
Before you use this script, please enable Drive API at Advanced Google services.
From:
var blob = Utilities.newBlob(html, MimeType.HTML, subject).getAs(MimeType.PDF);
To:
// 1. Prepare HTML data.
var blob = Utilities.newBlob(html, MimeType.HTML, subject);
// 2. Convert HTML data to Google Doc
var id = Drive.Files.insert({title: subject, mimeType: MimeType.GOOGLE_DOCS}, blob).id;
// 3. Convert Google Document to PDF data.
var url = "https://docs.google.com/feeds/download/documents/export/Export?exportFormat=pdf&id=" + id;
var pdf = UrlFetchApp.fetch(url, {headers: {authorization: "Bearer " + ScriptApp.getOAuthToken()}}).getBlob().setName(subject);
DriveApp.getFileById(id).setTrashed(true);
// 4. Create blob as a file.
DriveApp.createFile(pdf);
Reference:
*
*Files: insert
A: By experimentation I found that Utilities.newBlob(html, MimeType.HTML, subject).getAs(MimeType.PDF) will respect page-break-inside: avoid; (rather than break-inside: avoid;) but only if it's applied to an entire table. So I had to treat each table row as a separate table. This version of the html template solved the problem:
<table style="border-collapse: collapse; border: 1px solid black; table-layout: fixed; width: 100%;">
<tbody>
<tr>
<th style="border: 1px solid black; width: 30%; padding: 5px;">Question</th>
<th style="border: 1px solid black; width: 70%; padding: 5px;">Response</th>
</tr>
</tbody>
</table>
<? rows.forEach(function(row){ ?>
<table style="page-break-inside: avoid; border-collapse: collapse; border: 1px solid black; table-layout: fixed; width: 100%;">
<tbody>
<tr>
<td style="width: 30%; border: 1px solid black; padding: 5px; line-height: 1.5rem;"> <?= row.question ?> </td>
<td style="width: 70%; avoid; border: 1px solid black; padding: 5px; line-height: 1.5rem;"> <?!= row.answer ?> </td>
</tr>
</tbody>
</table>
<? }) ?>
For the record, converting to a Google Doc and then to pdf did not solve the problem; it appears that Google Doc also allows table cells to break across pages. However, writing the data to a Google Sheet and then downloading as pdf does prevent breaking cells across pages; Sheets seems to take care of this automatically, so that's an alternate solution.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64235450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Random number generator for python based discord bot What I am trying to do is when someone enters the command !random (argument) I want the bot to generate a number between 1 and what they put as the argument. But whenever I try to do this it gives me around 6 different errors that are very long and make no sense to me. My current code for this command is below.
@Bot.command(pass_context=True)
async def random1and10(ctx, number):
arg = random.randint(1, number)
if number:
await Bot.say(arg)
else:
await Bot.say('Please select a valid number')
A: I guess number is passed as a string, so:
*
*you need to cast it to an integer before passing it to randint
*probably need to cast it to a string again before "saying" it
What's more, you're not using the correct way to check for wrong integer values; if number will never be False because your randint call will only return integers greater than 0 (or raise an error).
A fixed version would be something like:
@Bot.command(pass_context=True)
async def random1and10(ctx, number):
try:
arg = random.randint(1, int(number))
except ValueError:
await Bot.say("Invalid number")
else:
await Bot.say(str(arg))
Your mileage may vary, I didn't run it. I'm not sure about the decorated function signature.
whenever I try to do this it gives me around 6 different errors that are very long and make no sense to me.
Maybe they can make sense to others :) I'm relatively new to this site, but I think including them in your post would have been better. Cheers !
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49577305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Example for customizing the ignored pattern list in Django's collectstatic Like other questions here, I want to ignore my .scss files when running collectstatic. But because I'm using Heroku, which runs a collectstatic automatically, I would rather customize collectstatic's ignore pattern list rather than change the management command.
Django 2.2 provides a way to do this, as documented below:
The default ignored pattern list, ['CVS', '.', '~'], can be
customized in a more persistent way than providing the --ignore
command option at each collectstatic invocation. Provide a custom
AppConfig class, override the ignore_patterns attribute of this class
and replace 'django.contrib.staticfiles' with that class path in your
INSTALLED_APPS setting:
from django.contrib.staticfiles.apps import StaticFilesConfig
class MyStaticFilesConfig(StaticFilesConfig):
ignore_patterns = [...] # your custom ignore list
My problem is that, this being my first Django project, I don't quite know how to provide a custom AppConfig class (and diving into the AppConfig docs hasn't helped). I mean, should I add this class to a whole new app or use an existing one? Is this class going to be in a apps.py file? If so, what should be the best app to do so? So I'm asking if anyone could provide me with an example of the best practice.
For reference, right now my app structure is like this (with all templates, assets and apps grouped together in their own folders rather than within each app):
-- project_name
-- assets
-- app1
-- templates
-- project_name
-- app1
-- app2
-- __init__.py
-- settings.py
-- urls.py
-- wsgi.py
UPDATE:
As Nico suggested, I've created an app called static in project_name.project_name with only an init.py file and an apps.py. The apps.py is exactly like the doc example:
from django.contrib.staticfiles.apps import StaticFilesConfig
class StaticConfig(StaticFilesConfig):
name = 'static'
ignore_patterns = ['CVS', '.*', '*~', '*.scss']
However, I'm running into errors when replacing 'django.contrib.staticfiles' from INSTALLED_APPS.
*
*Replacing it for 'project_name.static' makes the terminal not understand the collectstatic management command.
*Adding 'project_name' after 'django.contrib.staticfiles' (i.e.
not removing the later) makes it ignore the overwrite and collect the
.scss files.
*Replacing for 'project_name.static.apps.StaticConfig' throws a
Cannot import 'static'. error
UPDATE 2:
After I rollbacked the app creation, I tried is again, but now, instead of using the startapp with the file path, I created the app on the project root, tested it, then moved it manually to my apps' folders, and tested it again. For some reason I don't quite understand, this time I replaced 'django.contrib.staticfiles' for 'project_name.static' and now it worked.
A: You can add it to some other app, or even create just a file called static in the root of project_name and refer to the class inside this file in your settings.INSTALLED_APPS directly, but the recommended way to provide AppConfigs is inside an apps.py file inside the application package.
If you have no app where this AppConfig could be placed, I think the best practice would be to create a package under project_name.project_name called static, with only an init.py file and an apps.py file.
In this file you can create your AppConfig in the way you described.
Your file structure will then look like this:
-- project_name
-- assets
-- app1
-- templates
-- project_name
-- app1
-- app2
-- static
-- __init__.py
-- apps.py
-- __init__.py
-- settings.py
-- urls.py
-- wsgi.py
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57921970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Revoke drive access through Google Play Services Is there a way to revoke drive access granted through Google Play Services?
Referring to this article:
https://developer.android.com/google/auth/api-client.html
I granted access to g drive from my app like so:
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
My question is, is there a clean way to revoke g drive access
i.e. without needing to do credential.getToken() and making http call to https://accounts.google.com/o/oauth2/revoke?token=
I'm looking for something like Drive.DriveApi.revokeAccessAndDisconnect();
I know there is one for g plus, but i cant find one for g drive.
http://developer.android.com/reference/com/google/android/gms/plus/Account.html
A: Yes, there is an method for revoking of Google Drive scope.
GoogleSignInClient googleSignInClient = buildGoogleSignInClient();
googleSignInClient.revokeAccess().addOnCompleteListener(onCompleteListener);
where
private GoogleSignInClient buildGoogleSignInClient() {
GoogleSignInOptions signInOptions =
new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(Drive.SCOPE_FILE)
.build();
return GoogleSignIn.getClient(this, signInOptions);
}
For more information, you can check this reference
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24558356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Django - deleting users with on_delete=models.CASCADE causes problems with signals.post_delete We are using Django 3.1 for our websites. We have a model, User, which is related to two SiteProfile models for two websites, and is also related to other models such as Friend and UserEmailAddress. All the relations are with on_delete=models.CASCADE. We also have models.signals.post_delete signals for models such as Friend, to update the number of friends a user has, which is saved in one of the SiteProfile models. But the problem is, when deleting a user, the signal is called and then the SiteProfile object is saved, and then I get an exception for django.db.utils.IntegrityError - violations of foreign keys. We used to have the same problem with the UserEmailAddress model (a user's email address), which I fixed with the following code:
def delete(self, *args, **kwargs):
if ((self.is_staff) or (self.is_superuser)):
warnings.warn('Can’t delete staff user.')
return False
else:
with transaction.atomic():
for user_email_address in self.email_addresses.all():
user_email_address.delete()
return_value = super().delete(*args, **kwargs)
return return_value
But I would like to know, is there a better way to delete a user with all its related objects which have on_delete=models.CASCADE, but without saving the counters in models.signals.post_delete to the database? Can I check something in models.signals.post_delete to know if the user is being deleted and then don't save the counters? Since I don't want to specifically delete any related object in the def delete method - there are at least 5 such models not including the two SiteProfile models.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66305134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: F# unit of measure to model area How can I use F# unit of measure to model the area of certain geometries.
The code i have so far is this but it isn't quite compiling.
[<Measure>] type radius
[<Measure>] type PI
[<Measure>] type area
let convertRadiusToArea (r:float<radius>) : float<area> =
// let pi = System.Math.PI
let a:float<PI> = 3.14<PI>
r * r * System.Math.PI
A: There are several things here:
*
*You need to define area as being a square length with type area = radius * radius. Otherwise the compiler has no way to match your input and output units.
*Pi, when used like this, is dimensionless, which is represented in F# as <1> or just no unit suffix.
[<Measure>] type radius
[<Measure>] type area = radius * radius
let convertRadiusToArea (r:float<radius>) : float<area> =
let pi = System.Math.PI
r * r * pi
A: A better example of using F#'s unit of measure would be this:
[<Measure>] type cm
let convertRadiusToArea(r:float<cm>) : float<cm^2> =
r * r * System.Math.PI
The idea being that you get benefits of the units of measurement in your calculations and derivations. You're not getting that by creating a unit of measure called 'radius'. Is it in meters? Feet? Centimetres? And that is why you would introduce them into an F# function, to be non-ambiguous about the unit of measurement for the inputs and outputs.
Units of measure in F# should IMO be modelled the way we use units of measurement in any other calculations or real world example like speed, temperature, force etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58064063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: NSG Configuration Management I am looking for a tool or some way to manage the Azure NSG configuration. NSG rules are changed manually on ad-hoc basis at the moment. I am looking to implement this NSG config change in more scripted fashion so that I can track the changes history as well.
I am looking at Git based repository of NSG where all ARM templates for NSG with different parameter files and run via those via Azure powershell or running as part of Azure Devops CI/CD pipeline.
I am not sure if Ansible can help with this management of NSGs or Terraform can help.
I love to think about Ansible for this. Anyone knows about this requirement how NSG can be managed.
Thank you
A: You can manage Azure NSG configuration via ARM template, Teffaform and Ansible.
*
*ARM template
1,You can check out below examples to create ARM Template to manage Azure NSG.
Create a Network Security Group.
How to create NSGs using a template
Please check the official document for more examples.
2, After the ARM template is created and pushed to your git repo. You can create azure pipeline to automate the deployment. See tutorial here.
3, Then you need to create an azure Resource Manager service connection to connect your Azure subscription to Azure devops. See this thread for an example.
4, In your azure devops pipeline. You can use ARM template deployment task to deploy the ARM template.
steps:
- task: AzureResourceManagerTemplateDeployment@3
displayName: 'ARM Template deployment: Resource Group scope'
inputs:
azureResourceManagerConnection: 'azure Resource Manager service connection'
subscriptionId: '...'
resourceGroupName: '...'
location: 'East US'
csmFile: azuredeploy.json
csmParametersFile: azuredeploy.parameters.json
*
*Teffaform
1, Create Teffaform configuration file. See example here.
Check out terraform-azurerm-network-security-group module for more information.
2, Upload Teffaform configuration file to git repo. Create Azure devops pipeline
3, Create azure Resource Manager service connection like above using ARM template.
4, Use Terraform task in the azure devops pipeline.
steps:
- task: ms-devlabs.custom-terraform-tasks.custom-terraform-installer-task.TerraformInstaller@0
displayName: 'Install Terraform 0.12.3'
- task: ms-devlabs.custom-terraform-tasks.custom-terraform-release-task.TerraformTaskV1@0
displayName: 'Terraform : azurerm'
inputs:
command: apply
environmentServiceNameAzureRM: 'azure Resource Manager service connection'
*
*Ansible
1, Create Ansible playbook with plugin azure.azcollection.azure_rm_securitygroup
Please check out the example here.
2,Upload ansible playbook to git repo. Create Azure devops pipeline. Use Ansible task in your pipeline.
Please check out this detailed tutorial for more information about how to run ansible playbook in azure devops pipeline.
*
*Azure powershell/Azure CLI commands
You can using azure powershell or azure cli commands to manage azure nsg. And run the commands in Azure powershell task or azure cli task in azure devops pipeline.
Please check out this document for more information.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65912291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Macosx yosemite installing mysql-python config error I am trying install mysql-python but always throw error. The command is "pip install mysql-python". I searched in google and tried everything but i am still getting error.
I am using mamp, MAMP's path is "/Applications/MAMP". I tested mysql with php and there is no error, mysql is working. I also connected to mysql by navicat. I am sure that mysql is installed and it is working.
I put the error screenshoot.
A: You need libmysqlclient.so library to be able to install MySQLdb,
Which come with MySQL Server and client and can also be downloaded with MySQL Connector/C.
Locate the library and set your DYLD_LIBRARY_PATH to have the path where libmysqlclient.so is present.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29407584",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do i make a println list of random numbers with no duplicates? is there a way I can make the drawerList() method look at the output from the drawerNumber() and add them to an array. I want to store the outputs into an array list in order to find the duplicates and print out both the stored values and possibly make an if else statement that finds duplicates of the random numbers and mark those outputs as "already drawn" This is my first semester of CS and i am in the learning stages so i feel like what i'm trying to do is out of my knowledge and I'm not sure what to do.
import java.util.Scanner;
import java.util.Random;
class RandomNumbers{
public static void main(String [] args){
System.out.println(drawerNumbers());
}
//drawerNumbers()-draws new numbers
public static int drawerNumbers(){
Random rand = new Random();
int num = rand.nextInt(75)+1;
return num;
}
// drawerList()- List of numbers drawn
public static int drawerList(){ //Method.
String p = Integer.toString(drawerList()); //Convert method into string in order to be put in array
int[] numbers = new int[p.length()]; // creates the array to store the values
//
After this not sure how to make the outputs be listed to the console and how to make the program find the duplicate random numbers.
`
*
*Heading
` ##
A: It seems your intention is to randomly pick numbers between 1 and 75 without repeating a number. This is most easily done by inverting the problem to randomly ordering the numbers 1-75 then iterating through them:
List<Integer> nums = new ArrayList<Integer>(75);
for (int i = 1; i < 75; i++)
nums.add(i);
Collections.shuffle(nums);
Now they are in random order, just use them one by one:
for (Integer i : nums) {
// use i
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19942167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: How does this endian conversion work? A QNX library called gfpr.h contains the line
#define ENDIAN_LE16(__x) (__x)
which is used as follows
var1 = ENDIAN_LE16(var1);
to convert the endianness of (unsigned short) var1. How does this work? __x and x__ must have some special meaning to the preprocessor?
A: __x does not have a special meaning. ENDIAN_LE16 is a macro that makes a place to change endianness without changing your source code. Each build target can have a different version of gfpr.h specific for that target.
You must be compiling for a little-endian machine, so ENDIAN_LE16 doesn't need to make any changes. It just leaves its argument (__x) unchanged. If you were compiling for a big-endian target, ENDIAN_LE16 would be defined to swap the bytes of its argument. Something like:
#define ENDIAN_LE16(__x) ( (((x) & 0xff) << 8) | (((x) >> 8) & 0xff) )
That way, by changing which target's gfpr.h file you include, you get the right results without having to change your source code.
Edit Per the file you're probably looking at, ENDIAN_BE32 invokes ENDIAN_RET32, which twiddles bits in a way similar to what I showed above.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38151312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Live Reload of SCSS in React JS using Webpack I would like to ask if there's a way that the compiling of .scss file to .css is included in webpack hot reload, I use to always run npm run build to convert my .scss to .css
Here's my webpack.config:
var autoprefixer = require('autoprefixer');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
entry: './app/main.js',
output: {
path: './',
filename: 'index.js'
},
devServer: {
inline: true,
port: 3333
},
module: {
loaders: [
{
test: /\.js$/,
exclude: '/node_modules/',
loader: 'babel',
query: {
presets: ['es2015','react']
}
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader!sass-loader")
}
]
},
plugins: [
new ExtractTextPlugin('[name].css',{
allChunks: false
})
],
postcss: [
autoprefixer({
browsers: ['last 2 versions']
})
]
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36963473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Can the argument for Switch statement have an expression to eliminate a variable used for comparison? This program simulates a simple menu driven calculator with +, -, *, and / operations
#include <stdio.h>
#include <conio.h>
int main()
{
float a = 0, b = 0;
printf(" Enter two numbers: ");
scanf(" %f %f",&a ,&b);
puts(" Enter choice number of operation: ");
puts(" 1)Addition ");
puts(" 2)Subtraction ");
puts(" 3)Multiplication ");
puts(" 4)Division ");
flushall(); //To clear the trailing '\n'
switch( getchar() - 48 )
{
case 1: printf("The Sum of %.2f and %.2f is : %.2f",a,b,(a+b));
break;
case 2: printf("The Difference of %.2f and %.2f is : %.2f",a,b,(a-b));
break;
case 3: printf("The Product of %.2f and %.2f is : %.2f",a,b,(a*b));
break;
case 4: if ( b != 0 ) printf("The Quotient of %.2f and %.2f is : %.2f",a,b,(a/b));
else puts("Error, divide by zero not possible.");
break;
default: puts("Error, Invalid choice");
}
return 0;
}
Is it better this way? As I have avoided the usage of a variable, and equivalently described why the program crashes when the last input is not a valid choice, I don't think there is any need to add info about what was entered. It adds an extra variable into the picture.
A: Yes, switch statement can take an expression for the value on which you switch. Your code should work fine, except that getchar() would read the leftover '\n' character from scanf of the operands.
Add another call to getchar() before the switch to read and discard that extra character.
A: While the code is valid and correct, I'd do the following to make it more readable:
switch(getchar()) {
case '1': // ...
case '2': // ...
case '3': // ...
case '4': // ...
}
Or
switch(getchar() - '0') {
case 1: // ...
case 2: // ...
}
This is to avoid using the magic number 48, which may not be understood easily by readers.
Furthermore, you can discard input until the next \n using a simple while loop:
while(getchar() != '\n') ;
In addition to the \n, this will also read and discard anything before the newline.
A: switch ( expression )
So you have a valid expression and you can have a expression like you have if you really have a need for something like this.
Else
char ch = getchar(); /* or scanf(" %c",&ch); (Better)*/
int a = ch - '0';
switch(a)
{
}
A: For your answer : Yes the switch can accept an expression in its arguments but it should returns only one of these types char int short long int long long int it can be also signed or unsigned !
There is no need to make a cast for the expression getchar() - 48 because getchar() returns int and 48 is an int so th result would be an int
now after compiling you have to add 3 number one for the variable a and the second for the variable b and the third for the switch statement... for instance
$./executable_file
Enter two numbers: 1 2 3
A: Switch formatting
This is a suggested formatting of your switch statement. I disagree with the idea of using getchar() in the switch statement (though it is technically legal, it is simply a bad idea in practice), so I've replaced that with c:
int c;
/* c is set by some input operation.
** It might be char c; if you read its value with scanf(), but it must be int if you use getchar()
*/
switch (c)
{
case 1:
printf("The Sum of %.2f and %.2f is : %.2f", a, b, (a+b));
break;
case 2:
printf("The Difference of %.2f and %.2f is : %.2f", a, b, (a-b));
break;
case 3:
printf("The Product of %.2f and %.2f is : %.2f", a, b, (a*b));
break;
case 4:
if (b != 0)
printf("The Quotient of %.2f and %.2f is : %.2f",a, b, (a/b));
else
fputs("Error, divide by zero not possible.\n", stderr);
break;
default:
fprintf(stderr, "Error, Invalid choice %c\n", c);
break;
}
Note the use of break; after the default: label too; it protects you against future additions to the code and is completely uniform. (The default: label does not have to be last, though that is the conventional place for it to go.) Commas get a space after them; so do if, for, while, switch, but function calls do not get a space between the name and the open parenthesis. You don't normally need a space after an open parenthesis or before a close parenthesis. Errors are reported to standard error.
Personally, I like the actions of the switch to be indented just one level, not two levels, so I'd use:
switch (c)
{
case 1:
printf("The Sum of %.2f and %.2f is : %.2f", a, b, (a+b));
break;
case 2:
printf("The Difference of %.2f and %.2f is : %.2f", a, b, (a-b));
break;
case 3:
printf("The Product of %.2f and %.2f is : %.2f", a, b, (a*b));
break;
case 4:
if (b != 0)
printf("The Quotient of %.2f and %.2f is : %.2f",a, b, (a/b));
else
fputs("Error, divide by zero not possible.\n", stderr);
break;
default:
fprintf(stderr, "Error, Invalid choice %c\n", c);
break;
}
Many people disagree, so you're certainly not under an obligation to do that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27648935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: docker push doesn't use the correct repository and fails I'm trying to push a docker image to an Azure container repository and even after successfully "logging in" the push command tries to push it to docker.io and then fails.
Note: I am using Windows 10 Pro and have set up docker to to use the minikube docker dameon
How do I tell docker push to use my Azure container repo?
See the output:
A: You must tag your image with the Docker Registry URL and then push like this:
docker tag design-service dockerregistry.azurecr.io/design-service
docker push dockerregistry.azurecr.io/design-service
Note: The correct term is registry and not repository. A Docker registry holds repositories of tagged images.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45556753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Custom DetailView like function returns the same set of data - Django I have a view with a list of items and want to create a detail view of those items so i can update, enable or disable items, the problem I have is I always get the same set of data no matter what item I click on to get the details of.
I've posted this here multiple times now but never had an answer, maybe I am failing to explain my issue.
View that handles the details
def detalle_Items(request, pk):
model = Transaccion
template_name = 'inventario/carrito/test-template.html'
try:
items_update = Transaccion.objects.filter(activo=True, carrito_id=pk, herramienta_id=pk)
except Transaccion.DoesNotExist:
raise Http404()
return render(request, template_name, {'items_update':items_update})
This is where the function gets trigerred by the green "actualizar" button
No matter what button I press this is what I get:
This is my views.py set of functions for carrito:
# =========================================================================== #
# LOGICA PARA CREAR CARRITOS
# =========================================================================== #
# ===================> Logica relacinado con Cortadores <=====================#
def home_carrito(request):
template_name = 'inventario/carrito/createcarrito.html'
model = Carritos
carritos = Carritos.objects.all()
if carritos:
return render(request, template_name, {'carritos':carritos})
else:
return render(request,template_name)
class CarritoCreate(CreateView):
model = Carritos
fields = [
'no_carrito',
'empleado',
'activo',
]
class ItemCreate(CreateView):
model = Transaccion
fields = [
'carrito',
'herramienta',
]
def detalle_carrito(request, pk):
model = Carritos, Transaccion
template_name = 'inventario/carrito/detalles_carrito.html'
carritos = Carritos.objects.filter(pk=pk)
# GEST ALL TOOLS ASSIGN TO CARRITO'S PK THAT ARE ACTIVE
# TRY TO GET ALL ACTIVE ITEMS THAT BELONG TO CARRITO = PK AND AGREGATE TOTAL ITEMS PER TYPE
cantidades = Transaccion.objects.values('herramienta__description').annotate(Sum('cantidad')).filter(activo=True, carrito_id=pk)
# GEST ALL TOOLS ASSIGN TO CARRITO'S PK THAT ARE NOT ACTIVE
eliminados = Transaccion.objects.filter(activo=False,carrito_id=pk)
return render(request,template_name, {'carrito':carritos, 'trans':cantidades, 'eliminados':eliminados})
class CarritoUpdate(UpdateView):
model = Carritos
fields = [
'no_carrito',
'empleado',
'activo',
]
template_name_suffix = '_update_form'
def detalle_Items(request, pk):
model = Transaccion
template_name = 'inventario/carrito/test-template.html'
try:
items_update = Transaccion.objects.filter(activo=True, carrito_id=pk, herramienta_id=pk)
except Transaccion.DoesNotExist:
raise Http404()
return render(request, template_name, {'items_update':items_update})
class ItemUpdate(UpdateView):
model = Transaccion
fields = [
'carrito',
'herramienta',
'cantidad',
'tipo',
'motivo',
'activo',
]
template_name_suffix = '_update_form'
class ItemDelete(DeleteView):
model = Transaccion
success_url = reverse_lazy('item-herramienta')
And these are my models.py for carritos:
# =========================================================================== #
# MODELO PARA CREAR CARRITOS
# =========================================================================== #
class Carritos(models.Model):
no_carrito = models.CharField(max_length=3, unique=True)
empleado = models.OneToOneField(Empleados, on_delete=models.CASCADE)
# empleado = models.ManyToManyField(Empleados, through='Transaccion')
items = models.ManyToManyField(Item, through='Transaccion', related_name='carritos')
f_creacion = models.DateTimeField(auto_now_add=True)
f_actualizacion = models.DateTimeField(auto_now=True)
activo = models.BooleanField(default=True)
def get_absolute_url(self):
return reverse('inventario:carrito')#, kwargs={'pk': self.pk})
class Meta:
verbose_name_plural = "Carritos"
def __str__(self):
return self.no_carrito
class Transaccion(models.Model):
carrito = models.ForeignKey(Carritos, on_delete=models.CASCADE, related_name='items_carrito')
herramienta = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='items_carrito')
cantidad = models.PositiveSmallIntegerField(default=1)
activo = models.BooleanField(default=True)
tipo = models.CharField(max_length=10, choices=CONSUMIBLE, blank=True, null=True)
motivo = models.CharField(max_length=10, blank=True, null=True)
def get_absolute_url(self):
return reverse('inventario:carrito')#, kwargs={'pk': self.pk})
Template for image #1
{% extends "inventario/base.html" %}
{% block lista %}
<div class="container cf">
<div class="carrito">
{% if carrito %}
{% for c in carrito %}
<div class="side-panel">
<div class="info">
<p>Carrito:</p> <h1>{{c.no_carrito}}</h1>
<p>Asignado a:</p> <h1>{{c.empleado.nombre}} {{c.empleado.apellido}}</h1>
</div>
<div class="eliminados">
{% if eliminados %}
<!-- <table id="tablas" class="cf">
<tr class="theader">
<th>Herramienta dañadas</th>
<th>Motivo</th>
<th>Consumible?</th>
</tr>
{% for e in eliminados %}
<tr class="tr-eliminados">
<td>{{e.herramienta}}</td>
<td>{{e.motivo}}</td>
<td>{{e.tipo}}</td>
</tr>
{% endfor%}
</table> -->
{% else %}
<h2>No hay elementos eliminados</h2>
{% endif %}
</div>
<a href="" class="btn-carrito dec">Ver reporte de daños</a>
</div>
<div class="side-main">
<table id="tablas" class="cf">
<tr class="theader">
<td>Contenido de carrito</td>
<td>cantidad</td>
<td>actualizar</td>
</tr>
{% for i in trans %}
<tr class="list" >
<td>{{i.herramienta__description}}</td>
<td>{{i.cantidad__sum}}</td>
<td><a href="{% url 'inventario:actualizar-herramienta' pk=c.pk %}" class="btn-lista inc">Actualizar</a></td>
</tr>
{% endfor %}
</table>
<a href="{% url 'inventario:agregar-herramienta' pk=c.id %}" class="btn-carrito">Agregar</a>
</div>
{% endfor%}
{% else %}
<h1>No hay articulos por vencer</h1>
{%endif%}
</div>
</div>
{% endblock lista%}
Template for image #2
{% extends "inventario/base.html" %}
{% block lista %}
<div class="container">
<table id="tablas" class="cf">
<tr class="theader">
<td>Contenido de carrito</td>
<td>cantidad</td>
<td>actualizar</td>
</tr>
{% for i in items_update %}
<tr class="list" >
<td>{{i.herramienta}}</td>
<td>{{i.cantidad}}</td>
<td><a href="#" class="btn-lista dec">Actualizar</a></td>
</tr>
{% endfor %}
</table>
</div>
{% endblock lista%}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51544256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: multiple triggered subsystem + algebraic loop, initialisation problem I have a Simulink diagram which contains multiple triggered subsystem with different timestamp. In this model I also got a feedback loop inducing an algebraic loop. Therefore the signal must be initialised, in order to do that, I used a Memory block.
The problem is on the feedback loop, the value of the signal seems to be not initialised.
I believe the origin of this problem is that it is indeed initialised by the memory block for the first timestamp, however, the trigger on the next subsystem did not occur. By default, this subsytem puts its out signal value to be 0. The loop is therefore broken there.
Did someone already encounter this situation ? Any Tips ?
Thank you for your time.
A: You could add initialization blocks for your trigger values? I don't know about what SubSystem0 looks like inside, but its output could use an initialization block as well, this way you guarantee that you have an input to Subsystem
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62446969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Should Job/Step/Reader/Writer all be bean? As fars as all the examples from the Spring Batch reference doc , I see that those objects like job/step/reader/writer are all marked as @bean, like the following:
@Bean
public Job footballJob() {
return this.jobBuilderFactory.get("footballJob")
.listener(sampleListener())
...
.build();
}
@Bean
public Step sampleStep(PlatformTransactionManager transactionManager) {
return this.stepBuilderFactory.get("sampleStep")
.transactionManager(transactionManager)
.<String, String>chunk(10)
.reader(itemReader())
.writer(itemWriter())
.build();
}
I have a scenario that the server side will receive requests and run job concurrently(different job names or same job name with different jobparameters). The usage is to new a job object(including steps/reader/writers) in concurrent threads, so I propabaly will not state the job method as @bean and new a job each time.
And there is actually a differenence on how to transmit parameters to object like reader. If using @bean , parameters must be put in e.g. JobParameters to be late binding into object using @StepScope, like the following example:
@StepScope
@Bean
public FlatFileItemReader flatFileItemReader(@Value(
"#{jobParameters['input.file.name']}") String name) {
return new FlatFileItemReaderBuilder<Foo>()
.name("flatFileItemReader")
.resource(new FileSystemResource(name))
}
If not using @bean , I can just transmit parameter directly with no need to put data into JobParameter,like the following
public FlatFileItemReader flatFileItemReader(String name) {
return new FlatFileItemReaderBuilder<Foo>()
.name("flatFileItemReader")
.resource(new FileSystemResource(name))
}
Simple test shows that no @bean works. But I want to confirm formally:
1、 Is using @bean at job/step/reader/writer mandatory or not ?
2、 if it is not mandatory, when I new a object like reader, do I need to call afterPropertiesSet() manually?
Thanks!
A:
1、 Is using @bean at job/step/reader/writer mandatory or not ?
No, it is not mandatory to declare batch artefacts as beans. But you would want to at least declare the Job as a bean to benefit from Spring's dependency injection (like injecting the job repository reference into the job, etc) and be able to do something like:
ApplicationContext context = new AnnotationConfigApplicationContext(MyJobConfig.class);
Job job = context.getBean(Job.class);
JobLauncher jobLauncher = context.getBean(JobLauncher.class);
jobLauncher.run(job, new JobParameters());
2、 if it is not mandatory, when I new a object like reader, do I need to call afterPropertiesSet() manually?
I guess that by "when I new a object like reader" you mean create a new instance manually. In this case yes, if the object is not managed by Spring, you need to call that method yourself. If the object is declared as a bean, Spring will call
the afterPropertiesSet() method automatically. Here is a quick sample:
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TestAfterPropertiesSet {
@Bean
public MyBean myBean() {
return new MyBean();
}
public static void main(String[] args) throws Exception {
ApplicationContext context = new AnnotationConfigApplicationContext(TestAfterPropertiesSet.class);
MyBean myBean = context.getBean(MyBean.class);
myBean.sayHello();
}
static class MyBean implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("MyBean.afterPropertiesSet");
}
public void sayHello() {
System.out.println("Hello");
}
}
}
This prints:
MyBean.afterPropertiesSet
Hello
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67599478",
"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.