text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: header menu with a logo left is not being displayed I am new with HTML & CSS, and I Am having a weird issue where the logo path is properly rendered into the page, but however doesn't display on the site. how does it happen this? e.g. the logo is a SVG format where I don't see it's an issue, but I am not sure why it behaves like this
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css'>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<!-- partial:index.partial.html -->
<header> <!-- PAGE HEADER -->
<div class="header-logo">
<img src="https://www.svgrepo.com/show/128647/download.svg" alt="header-logo">
</div>
<nav class="header-menu">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">home</a></li>
<li><a href="#">home</a></li>
<li><a href="#">demo1</a></li>
</ul>
</nav>
</header>
</body>
</html>
css
header {
padding: 5% 5% 0;
display: flex;
align-items: center;
justify-content: space-between;
}
.header-logo {
margin-left: 0;
}
.header-menu ul {
display: flex;
}
.header-menu li {
margin-right: 40px;
color: hsl(243, 87%, 12%);
font-family: "Raleway", sans-serif;
list-style: none;
cursor: pointer;
font-size: 16px;
}
.header-menu li:after {
background: none repeat scroll 0 0 transparent;
bottom: 0;
content: "";
display: block;
height: 2px;
left: 50%;
background: hsl(260, 100%, 75%);
transition: width 0.3s ease 0s, left 0.3s ease 0s;
width: 0;
}
.header-menu li:hover:after {
width: 100%;
left: 0;
}
a{
text-decoration: none;
}
A: Give your logo a width and height.
<img src="https://www.svgrepo.com/show/128647/download.svg" height="150" width="150" alt="header-logo" />
A: Just add this code to your CSS:
.header-logo {
width: 2rem;
}
If you face any problem then let me know.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62963357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How Can an app take a screenshot while running in the background and save it on a server is it possible to make my App take a screenshot by code .. and then save it on server
(I'm using parse as a backend Server)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36867434",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I find the source file that causes the print_r display in PHP I'm wondering how would someone debug to find the source file (and perhaps line number in the code) that causes the print_r? Or is there a package that could be use for this kind of debugging during page load? Similar idea like console.log in the dev tool.
A: Probably the debug_print_backtrace() from PHP can help you.
These way you can see all the functions that have been called.
More details: http://php.net/manual/en/function.debug-print-backtrace.php
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31044603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android resumes my Activity even if i call FINISH on BackButton I have an activity A that launches B with an Intent. (B is a MapActivity and has some async code)
in B i have the following code
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
// Log.d(this.getClass().getName(), "back button pressed");
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
This simply not work. I mean that when I press the back button on the phone, the current activity B disappears and the activity A that launched B is shown.
If I press again on A the button that launch B, I see B is exactly how it was when I closed it. SAME text in textboxes, same Map position... So i think the activity B is not really closed.
How can I close it for real so when I launch again it, activity B is cleas as new born?
EDIT: just to make the question clearer:
I want it to work like this: when the user is on activity B and BACK button is pressed, B has to be closed and destroyed. When the user again launches B from A, B has to be launched as a NEW activity, with blank field, reset map, etc., etc., ... just like the first time the user launches B from A.
A: Instead of returning true, try returning super.onKeyDown(keyCode, event) after finish().
You can try 1 more thing: specify android:noHistory="true" in the manifest for that activity.
Specifying this attribute doesn't keep the activity on the Activity Stack.
http://developer.android.com/guide/topics/manifest/activity-element.html#nohist
A: Have you tried lauching B by calling startActivityForResult() in A?
Do all your processing in B and then ensure you call finish on it and this should clear all data in it.
Please let me know if it works.
A: It's obvious. OnSaveState is called when finishing activity, and this activity is popped out of the stack. Best practice for you to clear the situation is to log all the lifecycle events in both activities, it will help to figure out where to put initializing your B activity.
Yes, and one more thing try researching onNewIntent method in B activity i suppose it will be really helpfull
A: As i stated in my last comment to the post, @Jianhong given me the correct answer (aslso if as a comment). As he don't copied the comment as answer in time, i add this answer and mark it as the ACCEPTED. Thanks @Jianhong!
Answer:
@Jianhong OMG! you completely right! i checked for this problem in past days but i couldn't find it as... i've not UPDATED from SVN. my coworker inserted lines of code that prefill fields by some static var!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8525465",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Condition within JOIN or WHERE Is there any difference (performance, best-practice, etc...) between putting a condition in the JOIN clause vs. the WHERE clause?
For example...
-- Condition in JOIN
SELECT *
FROM dbo.Customers AS CUS
INNER JOIN dbo.Orders AS ORD
ON CUS.CustomerID = ORD.CustomerID
AND CUS.FirstName = 'John'
-- Condition in WHERE
SELECT *
FROM dbo.Customers AS CUS
INNER JOIN dbo.Orders AS ORD
ON CUS.CustomerID = ORD.CustomerID
WHERE CUS.FirstName = 'John'
Which do you prefer (and perhaps why)?
A: Most RDBMS products will optimize both queries identically. In "SQL Performance Tuning" by Peter Gulutzan and Trudy Pelzer, they tested multiple brands of RDBMS and found no performance difference.
I prefer to keep join conditions separate from query restriction conditions.
If you're using OUTER JOIN sometimes it's necessary to put conditions in the join clause.
A: I prefer the JOIN to join full tables/Views and then use the WHERE To introduce the predicate of the resulting set.
It feels syntactically cleaner.
A: I typically see performance increases when filtering on the join. Especially if you can join on indexed columns for both tables. You should be able to cut down on logical reads with most queries doing this too, which is, in a high volume environment, a much better performance indicator than execution time.
I'm always mildly amused when someone shows their SQL benchmarking and they've executed both versions of a sproc 50,000 times at midnight on the dev server and compare the average times.
A: Agree with 2nd most vote answer that it will make big difference when using LEFT JOIN or RIGHT JOIN. Actually, the two statements below are equivalent. So you can see that AND clause is doing a filter before JOIN while the WHERE clause is doing a filter after JOIN.
SELECT *
FROM dbo.Customers AS CUS
LEFT JOIN dbo.Orders AS ORD
ON CUS.CustomerID = ORD.CustomerID
AND ORD.OrderDate >'20090515'
SELECT *
FROM dbo.Customers AS CUS
LEFT JOIN (SELECT * FROM dbo.Orders WHERE OrderDate >'20090515') AS ORD
ON CUS.CustomerID = ORD.CustomerID
A: The relational algebra allows interchangeability of the predicates in the WHERE clause and the INNER JOIN, so even INNER JOIN queries with WHERE clauses can have the predicates rearrranged by the optimizer so that they may already be excluded during the JOIN process.
I recommend you write the queries in the most readable way possible.
Sometimes this includes making the INNER JOIN relatively "incomplete" and putting some of the criteria in the WHERE simply to make the lists of filtering criteria more easily maintainable.
For example, instead of:
SELECT *
FROM Customers c
INNER JOIN CustomerAccounts ca
ON ca.CustomerID = c.CustomerID
AND c.State = 'NY'
INNER JOIN Accounts a
ON ca.AccountID = a.AccountID
AND a.Status = 1
Write:
SELECT *
FROM Customers c
INNER JOIN CustomerAccounts ca
ON ca.CustomerID = c.CustomerID
INNER JOIN Accounts a
ON ca.AccountID = a.AccountID
WHERE c.State = 'NY'
AND a.Status = 1
But it depends, of course.
A: For inner joins I have not really noticed a difference (but as with all performance tuning, you need to check against your database under your conditions).
However where you put the condition makes a huge difference if you are using left or right joins. For instance consider these two queries:
SELECT *
FROM dbo.Customers AS CUS
LEFT JOIN dbo.Orders AS ORD
ON CUS.CustomerID = ORD.CustomerID
WHERE ORD.OrderDate >'20090515'
SELECT *
FROM dbo.Customers AS CUS
LEFT JOIN dbo.Orders AS ORD
ON CUS.CustomerID = ORD.CustomerID
AND ORD.OrderDate >'20090515'
The first will give you only those records that have an order dated later than May 15, 2009 thus converting the left join to an inner join.
The second will give those records plus any customers with no orders. The results set is very different depending on where you put the condition. (Select * is for example purposes only, of course you should not use this in production code.)
The exception to this is when you want to see only the records in one table but not the other. Then you use the where clause for the condition not the join.
SELECT *
FROM dbo.Customers AS CUS
LEFT JOIN dbo.Orders AS ORD
ON CUS.CustomerID = ORD.CustomerID
WHERE ORD.OrderID is null
A: WHERE will filter after the JOIN has occurred.
Filter on the JOIN to prevent rows from being added during the JOIN process.
A: Joins are quicker in my opinion when you have a larger table. It really isn't that much of a difference though especially if you are dealing with a rather smaller table. When I first learned about joins, i was told that conditions in joins are just like where clause conditions and that i could use them interchangeably if the where clause was specific about which table to do the condition on.
A: It is better to add the condition in the Join. Performance is more important than readability. For large datasets, it matters.
A: Putting the condition in the join seems "semantically wrong" to me, as that's not what JOINs are "for". But that's very qualitative.
Additional problem: if you decide to switch from an inner join to, say, a right join, having the condition be inside the JOIN could lead to unexpected results.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1018952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "268"
}
|
Q: how resource integrity is maintained using Semaphores I am new to computer science and it may sound stupid to some of you. Although i have searched for related question, but this scenario stuck in my mind.
I understand that Mutexes provide lock facility for a section or resource. Consider the example of a buffer(an array of size 10 say) where a thread puts some value in it. We lock the mutex before using it releases after. This whole process is done by same thread.
Now if i have to do this same process with semaphores. I can limit the number of threads that can enter the critical section in this case. But how can the integrity of the buffer is maintained.
(read and write operations handled by different threads on buffer)
A: The usual solution with semaphores is to allow multiple simultaneous readers or one writer. See the Wikipedia article Readers-writers problem for examples.
A: Semaphores are an higher abstraction. Semaphores controls the ability to create processes and make sure the instance created is distinct in which case it is kicked out. In a nutshell.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23146711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Spring AsyncTaskExecutor Returns Futures That Don't Throw Exceptions If I submit a Callable task to Spring's ThreadPoolTaskScheduler (the default implementation of AsyncTaskExecutor), I receive a Future representing the result of the computation. I know that my callable will throw an exception, but when I call Future#get, the method returns null instead of throwing an exception. I have found this to be the case when I invoke AsyncTaskExecutor#submit directly, and when it is used implicitly through Spring's @Async annotation.
In the source for ThreadPoolTaskScheduler, I see there's an ErrorHandler instance variable that seems to control how the futures throw exceptions. I tried wiring in a custom ErrorHandler that would rethrow any exception it received as a RuntimeException, but for some reason that didn't work. When I sent a request to my running application's endpoint, it timed out. My app printed no logs; not even the ones Spring normally prints before the request hits my REST controller. Note that I wired my ErrorHandler directly into the ThreadPoolTaskScheduler bean. I didn't define the ErrorHandler itself as a bean.
public class DataRetriever {
@Autowired
private AsyncTaskExecutor taskExecutor;
public List<Data> getData(String id) throws Exception {
Future<List<Data>> futureData = getDataEventually(id);
return futureData.get(); // exception should be thrown here
}
private Future<List<Data>> getDataEventually(
return taskExecutor.submit(() -> throw new RuntimeException());
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60101996",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Guarantee the lock is exclusive on the table for read also I am writing a web application and came across the problem to keep a value in column that is identical in two rows only and both goes in single batch of execution. One way I came up with solution to read the MAX value in the column and increment by 1. Thus, I end-up writing the procedure to lock the table so that other user should not get the dirty read of MAX value.
Create table D(Id int , Name varchar(100))
Begin Tran
DECLARE @i int = (SELECT MAX(ID) FROM D with (tablockx, holdlock))
Print @i ;
Insert into D values ((@i + 1), 'ANAS')
SELECT * FROM D
--COMMIT
Rollback
This code lock the table until query commits or rollback. I have two question from this 1) Is this code guarantee to have exclusive lock on table? 2) In my quick read tablockx can help perform lock for read also whereas holdlock help to prevent the changes in row I am working in locked session, but is this rightly used because I think holdlock may actually not required
A: Not sure you are asking the right question. You need the current value not to be changed and no insert. With SERIALIZABLE you may not need (updlock).
I am not positive about this answer. You should do your own testing.
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
Begin Tran
DECLARE @i int = (SELECT MAX(ID) FROM D with (updlock))
Print @i ;
Insert into D values ((@i + 1), 'ANAS')
SELECT * FROM D
--COMMIT
Rollback
identity or sequence number are better approaches
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49466768",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Add two factor authentication to my web application I have a java spring web application and currently it has a normal authentication flow. I need to add a two factor authentication implementation to it. For that can we use 3rd party provider like google or any other provider.
A:
I need to add a two factor authentication implementation to [my java spring web application].
Here's a good package that I wrote which implements 2FA/two-factor authentication in Java code.
Copying from the READ_ME, to get this to work you:
*
*Properly seed the random number generator.
*Use generateBase32Secret() to generate a secret key for a user.
*Store the secret key in the database associated with the user account.
*Display the QR image URL returned by qrImageUrl(...) to the user.
*User uses the image to load the secret key into his authenticator application.
Whenever the user logs in:
*
*The user enters the number from the authenticator application into the login form.
*Read the secret associated with the user account from the database.
*The server compares the user input with the output from generateCurrentNumber(...).
*If they are equal then the user is allowed to log in.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33206800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Condition is not verifying the validity of the input I'm doing an assignment that asks a user to input a student name, and then quiz scores until the user chooses to stop. It then calculates the total score and the average of all those scores and outputs them to the screen.
We are moving on to the subject of inheritance and now we are requested to make a class called MonitoredStudent which extends Student. The point of the MonitoredStudent class is to check if the average is above a user inputted average and display whether the student is off academic probation.
I have got most of the program written and when I input just one score (such as 71, when the average I set is 70) it is still displaying that I am on academic probation, even though the one quiz score is above the average I set of 70.
The main issue is that no matter what integer is set for the minimum passing average, I always get a return of false.
I added the "return false" statement in the isOffProbation method as when I add an if-else statement to check if the averageScore (from the Student class) is less than or equal to minPassingAvg eclipse tells me that the method needs a return type of boolean.
public class MonitoredStudent extends Student {
int minPassingAvg;
public MonitoredStudent(){
super();
minPassingAvg = 0;
}
public MonitoredStudent(String name, int minPassingAvg) {
super(name);
this.minPassingAvg = minPassingAvg;
}
public int getMinPassingAvg() {
return minPassingAvg;
}
public void setMinPassingAvg(int minPassingAvg) {
this.minPassingAvg = minPassingAvg;
}
boolean isOffProbation() {
if(getAverageScore() >= minPassingAvg)
return true;
return false;
}
}
This is the Student super class:
public class Student{
private String name;
private double totalScore;
private int quizCount;
public Student(){
name = "";
totalScore = 0;
quizCount = 0;
}
public Student(String n){
name = n;
totalScore = 0;
quizCount = 0;
}
public void setName(String aName){
name = aName;
}
public String getName(){
return name;
}
public void addQuiz(int score){
if(score >= 0 && score <= 100){
totalScore = totalScore + score;
quizCount = quizCount + 1;
}else{
System.out.println("Score must be between 0 and 100, inclusive");
}
}
public double getTotalScore(){
return totalScore;
}
public double getAverageScore(){
return totalScore / quizCount;
}
}
This is the main method:
import java.util.Scanner;
public class MonitoredStudentTester{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
MonitoredStudent monStu = new MonitoredStudent();
String repeat = "n";
int currentScore = 0;
int minPassAv;
System.out.println("Enter the student's name:");
String stuName = scan.next();
Student sName = new Student(stuName);
System.out.println("What is the minimum passing average score: ");
minPassAv = scan.nextInt();
Student stu = new Student();
do {
System.out.println("Enter a quiz score: ");
currentScore = scan.nextInt();
stu.addQuiz(currentScore);
monStu.setMinPassingAvg(currentScore);
System.out.println("Would you like to enter any more scores?: (Y for yes, N for no)");
scan.nextLine();
repeat = scan.nextLine();
}while(repeat.equalsIgnoreCase("y"));
String studName = stu.getName();
double totalScore = stu.getTotalScore();
double avgScore = stu.getAverageScore();
boolean offProb = monStu.isOffProbation();
System.out.println(studName + "'s Total Score is: " + totalScore);
System.out.println(studName + "'s Average Score is: " + avgScore);
System.out.println("Is " + studName + "off academic probation?: " + offProb);
}
}
A: You main class should be something like this.
public class MonitoredStudentTester {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
MonitoredStudent monStu = new MonitoredStudent();
String repeat = "n";
int currentScore = 0;
int minPassAv;
System.out.println("Enter the student's name:");
monStu.setName(scan.next());
System.out.println("What is the minimum passing average score: ");
minPassAv = scan.nextInt();
do {
System.out.println("Enter a quiz score: ");
currentScore = scan.nextInt();
monStu.addQuiz(currentScore);
monStu.setMinPassingAvg(minPassAv);
System.out.println("Would you like to enter any more scores?: (Y for yes, N for no)");
scan.nextLine();
repeat = scan.nextLine();
} while (repeat.equalsIgnoreCase("y"));
String studName = monStu.getName();
double totalScore = monStu.getTotalScore();
double avgScore = monStu.getAverageScore();
boolean offProb = monStu.isOffProbation();
System.out.println(studName + "'s Total Score is: " + totalScore);
System.out.println(studName + "'s Average Score is: " + avgScore);
System.out.println("Is " + studName + "off academic probation?: " + offProb);
}
}
When using inheritance you just need to create an object of child class.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71011590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to convert excel rate() formula into step by step formula I want to convert this excel rate() formula =RATE(D5,-D8,D3,,D6)*12 into manual formula for me to get the Effective Rate.
How can I convert this rate() =RATE(D5,-D8,D3,,D6)*12 formula from excel into a step by step formula?
The Effective Rate formula that I found online has not been able to reproduce the same results from the excel file.
You can download the excel file from Google Drive
Appreciate if anyone can help.
A: There is not a closed-form formula for the effective interest of an amortized loan payment. The RATE formula in Excel uses an iterative approach to "solve" for the rate by guessing and adjusting the rate until the present value of the payments matches the passed-in PV.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61753306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unable to add SSL support for database I am using Spring3, Hibernate4 and postgres9.2.
For enabling the SSL database connection, I followed following steps :
*
*Creating self signed Certificate : refer : http://www.postgresql.org/docs/9.2/static/ssl-tcp.html#SSL-CERTIFICATE-CREATION
*Copied the generated server.crt and server.key into postgres/9.2/data folder.
*URL for hibernate connection : jdbc:postgresql://localhost:5432/DB_NAME?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory
After restarting the postgres I run my application and it gives error as :
org.postgresql.util.PSQLException: The server does not support SSL.
at org.postgresql.core.v3.ConnectionFactoryImpl.enableSSL(ConnectionFactoryImpl.java:307)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:105)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:65)
at org.postgresql.jdbc2.AbstractJdbc2Connection.<init>(AbstractJdbc2Connection.java:140)
at org.postgresql.jdbc3.AbstractJdbc3Connection.<init>(AbstractJdbc3Connection.java:29)
at org.postgresql.jdbc3g.AbstractJdbc3gConnection.<init>(AbstractJdbc3gConnection.java:21)
at org.postgresql.jdbc4.AbstractJdbc4Connection.<init>(AbstractJdbc4Connection.java:31)
at org.postgresql.jdbc4.Jdbc4Connection.<init>(Jdbc4Connection.java:23)
at org.postgresql.Driver.makeConnection(Driver.java:393)
at org.postgresql.Driver.connect(Driver.java:267)
Even I tried to add this line at the end of pg_hba.conf file but postgres does not get restarted :
hostssl all all 127.0.0.1/32 trust
EDIT
It is for other folks who received such error or wants to add database ssl connection :
I added ssl = true and removed comments for ssl related entries from postgresql.conf and it worked. :)
A: The root of your problem appears to be that your server does not support SSL or does not have it enabled. The message:
The server does not support SSL
may only be emitted by org/postgresql/core/v3/ConnectionFactoryImpl.java in enableSSL(...) when the server refuses or doesn't understand SSL requests.
Sure enough, in your update you say that you had the SSL-related options in postgresql.conf commented out. Them being commented out is the same as them being not there at all to the server; it will ignore them. This will cause the server to say it doesn't support SSL and refuse SSL connections because it doesn't know what server certificate to send. PgJDBC will report the error above when this happens.
When you un-commented the SSL options in postgresql.conf and re-started the server it started working.
You were probably confused by the fact that:
&ssl
&ssl=true
&ssl=false
all do the same thing: they enable SSL. Yes, that's kind of crazy. It's like that for historical reasons that we're stuck with, but it's clearly documented in the JDBC driver parameter reference:
ssl
Connect using SSL. The driver must have been compiled with SSL
support. This property does not need a value associated with it. The
mere presence of it specifies a SSL connection. However, for
compatibility with future versions, the value "true" is preferred. For
more information see Chapter 4, Using SSL.
As you can see, you should still write ssl=true since this may change in future.
Reading the server configuration and client configuration sections of the manual will help you with setting up the certificates and installing the certificate in your local certificate list so you don't have to disable certificate trust checking.
For anyone else with this problem: There will be more details in your PostgreSQL error logs, but my guess is your PostgreSQL config isn't right or you're using a hand-compiled PostgreSQL and you didn't compile it with SSL support.
A: If you are using a self-signed certificate you need to add it to your trusted key store of your Java installation on the client side.
You find the detailed instructions to achieve this here: telling java to accept self-signed ssl certificate
A: In your connection string, try
?sslmode=require
instead of
?ssl=true
A: Use param sslmode=disable. Work for me. Postgresql 9.5 with jdbc driver SlickPostgresDriver.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16980551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Google Analytics not showing any data After building a basic ionic 3 app with two pages (quotes-list and quotes-detail) where clicking a name on the former you edit a text on the latter, run the app on a real device and go through GA, trying to get some statistics about the two tracked pages, but all I can see is nothing. Anyone could help me, please? I'm not able to get data, neither past nor real time. I'd appreciate it so much...
app.module.ts
import { GoogleAnalytics } from '@ionic-native/google-analytics';
providers: [
GoogleAnalytics,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
app.component.ts
import { GoogleAnalytics } from '@ionic-native/google-analytics';
export class MyApp {
rootPage:any = QuotesListPage;
constructor(platform: Platform, googleanalytics: GoogleAnalytics) {
platform.ready().then(() => {
googleanalytics.debugMode();
googleanalytics.startTrackerWithId("UA-XXXXXXXXX-1");
googleanalytics.enableUncaughtExceptionReporting(true).then((_success) => {
console.log("Successful enabling of uncaught exception reporting "+_success)}).catch((_error) => {
console.log("error occured "+_error)
});
});
}
}
quotes-list.ts
import { GoogleAnalytics } from '@ionic-native/google-analytics';
constructor(platform: Platform, private http:Http, public navCtrl: NavController, public navParams: NavParams, public googleanalytics: GoogleAnalytics) {
this.isfiltered = false;
this.http.get('quotes.json')
.map(res => res.json())
.subscribe(
data => {
this.quotesList = data.quotes;
},
err => console.log("error is "+err), // error
() => console.log('read quotes Complete '+ this.quotesList) // complete
);
platform.ready().then(() => {
googleanalytics.trackView("Quotes List");
});
}
ionViewDidLoad() {
console.log('ionViewDidLoad QuotesListPage');
}
}
quotes-detail.ts
import { GoogleAnalytics } from '@ionic-native/google-analytics';
constructor(public navCtrl: NavController, public navParams: NavParams, public googleanalytics: GoogleAnalytics) {
this.quoteDetail = navParams.get('quote');
googleanalytics.trackView("Quotes Detail");
}
}
A: 2 changes needed in app.components.ts
*
*Ensure googleanalytics.startTrackerWithId("UA-XXXXXXXXX-1"); is always the first line to be executed before any other analytics code.
*Remove googleanalytics.debugMode();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53198508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Shopware 6: How to display product name in breadcrumbs We want to add the product name to the breadcrumb list when current page matches a product detail page.
Unfortunately, it doesn't seem like the product is loaded yet when the breadcrumb is rendered. We have tried using dump() to see what variables are available and nothing related to the product.
Where should I look in order to include the product name in our breadcrumbs?
A: Have a look at storefront/base.html.twig. There you will see, that currently the breadcrumb-template gets passed the context and the category. If you want to also use some product-information, you have to overwrite this block like this:
{% block base_breadcrumb %}
{% sw_include '@Storefront/storefront/layout/breadcrumb.html.twig' with {
context: context,
category: page.product.seoCategory,
product: page.product
} only %}
{% endblock %}
Then you can use product in the breadcrumb-template.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73333452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Playing a MIDI file using SoundFonts and NAudio I am trying to create a simple program that plays some notes using a preset from inside a Soundfont. To do this I am trying to use NAudio. So far I have been able to successfully open a SoundFont, and get the names of all the instruments, presets, etc.:
NAudio.SoundFont.SoundFont sf = new NAudio.SoundFont.SoundFont("SoundFont.sf2");
MessageBox.Show(sf.Presets[0].Name); //Just looking at the first name
Now I want to be able to play sounds using those soundfonts, in the end from midi, but for now, just a note. I have played around with a few things, but not come up with anything so far.
A: NAudio can read information out of SoundFont files, but it does not include a SoundFont engine. For that you would need a good pitch shifting algorithm, some filters, and some voice management, as well as a sequencer if you wanted to play back MIDI files.
The closest I have come to building something like this is a demo I made for my NAudio Pluralsight course, in which I build a simple sampled piano based on some piano note recordings. If you are subscriber, you are free to use it. The technique I use is to load the sample into memory, connect a RawSourceWaveStream to it, convert it into a sample provider, and then pass it through a pitch shifter sample provider, based on the one I ported to C# for this open source project.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20624321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Image.createImage problem in J2ME I tried this on J2ME
try {
Image immutableThumb = Image.createImage( temp, 0, temp.length);
} catch (Exception ex) {
System.out.println(ex);
}
I hit this error:
java.lang.IllegalArgumentException:
How do I solve this?
A: Image.createImage() throws an IllegalArgumentException if the first argument is incorrectly formatted or otherwise cannot be decoded. (I'm assuming that temp is a byte[]).
http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Image.html#createImage(byte[],%20int,%20int)
(This URL refuses to become a hyperlink for some reason (?))
A: It's hard to say without more details or more surrounding code, but my initial suspicion is that the file your are trying to load is in a format not supported by the device.
A: Let us have a look at the docs: IllegalArgumentException is thrown
if imageData is incorrectly formatted or otherwise cannot be decoded
So the possible reason can be either unsupported format of the image, or truncated data. Remember, you should pass entire file to that method, including all the headers. If you have doubts about the format, you'd better choose PNG, it must be supported anyway.
A: I just had the same problem with my MIDLET and the problem in my case was the HTTP header that comes along the JPEG image that I read from the socket's InputStream. And I solved it by finding the JPEG SOI marker that is identified by two bytes: FFD8 in my byte array. Then when I find the location of the FFD8 in my byte array, I trim the starting bytes that represent the HTTP header, and then I could call createImage() without any Exception being thrown...
You should check if this is the case with you. Just check is this true (temp[0] == 0xFF && temp[1] == 0xD8) and if it is not, trim the start of temp so you remove HTTP header or some other junk...
P.S.
I presume that you are reading JPEG image, if not, look for the appropriate header in the temp array.
Also if this doesn't help, and you are reading JPEG image make sure that the array starts with FFD8 and ends with FFD9 (which is the EOI marker). And if it doesn't end with the EOI just trim the end like I explained for SOI...
P.P.S
And if you find that the data in temp is valid, then your platform cannot decode the JPEG images or the image in temp is to large for JPEG decoder.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/271672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: retrieve most recent records I'm having a bit of mysql query brain freeze. I need to retrieve the latest record from a table, grouped by a second column. Something like this:
SELECT ca.id, ca.activity_date, cat.contact_id as cid
FROM activity ca
JOIN activity_target cat
ON ca.id = cat.activity_id
WHERE ca.activity_type_id = 44
GROUP BY cid
ORDER BY activity_date DESC
...except that I need the most recent record (using activity_date) within the group by (the order by is performed after the group). I tried using HAVING activity_date = max(activity_date) but that doesn't work.
A: I think you can do it like this:
SELECT ca.id, ca.activity_date, cat.contact_id as cid
FROM activity ca
JOIN activity_target cat
ON ca.id = cat.activity_id
WHERE ca.activity_type_id = 44
and ca.id = (SELECT id from activity a
join activity_target t on a.id = t.activity_id
WHERE t.contact_id = cat.contact_id
ORDER BY activity_date DESC LIMIT 1)
ORDER BY activity_date DESC
I can't say for sure without looking at your schema, and I'm guessing a bit with the differences between MySQL and Microsoft SQL Server.
A: SELECT ca.id, ca.activity_date, cat.contact_id AS cid
FROM activity ca
JOIN activity_target cat
ON ca.id = cat.activity_id
JOIN
( SELECT t.contact_id
, MAX(a.activity_date) AS activity_date
FROM activity a
JOIN activity_target t
ON a.id = t.activity_id
WHERE a.activity_type_id = 44
GROUP BY t.contact_id
) AS grp
ON grp.contact_id = cat.contact_id
AND grp.activity_date = ca.activity_date
WHERE ca.activity_type_id = 44
ORDER BY ca.activity_date DESC
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8918511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Try to export form result into single field I'm trying to fill one hidden field with the results obtained from an HTML form. I have seen someone who suggests using Javascript and jQuery. I've tried to write some scripts using that language. This is the HTML form hosted in Formtools platform (www.formtools.org):
I tried many times and I'm going crazy, cause everything I've tried didn't work. Could someone help me?
Thanks
<$(document).ready(function() {
$("#formdatimarketing.php").continue(function() {
var tipologia_auto = $("tipologia_auto[]").val();
var alimentazione = $("alimentazione[]").val();
var km_annui = $("km_annui").val();
var mod_acq = $("mod_acq").val();
var budget = $("budget_spesa").val();
var rata = $("rata_mensile").val();
var abitudini_acq = $("abitudini_acq").val();
var componenti_famiglia = $("n_comp_famiglia").val();
var hobby = $("hobby[]").val();
var professione = $("professione").val();
var asscociazione_categoria = $("ass_cat").val();
var privacy = $("privacy_mkt_all").val;
var giorno_pref_ricontatto = $("giorno_ricontatto[]").val();
var orario_ricontatto = $("orario_ricontatto[]").val();
var mkt = "";
mkt = tipologia_auto + "," + alimentazione + "," + km_annui + "," + mod_acq + "," + budget + "," + rata + "," + abitudini_acq + "," + componenti_famiglia + "," + hobby + "," + professione + "," + asscociazione_categoria + "," + privacy + "," + giorno_pref_ricontatto + "," + orario_ricontatto;
output = mkt;
alert(output);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="formdatimarketing.php" method="post" enctype="multipart/form-data" id="ts_form_element_id" name="edit_submission_form">
<input type="hidden" id="form_tools_published_form_id" value="12">
<a name="s143"></a>
<h3>Dati Marketing</h3>
<table class="table_1" cellpadding="1" cellspacing="1" border="0" width="798">
<tbody>
<tr>
<td width="180" valign="top">
Segmento auto richiesto
<span class="req">*</span>
</td>
<td class="answer" valign="top">
<div class="pad_left">
<input type="checkbox" name="tipologia_auto[]" id="tipologia_auto_1" value="tipologia_auto_1">
<label for="tipologia_auto_1">Citycar</label>
<br>
<input type="checkbox" name="tipologia_auto[]" id="tipologia_auto_2" value="tipologia_auto_2">
<label for="tipologia_auto_2">Berlina</label>
<br>
<input type="checkbox" name="tipologia_auto[]" id="tipologia_auto_3" value="tipologia_auto_3">
<label for="tipologia_auto_3">Monovolume</label>
<br>
<input type="checkbox" name="tipologia_auto[]" id="tipologia_auto_4" value="tipologia_auto_4">
<label for="tipologia_auto_4">Veicolo commerciale</label>
<br>
<input type="checkbox" name="tipologia_auto[]" id="tipologia_auto_5" value="tipologia_auto_5">
<label for="tipologia_auto_5">Suv</label>
<br>
<input type="checkbox" name="tipologia_auto[]" id="tipologia_auto_6" value="tipologia_auto_6">
<label for="tipologia_auto_6">Cabrio</label>
<br>
<input type="checkbox" name="tipologia_auto[]" id="tipologia_auto_7" value="tipologia_auto_7">
<label for="tipologia_auto_7">Coupe</label>
<br>
<input type="checkbox" name="tipologia_auto[]" id="tipologia_auto_8" value="tipologia_auto_9">
<label for="tipologia_auto_8">Station Wagon</label>
<br>
</div>
</td>
</tr>
<tr>
<td width="180" valign="top">
Alimentazione
<span class="req">*</span>
</td>
<td class="answer" valign="top">
<div class="pad_left">
<input type="checkbox" name="alimentazione[]" id="alimentazione_1" value="alimentazione_1">
<label for="alimentazione_1">Benzina</label>
<br>
<input type="checkbox" name="alimentazione[]" id="alimentazione_2" value="alimentazione_2">
<label for="alimentazione_2">Diesel</label>
<br>
<input type="checkbox" name="alimentazione[]" id="alimentazione_3" value="alimentazione_3">
<label for="alimentazione_3">Metano</label>
<br>
<input type="checkbox" name="alimentazione[]" id="alimentazione_4" value="alimentazione_4">
<label for="alimentazione_4">GPL</label>
<br>
<input type="checkbox" name="alimentazione[]" id="alimentazione_5" value="alimentazione_5">
<label for="alimentazione_5">Ibrido</label>
<br>
<input type="checkbox" name="alimentazione[]" id="alimentazione_6" value="alimentazione_6">
<label for="alimentazione_6">Elettrico</label>
<br>
</div>
</td>
</tr>
<tr>
<td width="180" valign="top">
Km annui percorsi
<span class="req">*</span>
</td>
<td class="answer" valign="top">
<div class="pad_left">
<input type="radio" name="km_annui" id="km_annui_1" value="km_annui_1">
<label for="km_annui_1">0-10.000 km</label>
<input type="radio" name="km_annui" id="km_annui_2" value="km_annui_2">
<label for="km_annui_2">10.000 - 25.000 km</label>
<input type="radio" name="km_annui" id="km_annui_3" value="km_annui_4">
<label for="km_annui_3">Più di 25.000 km</label>
</div>
</td>
</tr>
<tr>
<td width="180" valign="top">
Modalità di acquisto
<span class="req">*</span>
</td>
<td class="answer" valign="top">
<div class="pad_left">
<input type="radio" name="mod_acq" id="mod_acq_1" value="mod_acq_1">
<label for="mod_acq_1">Contanti</label>
<input type="radio" name="mod_acq" id="mod_acq_2" value="mod_acq_2">
<label for="mod_acq_2">Finanziamento - Leasing</label>
<input type="radio" name="mod_acq" id="mod_acq_3" value="mod_acq_4">
<label for="mod_acq_3">Noleggio</label>
</div>
</td>
</tr>
<tr>
<td width="180" valign="top">
Budget di spesa
<span class="req">*</span>
</td>
<td class="answer" valign="top">
<div class="pad_left">
<div class="cf_option_list_2cols">
<div class="column"> <input type="radio" name="budget_spesa" id="budget_spesa_1" value="budget_spesa_1">
<label for="budget_spesa_1">Budget: 0 - 5.000 €</label>
</div>
<div class="column"> <input type="radio" name="budget_spesa" id="budget_spesa_2" value="budget_spesa_2">
<label for="budget_spesa_2">Budget: 5.000 - 12.000 €</label>
</div>
<div class="column"> <input type="radio" name="budget_spesa" id="budget_spesa_3" value="budget_spesa_3">
<label for="budget_spesa_3">Budget: 12.000 - 18.000 €</label>
</div>
<div class="column"> <input type="radio" name="budget_spesa" id="budget_spesa_4" value="budget_spesa_4">
<label for="budget_spesa_4">Budget: 18.000 - 24.000 €</label>
</div>
<div class="column"> <input type="radio" name="budget_spesa" id="budget_spesa_5" value="budget_spesa_5">
<label for="budget_spesa_5">Budget: 24.000 - 32.000 €</label>
</div>
<div class="column"> <input type="radio" name="budget_spesa" id="budget_spesa_6" value="budget_spesa_6">
<label for="budget_spesa_6">Budget: 32.000 - 40.000 €</label>
</div>
<div class="column"> <input type="radio" name="budget_spesa" id="budget_spesa_7" value="budget_spesa_7">
<label for="budget_spesa_7">Budget: 40.000 - 50.000 €</label>
</div>
<div class="column"> <input type="radio" name="budget_spesa" id="budget_spesa_8" value="budget_spesa_8">
<label for="budget_spesa_8">Budget: 50.000 - 60.000 €</label>
</div>
<div class="column"> <input type="radio" name="budget_spesa" id="budget_spesa_9" value="budget_spesa_9">
<label for="budget_spesa_9">Budget: 60.000 - 70.000 €</label>
</div>
<div class="column"> <input type="radio" name="budget_spesa" id="budget_spesa_10" value="budget_spesa_10">
<label for="budget_spesa_10">Budget: 70.000 € o più</label>
</div>
</div>
</div>
</td>
</tr>
<tr>
<td width="180" valign="top">
Rata mensile
<span class="req">*</span>
</td>
<td class="answer" valign="top">
<div class="pad_left">
<div class="cf_option_list_2cols">
<div class="column"> <input type="radio" name="rata_mensile" id="rata_mensile_1" value="rata_mensile_1">
<label for="rata_mensile_1">Rata = 150-200</label>
</div>
<div class="column"> <input type="radio" name="rata_mensile" id="rata_mensile_2" value="rata_mensile_2">
<label for="rata_mensile_2">Rata = 200-300</label>
</div>
<div class="column"> <input type="radio" name="rata_mensile" id="rata_mensile_3" value="rata_mensile_3">
<label for="rata_mensile_3">Rata = 300-400</label>
</div>
<div class="column"> <input type="radio" name="rata_mensile" id="rata_mensile_4" value="rata_mensile_4">
<label for="rata_mensile_4">Rata = 400-500</label>
</div>
<div class="column"> <input type="radio" name="rata_mensile" id="rata_mensile_5" value="rata_mensile_5">
<label for="rata_mensile_5">Rata = 500-750</label>
</div>
<div class="column"> <input type="radio" name="rata_mensile" id="rata_mensile_6" value="rata_mensile_6">
<label for="rata_mensile_6">Rata = 750 o piu</label>
</div>
</div>
</div>
</td>
</tr>
<tr>
<td width="180" valign="top">
Abitudini di acquisto
<span class="req">*</span>
</td>
<td class="answer" valign="top">
<div class="pad_left">
<input type="radio" name="abitudini_acq" id="abitudini_acq_1" value="abitudini_acq_1">
<label for="abitudini_acq_1">Primo acquisto</label>
<br>
<input type="radio" name="abitudini_acq" id="abitudini_acq_2" value="abitudini_acq_2">
<label for="abitudini_acq_2">1 - 3 anni</label>
<br>
<input type="radio" name="abitudini_acq" id="abitudini_acq_3" value="abitudini_acq_3">
<label for="abitudini_acq_3">3 - 6 anni</label>
<br>
<input type="radio" name="abitudini_acq" id="abitudini_acq_4" value="abitudini_acq_4">
<label for="abitudini_acq_4">6 - 10 anni</label>
<br>
<input type="radio" name="abitudini_acq" id="abitudini_acq_5" value="abitudini_acq_5">
<label for="abitudini_acq_5">più di 10 anni</label>
<br>
</div>
</td>
</tr>
<tr>
<td width="180" valign="top">
Numero di componenti del nucleo familiare
<span class="req"></span>
</td>
<td class="answer" valign="top">
<div class="pad_left">
<input type="radio" name="n_comp_famiglia" id="n_comp_famiglia_1" value="n_comp_famiglia_1">
<label for="n_comp_famiglia_1">Single</label>
<br>
<input type="radio" name="n_comp_famiglia" id="n_comp_famiglia_2" value="n_comp_famiglia_2">
<label for="n_comp_famiglia_2">Senza figli</label>
<br>
<input type="radio" name="n_comp_famiglia" id="n_comp_famiglia_3" value="n_comp_famiglia_3">
<label for="n_comp_famiglia_3">1 figlio</label>
<br>
<input type="radio" name="n_comp_famiglia" id="n_comp_famiglia_4" value="n_comp_famiglia_4">
<label for="n_comp_famiglia_4">2 o più figli</label>
<br>
</div>
</td>
</tr>
<tr>
<td width="180" valign="top">
Hobby
<span class="req"></span>
</td>
<td class="answer" valign="top">
<div class="pad_left">
<div class="cf_option_list_3cols">
<div class="column"> <input type="checkbox" name="hobby[]" id="hobby_1" value="hobby_1">
<label for="hobby_1">Golf</label>
</div>
<div class="column"> <input type="checkbox" name="hobby[]" id="hobby_2" value="hobby_2">
<label for="hobby_2">Vela</label>
</div>
<div class="column"> <input type="checkbox" name="hobby[]" id="hobby_3" value="hobby_3">
<label for="hobby_3">Tennis</label>
</div>
<div class="column"> <input type="checkbox" name="hobby[]" id="hobby_4" value="hobby_4">
<label for="hobby_4">Cucina</label>
</div>
<div class="column"> <input type="checkbox" name="hobby[]" id="hobby_5" value="hobby_5">
<label for="hobby_5">Cinema</label>
</div>
<div class="column"> <input type="checkbox" name="hobby[]" id="hobby_6" value="hobby_6">
<label for="hobby_6">Musica</label>
</div>
<div class="column"> <input type="checkbox" name="hobby[]" id="hobby_7" value="hobby_7">
<label for="hobby_7">Fitness</label>
</div>
<div class="column"> <input type="checkbox" name="hobby[]" id="hobby_8" value="hobby_8">
<label for="hobby_8">Basket</label>
</div>
<div class="column"> <input type="checkbox" name="hobby[]" id="hobby_9" value="hobby_9">
<label for="hobby_9">Calcio</label>
</div>
<div class="column"> <input type="checkbox" name="hobby[]" id="hobby_10" value="hobby_10">
<label for="hobby_10">Motori</label>
</div>
<div class="column"> <input type="checkbox" name="hobby[]" id="hobby_11" value="hobby_11">
<label for="hobby_11">Sci</label>
</div>
<div class="column"> <input type="checkbox" name="hobby[]" id="hobby_12" value="hobby_12">
<label for="hobby_12">Concerti</label>
</div>
<div class="column"> <input type="checkbox" name="hobby[]" id="hobby_13" value="hobby_13">
<label for="hobby_13">Motociclismo</label>
</div>
<div class="column"> <input type="checkbox" name="hobby[]" id="hobby_14" value="hobby_14">
<label for="hobby_14">Automobilismo</label>
</div>
<div class="column"> <input type="checkbox" name="hobby[]" id="hobby_15" value="hobby_15">
<label for="hobby_15">Test drive in pista</label>
</div>
<div class="column"> <input type="checkbox" name="hobby[]" id="hobby_16" value="hobby_16">
<label for="hobby_16">Teatro</label>
</div>
<div class="column"> <input type="checkbox" name="hobby[]" id="hobby_17" value="hobby_17">
<label for="hobby_17">Fotografia</label>
</div>
<div class="column"> <input type="checkbox" name="hobby[]" id="hobby_18" value="hobby_18">
<label for="hobby_18">Arte</label>
</div>
<div class="column"> <input type="checkbox" name="hobby[]" id="hobby_19" value="hobby_19">
<label for="hobby_19">Viaggi</label>
</div>
</div>
</div>
</td>
</tr>
<tr>
<td width="180" valign="top">
Professione
<span class="req"></span>
</td>
<td class="answer" valign="top">
<div class="pad_left">
<select name="professione">
<option value="professione_1">Impiegato</option>
<option value="professione_2">Libero professionista</option>
<option value="professione_3">Agente di commercio</option>
<option value="professione_4">Imprenditore</option>
<option value="professione_5">Medico</option>
</select>
</div>
</td>
</tr>
<tr>
<td width="180" valign="top">
Iscritto ad associazioni di categoria
<span class="req"></span>
</td>
<td class="answer" valign="top">
<div class="pad_left">
<input type="radio" name="ass_cat" id="ass_cat_1" value="ass_cat_3">
<label for="ass_cat_1">Confindustria</label>
<br>
<input type="radio" name="ass_cat" id="ass_cat_2" value="ass_cat_4">
<label for="ass_cat_2">Confartigianato</label>
<br>
<input type="radio" name="ass_cat" id="ass_cat_3" value="ass_cat_5">
<label for="ass_cat_3">Confagricoltura</label>
<br>
<input type="radio" name="ass_cat" id="ass_cat_4" value="ass_cat_6">
<label for="ass_cat_4">Confcommercio</label>
<br>
<input type="radio" name="ass_cat" id="ass_cat_5" value="ass_cat_7">
<label for="ass_cat_5">Forze dell'ordine</label>
<br>
<input type="radio" name="ass_cat" id="ass_cat_6" value="ass_cat_8">
<label for="ass_cat_6">Ordine dei Dottori Commercialisti</label>
<br>
<input type="radio" name="ass_cat" id="ass_cat_7" value="ass_cat_9">
<label for="ass_cat_7">Ordine degli avvocati</label>
<br>
<input type="radio" name="ass_cat" id="ass_cat_8" value="ass_cat_2">
<label for="ass_cat_8">Ordine dei medici</label>
<br>
<input type="radio" name="ass_cat" id="ass_cat_9" value="ass_cat_10">
<label for="ass_cat_9">Altri ordini professionali</label>
<br>
<input type="radio" name="ass_cat" id="ass_cat_10" value="ass_cat_1">
<label for="ass_cat_10">Associazioni di volontariato varie</label>
<br>
</div>
</td>
</tr>
<tr>
<td width="180" valign="top">
Privacy marketing
<span class="req"></span>
</td>
<td class="answer" valign="top">
<div class="pad_left">
<input type="radio" name="privacy_mkt_all" id="privacy_mkt_all_1" value="privacy_mkt_all_1">
<label for="privacy_mkt_all_1">Si</label>
<input type="radio" name="privacy_mkt_all" id="privacy_mkt_all_2" value="privacy_mkt_all_2">
<label for="privacy_mkt_all_2">No</label>
</div>
</td>
</tr>
<tr>
<td width="180" valign="top">
Giorno preferito per il ricontatto
<span class="req"></span>
</td>
<td class="answer" valign="top">
<div class="pad_left">
<input type="checkbox" name="giorno_ricontatto[]" id="giorno_ricontatto_1" value="giorno_ricontatto_1">
<label for="giorno_ricontatto_1">Lunedì</label>
<br>
<input type="checkbox" name="giorno_ricontatto[]" id="giorno_ricontatto_2" value="giorno_ricontatto_2">
<label for="giorno_ricontatto_2">Martedì</label>
<br>
<input type="checkbox" name="giorno_ricontatto[]" id="giorno_ricontatto_3" value="giorno_ricontatto_3">
<label for="giorno_ricontatto_3">Mercoledì</label>
<br>
<input type="checkbox" name="giorno_ricontatto[]" id="giorno_ricontatto_4" value="giorno_ricontatto_4">
<label for="giorno_ricontatto_4">Giovedì</label>
<br>
<input type="checkbox" name="giorno_ricontatto[]" id="giorno_ricontatto_5" value="giorno_ricontatto_5">
<label for="giorno_ricontatto_5">Venerdì</label>
<br>
</div>
</td>
</tr>
<tr>
<td width="180" valign="top">
Orario preferito per il ricontatto
<span class="req"></span>
</td>
<td class="answer" valign="top">
<div class="pad_left">
<div class="cf_option_list_2cols">
<div class="column"> <input type="checkbox" name="orario_ricontatto[]" id="orario_ricontatto_1" value="orario_ricontatto_1">
<label for="orario_ricontatto_1">09:00 - 10:00</label>
</div>
<div class="column"> <input type="checkbox" name="orario_ricontatto[]" id="orario_ricontatto_2" value="orario_ricontatto_2">
<label for="orario_ricontatto_2">10:00 - 11:00</label>
</div>
<div class="column"> <input type="checkbox" name="orario_ricontatto[]" id="orario_ricontatto_3" value="orario_ricontatto_3">
<label for="orario_ricontatto_3">11:00 - 12:00</label>
</div>
<div class="column"> <input type="checkbox" name="orario_ricontatto[]" id="orario_ricontatto_4" value="orario_ricontatto_4">
<label for="orario_ricontatto_4">12:00 - 13:00</label>
</div>
<div class="column"> <input type="checkbox" name="orario_ricontatto[]" id="orario_ricontatto_5" value="orario_ricontatto_5">
<label for="orario_ricontatto_5">13:00 - 14:00</label>
</div>
<div class="column"> <input type="checkbox" name="orario_ricontatto[]" id="orario_ricontatto_6" value="orario_ricontatto_6">
<label for="orario_ricontatto_6">14:00 - 15:00</label>
</div>
<div class="column"> <input type="checkbox" name="orario_ricontatto[]" id="orario_ricontatto_7" value="orario_ricontatto_7">
<label for="orario_ricontatto_7">15:00 - 16:00</label>
</div>
<div class="column"> <input type="checkbox" name="orario_ricontatto[]" id="orario_ricontatto_8" value="orario_ricontatto_8">
<label for="orario_ricontatto_8">16:00 - 17:00</label>
</div>
<div class="column"> <input type="checkbox" name="orario_ricontatto[]" id="orario_ricontatto_9" value="orario_ricontatto_9">
<label for="orario_ricontatto_9">17:00 - 18:00</label>
</div>
<div class="column"> <input type="checkbox" name="orario_ricontatto[]" id="orario_ricontatto_10" value="orario_ricontatto_10">
<label for="orario_ricontatto_10">18:00 - 19:00</label>
</div>
</div>
</div>
</td>
</tr>
</tbody>
</table>
<div class="ts_continue_button">
<input type="submit" name="form_tools_continue" value="Continue">
</div>
</form>
A: use the id not the name of the input fields
e.g. var tipologia_auto = $("#tipologia_auto_1").val();
A: Ok, thank you! I need also to store these concatenated values into one field that will be saved into the MySql Database.
|
{
"language": "it",
"url": "https://stackoverflow.com/questions/64990523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to run 'git diff --check' on certain file types only I have been unable to figure out how to run 'git diff --check' on only Python files in my commit. I have a commit with 3 files in it:
$ git show --name-only
...
tools/gitHooks/preReceive.py
tools/gitHooks/unittests/testPreReceive.py
Makefile
The last 2 files have trailing whitespace in them.
$ git diff --check HEAD~1 HEAD
tools/gitHooks/unittests/testPreReceive.py:75: trailing whitespace.
+newmock = Mock()
Makefile:41: new blank line at EOF.
I would like to restrict the whitespace check to only Python files. Doing this gives me the correct files:
$ git diff --name-only HEAD~1 HEAD | grep ".py"
tools/gitHooks/preReceive.py
tools/gitHooks/unittests/testPreReceive.py
But when I pipe the filenames to 'git diff --check' (with or without xargs) I get the wrong output.
$ git diff --name-only HEAD~1 HEAD | grep ".py" | xargs git diff --check HEAD~1 HEAD --
$
$ git diff --name-only HEAD~1 HEAD | grep ".py" | git diff --check HEAD~1 HEAD --
tools/gitHooks/unittests/testPreReceive.py:75: trailing whitespace.
+newmock = Mock()
Makefile:41: new blank line at EOF.
I also tried this as well as a few variations on it with no luck:
$ git diff --check HEAD~1 HEAD -- "*.py"
$
Can anyone help? I feel like I'm close to the answer.
A: From the original poster:
Turns out I was using the wrong grep.
$ git diff --name-only HEAD~1 HEAD | grep \.py$ | \
$ xargs git diff --check HEAD~1 HEAD --
tools/gitHooks/unittests/testPreReceive.py:75: trailing whitespace.
+newmock = Mock()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12427583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Issue using position dodge vertically in ggplots with geom_linerange in R I'm relatively new to R, and I am having issues with avoiding overlapping line ranges using geom_linerange and position_dodge with ggplot. I am comparing 2 different sets of age ranges for each individual in the study data. I would like to show the two ranges side-by-side, rather than display on the same ID line. Here is the data:
> dput(data)
structure(list(ID = c("A", "B", "C", "D", "E", "F", "G", "H",
"I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
"V", "W", "X", "Y", "Z"), Age_Range1_Start = c(39L, 21L, 28L,
35L, 35L, 20L, 21L, 28L, 20L, 29L, 28L, 20L, 49L, 20L, 39L, 21L,
39L, 21L, 20L, 28L, 30L, 29L, 21L, 28L, 29L, 35L), Age_Range1_End = c(69L,
42L, 52L, 57L, 57L, 43L, 42L, 52L, 43L, 44L, 52L, 43L, 65L, 43L,
69L, 42L, 69L, 42L, 43L, 52L, 54L, 44L, 42L, 52L, 44L, 57L),
Age_Range2_Start = c(46L, 43L, 49L, 46L, 48L, 34L, 37L, 45L,
44L, 46L, 37L, 43L, 51L, 45L, 48L, 36L, 53L, 44L, 24L, 43L,
45L, 49L, 34L, 45L, 22L, 30L), Age_Range2_End = c(87L, 80L,
92L, 86L, 90L, 64L, 69L, 83L, 81L, 85L, 68L, 80L, 97L, 84L,
89L, 68L, 100L, 83L, 45L, 82L, 83L, 92L, 64L, 84L, 42L, 56L
)), class = "data.frame", row.names = c(NA, -26L))
>
Here is the R code I used
ggplot(data) + theme_minimal() + coord_flip() +
geom_linerange(aes(x=ID, ymin=Age_Range1_Start, ymax=Age_Range1_End, color="Method 1", size=1.5)) +
geom_linerange(aes(x=ID, ymin=Age_Range2_Start, ymax=Age_Range2_End, color="Method 2", size=1.5), position=position_dodge(width=1)) +
labs(x="ID", y="Age Range", title="Method Age Range Comparison")
It produces the following plot:
Is it possible to shift (or dodge) the line ranges for Method 2 such that they appear slightly below or inferior to the age ranges for Method 1? I do not understand why the position_dodge code does not shift the values.
Thank you in advance for any help or suggestions.
A: If you organize your data in another format you can do the trick, as follows:
library(ggplot2)
data = data.frame(
ID = rep(c('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'), 2),
Start = c(39, 21, 28, 35, 35, 20, 21, 28, 46, 43, 49, 46, 48, 34, 37, 45),
End = c(69, 42, 52, 57, 57, 43, 42, 52, 87, 80, 92, 86, 90, 64, 69, 83),
Method = c(rep(1, 8), rep(2, 8))
)
data$Method = as.factor(data$Method)
ggplot(data) +
theme_minimal() +
coord_flip() +
geom_linerange(aes(x = ID, ymin = Start, ymax = End, colour = Method),
size = 1.5, position = position_dodge2(width = 0.5)) +
labs(x = 'ID', y = 'Age Range', title = 'Method Age Range Comparison')
Here is the output:
Note that I gather the starts together and the ends together. Then, I labeled each of them as method 1 or 2.
Also remember using position_dodge2() when you flip the coordinates.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64685369",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: display an image when dropdown is selected I am trying to display an image when a dropdown is selected with the code below.By default dropdown value will be "None".Initially when the page is loaded it is not displaying image.when i select field2 or field image is diaplaying.But when i select none again the image is still diaplaying.The code i used is:
<select id="dropdown" name="dropdown">
<option value="field1" selected="selected">None</option>
<option value="field2">field2</option>
<option value="field3">field3</option>
</select>
$(document).ready(function() {
$("#image").hide();
$('#dropdown').on('change', function() {
if ( this.value == 'field2')
{
$("#image").show();
}
elsif(this.value == 'field3')
{
$("#image1").show();
}
else
{
$("#image").hide();
$("#image1").hide();
}
});
});
#image img {
padding-left:554px;
position:absolute;
padding-top: 774px;
}
A: This should do it. Use the .indexOf() on an array of the good values and check if the value is in the array. To ensure that the handler fires at page load trigger the change event with .change().:
$(document).ready(function() {
$('#dropdown').on('change', function() {
if ( ['field2', 'field3'].indexOf( this.value ) > -1 )
{
$("#image").show();
}
else
{
$("#image").hide();
}
})
.change();
});
$(document).ready(function() {
$('#dropdown').on('change', function() {
if ( ['field2', 'field3'].indexOf( this.value ) > -1 )
{
$("#image").show();
}
else
{
$("#image").hide();
}
})
.change();
});
#image img {
padding-left: 60px;
position:absolute;
padding-top: -10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropdown" name="dropdown">
<option value="field1" selected="selected">None</option>
<option value="field2">field2</option>
<option value="field3">field3</option>
</select>
<div id="image">
<img src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQijmYaWonPS_ckwz9WLIrMpDPWCQDOTe8D7O_RIjEVcyMKr7NwZQ" alt="some image" />
</div>
Update
Note: For the purpose of continuity, it is good practice to retain the original question and include any new updates. When the question is drastically different, it's advisable to create a new question.
$(document).ready(function() {
$('#dropdown').on('change', function() {
$('#image,#image1').hide();
if ( this.value === 'field2')
{
$("#image").show();
}
else if(this.value === 'field3')
{
$("#image1").show();
}
else
{
$("#image").hide();
$("#image1").hide();
}
})
.change();
});
#imagex img {
padding-left:554px;
position:absolute;
padding-top: 774px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropdown" name="dropdown">
<option value="field1" selected="selected">None</option>
<option value="field2">field2</option>
<option value="field3">field3</option>
</select>
<span id="image">#image</span>
<span id="image1">#image1</span>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26538872",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Easiest way to test vim regex? I'm trying to write a vim syntax file, one problem I'm dealing with is vim's regex syntax is different from most other languages(I think the one called "perl compatible regex", Python, JavaScript etc. uses mostly the same regex syntax) and so I can't use regex testers like regexpal.
What is the easiest way to try vim regexes ? Ideally what I want is two splits, in one I'll write vim regex, and the other one will have the text, and matched parts should be highlighted.
Thanks in advance.
EDIT: I added a modified version of Ingo Karkat's answer to my .vimrc:
nnoremap <F5> mryi":let @/ = @"<CR>`r
This version also puts cursor back where it was when pressed F5 with the cost of losing mark r.
A: Use vim to test the regex. By typing / in vim you can search for stuff and the search uses regex.
For help on syntax have a look on vimregex
A: We can access Vim's registers in Ex mode or in searching mode by pressing Ctrl+R and then the register you want to paste.
In your situation we can use this to copy the text we want to test and then paste this in our search.
yi"/Ctrl+R0CR
Explanation:
yi" -> Yank inside of double quotes "
/ - > Open the search field
Ctrl+R0 -> paste the last yanked text
A: Do this in Vim. For syntax files, you often deal with start="^begin" stuff. Yank the regexp via yi", then highlight it via:
:let @/ = @"
Of course, if you need this often, bind this to a mapping (and :set hlsearch), like:
:nnoremap <F5> yi":let @/ = @"<CR>
A: Ideal solution:
https://github.com/bennypowers/nvim-regexplainer
But it seems that it only work on javascript regex, not vim's, so far.
Nice website (but no vim's regex engine)
Convert magic to very magic (to avoid backslashits):
https://github.com/sisrfeng/VimRegexConverter
Split to pieces of strings by hand:
if file_name =~# '\v^(' .. '[\%#~]' .. '|' .. '\.?[/\\]\a+:' .. '|' .. '^\d+' .. ')$'
vs
if file_name =~# '^\.\=[\\/]\|^\a\+:\|^[%#~]\|^\d\+$'
A: You can also try RegExr
It's a good tool to learn RegEx and try them in real time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14499107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Add mouse event listener to OBJMTL object - three.js I have created a OBJMTL 3D object with:
var loader = new THREE.OBJMTLLoader();
loader.addEventListener('load', function (event) {
Barrel = event.content;
side: THREE.DoubleSide;
scene.add(Barrel);
});
loader.load( '3D/Barrel/barrel.obj', '3D/Barrel/barrel.mtl');
I want to add an mouse event listener like in this :
link
Any other example of creating mouse listeners i found around the web does not work with OBJMTL loaded objects.
Any idea?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22389204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Convert foreach to lambda Just started with Lambda in c# and I got stumbled by this.How can I convert following code block to lambda expression, adding all the values in headers get added to DefaultRequestHeaders.
var client = new HttpClient();
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Name, header.Value);
}
A: This is no use case for a Lambda expression (as the discussion on Sim's answer shows), but it could be if you wanted to leverage parallel processing:
using System.Threading.Tasks;
Parallel.ForEach(headers, header =>
client.DefaultRequestHeaders.Add(header.Key, header.Value)
);
I wouldn't do that in this case though. The class might not be thread-safe and there is nothing to be gained here in terms of performance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50534129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
}
|
Q: Kendo UI Ajax Request I'm using Kendo UI Grid with an action link into a client-template column. This action link call an data edit view. See example:
c.Bound(p => p.sID).ClientTemplate(@Html.ImageActionLink(Url.Content("~/Content/images/edit3.png"), "Edit", "Edit", new { id = "#= sID #" }, new { title = "Edit", id = "Edit", border = 0, hspace = 2 }).ToString()
).Title("").Width(70).Filterable(false).Groupable(false).Sortable(false);
My question is how can I configure the grid in order to show an ajax loader when the action link is clicked, until the edit view is rendered?
A: you can create relative div and insert there your grid and loader wrapper:
<div class="grid-wrapper">
<div class="loading-wrapper">
<div class='k-loading-image loading'></div>
<!-- k-loading-image is standart kendo class that show loading image -->
</div>
@(Html.Kendo().Grid()....)
</div>
css:
.grid-wrapper {
position: relative;
}
.loading-wrapper {
display: none;
position: absolute;
width: 100%;
height: 100%;
z-index: 1000;
}
.loading {
position: absolute;
height: 4em;
top: 50%;
}
add to imageActionLink in htmlAttributes object class named "edit" (for example), and write click event handler:
$(document).on('click', '.edit', function (e) {
$('.loading-wrapper').show();
$.ajax({
// ajax opts
success: function(response) {
// insert your edit view received by ajax in right place
$('.loading-wrapper').hide();
}
})
});
A: you can do this like :
c.Bound(p => p.sID).Template(@<a href=\"YourLink\@item.sID\">Edit</a>).Title("Edit").Encoded(false);
//encoded false = Html.Raw
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19103415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Core data attribute not being made I've decided to add an NSNumber attribute to one of my entities in core data. I Cleaned the code and deleted the app from the simulator. I then added the following code in my appDelegate and it tells me that my NSNumber attribute doesn't exist.
People *PeopleA = [NSEntityDescription insertNewObjectForEntityForName:@"People" inManagedObjectContext:context];
PeopleA.name = @"Paul";
PeopleA.number = [NSNumber numberWithInt:12];
The name attribute works just fine, that was made before and it's always worked. But when it gets to PeopleA.number it crashes with :
-[People setNumber:]: unrecognized selector sent to instance 0x4d5eeb0
So I did a po 0x4d5eeb0 and saw that there is a name attribute but not one for number. My core data class should be good because I had XCode make it for me.
What could possibly be the issue?
Here is my People.h
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@class Group;
@interface People : NSManagedObject {
@private
}
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) id image;
@property (nonatomic, retain) NSNumber * number;
@property (nonatomic, retain) Group * group;
@end
People.m
#import "People.h"
#import "Group.h"
@implementation People
@dynamic name;
@dynamic image;
@dynamic number;
@dynamic group;
@end
po 0x4d5eeb0 gets me:
<People: 0x5932290> (entity: People; id: 0x59322f0 <x-coredata:///People/t83A9C7D9-4F7A-4189-9EC5-7695968A29552> ; data: {
group = nil;
name = Paul;
A: Printing the object in the debugger should give you all the properties defined in the class regardless of whether it is a NSManagedObject subclass held by a context or just a plain vanilla custom class. The debugger printout is not only missing the number property but the image one as well.
Really, the only way that could happen was if you didn't have the new version of the class file added to the target but were actually using the old version that lacked the new properties.
Check the target for the old files and/or check that the new version has been properly added to the build target.
A: Try naming the number attribute something different, such as theNumber. There are several known reserved words in Core Data attributes, and an unknown number (no pun intended) which are not documented - you may have stumbled onto another one.
A: When in doubt, delete it out.
I ended up deleting my two xcdatamodel files and the xcdatamodeld file. Also deleted them in their respective folders. Then I created a new one. Had some issues at first but it actually works now.
I have a little issue with xcode thinking that my Group.h file doesn't have an addPeople method, which it does. So it says that it may not respond to that method, or any of its other methods. It also throws me a Lexical or Preprocessor Issue: 'Group.h' file not found error at build-time, but everything seems to still work.
I still have no idea what was going on. Thanks to everyone for their suggestions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6601774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I calculate the difference between 2 numbers How can I calculate the diffrence between 2 Numbers in % in c? I have written my own exp funktion and want to compare it with the original one from the math.h.
this is my exp funktion and I want to compare the result with the exp() from math.h and print the difference in percent.
double expo(double zahl)
{
int schleifendurchlaeufe = 1;
double exp = 1;//Variable in der das Ergebnis steht
double sum = 1;//Summant, der auf exp raufaddiert wird
do
{
sum = sum * (zahl / schleifendurchlaeufe);
exp = exp + sum;
schleifendurchlaeufe++;
} while (exp != exp + sum);
return exp;
}
A: "difference between 2 Numbers in %" sounds strange, perhaps you want percentage difference (see explanation at https://www.mathsisfun.com/percentage-difference.html)
For case of comprising only results of exp function (two positive values) you can use the following function:
double percdiffcalc(double a, double b)
{
double difference = abs(a - b);
double average = (a + b) / 2.0;
return difference * 100.0 / average;
}
You can call this function for any two values, e.g. percdiffcalc(myexp(x), exp(x));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29626332",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: PHP ChromeDriver, multiple instances How to run multiple threads with multiple instances of chrome, is it possible? probably there is possibiity to operate via custom port?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73281668",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Shell Script for Flip Canvas Vertical I have M1.jpg M2.jpg ....... M100.jpg in /Users/KanZ/Desktop/Project/Test/
I would like Flip Canvas Vertical them, save and replace them instead of old files. How can I write the script for this problem?
A: You can do that with convert, with a little help from find so you don't have to write a loop:
find /Users/KanZ/Desktop/Project/Test/ -type f -name "M*.jpg" -exec convert {} -flip {} \;
Explanation:
*
*find /Users/KanZ/Desktop/Project/Test/ - Invoke find tool and specify the base directory to perform the search for files recursively.
*-type f - Find only files
*-name "M*.jpg" - Find only files with names that start with M and end with .jpg
*-exec ... \; - For each such file found, perform the command in ...
*convert {} -flip {} - This is the actual command that flips your images. The {}'s are syntax as part of the find command, they represent where the found files from find would be substituted into. So here we are saying to use convert to flip the images vertically with the -flip option, but keep the file names unchanged.
Alternatively:
You can also do it with a loop and globbing:
for file in /Users/KanZ/Desktop/Project/Test/M*.jpg; do convert "$file" -flip "$file"; done
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14008530",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Multi-dialog program in PyQT will not close For my project, I require multiple dialogs to be linked to each other. One button would go to one level, another button would go back two levels. To get a basic idea of what I'm looking for without showing all my code, here is a compilable example:
'''
Created on 2010-06-18
@author: dhatt
'''
import sys
from PyQt4 import QtGui, QtCore
class WindowLV3(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setGeometry(300, 300, 120, 150)
self.setWindowTitle('LV3')
quit = QtGui.QPushButton('Close', self)
quit.setGeometry(10, 10, 60, 35)
self.connect(quit, QtCore.SIGNAL('clicked()'),
QtGui.qApp, QtCore.SLOT('quit()')) # this will close entire program
class WindowLV2(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.Window3 = WindowLV3()
self.setGeometry(300, 300, 120, 150)
self.setWindowTitle('LV2')
quit = QtGui.QPushButton('Close', self)
quit.setGeometry(10, 10, 60, 35)
next = QtGui.QPushButton('Lv3', self)
next.setGeometry(10, 50, 60, 35)
self.connect(quit, QtCore.SIGNAL('clicked()'),
QtGui.qApp, QtCore.SLOT('reject()')) # this doesn't work
self.connect(next, QtCore.SIGNAL('clicked()'),
self.nextWindow)
def nextWindow(self):
self.Window3.show()
class WindowLV1(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.Window2 = WindowLV2()
self.setGeometry(300, 300, 120, 150)
self.setWindowTitle('LV1')
next = QtGui.QPushButton('Lv2', self)
next.setGeometry(10, 50, 60, 35)
quit = QtGui.QPushButton('Close', self)
quit.setGeometry(10, 10, 60, 35)
self.connect(next, QtCore.SIGNAL('clicked()'),
self.nextWindow)
def nextWindow(self):
self.Window2.show()
self.connect(quit, QtCore.SIGNAL('clicked()'),
QtGui.qApp, QtCore.SLOT('reject()')) # this doesn't work
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
Window1 = WindowLV1()
Window1.show()
sys.exit(app.exec_())
The problem is that I cannot close from a window and show the previous window. For instance, if I clicked on the 'CLOSE' button inside from a LV3 window, it will transfer control back to a LV2 window. I can call QtCore.SLOT('quit()')), but it will shut down the entire program, and I don't want that.
What am I doing wrong here?
A: there are two things that need to be addressed here.
*
*You can simply call QDialog.close in the connect method.
*In def nextWindow(self): you are trying to connect a local variable quit. So it won't work. You need to define quit as an instance variable (self.quit)
self.connect(self.quit, QtCore.SIGNAL('clicked()'),
self.close) # this should work
Here is the modified code:
import sys
from PyQt4 import QtGui, QtCore
class WindowLV3(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setGeometry(300, 300, 120, 150)
self.setWindowTitle('LV3')
self.quit = QtGui.QPushButton('Close', self)
self.quit.setGeometry(10, 10, 60, 35)
self.connect(self.quit, QtCore.SIGNAL('clicked()'),
self.close) # this will close entire program
class WindowLV2(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.Window3 = WindowLV3()
self.setGeometry(300, 300, 120, 150)
self.setWindowTitle('LV2')
self.quit = QtGui.QPushButton('Close', self)
self.quit.setGeometry(10, 10, 60, 35)
next = QtGui.QPushButton('Lv3', self)
next.setGeometry(10, 50, 60, 35)
self.connect(self.quit, QtCore.SIGNAL('clicked()'),
self.close) # this should work
self.connect(next, QtCore.SIGNAL('clicked()'),
self.nextWindow)
def nextWindow(self):
self.Window3.show()
class WindowLV1(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.Window2 = WindowLV2()
self.setGeometry(300, 300, 120, 150)
self.setWindowTitle('LV1')
next = QtGui.QPushButton('Lv2', self)
next.setGeometry(10, 50, 60, 35)
self.quit = QtGui.QPushButton('Close', self)
self.quit.setGeometry(10, 10, 60, 35)
self.connect(next, QtCore.SIGNAL('clicked()'),
self.nextWindow)
def nextWindow(self):
self.Window2.show()
self.connect(self.quit, QtCore.SIGNAL('clicked()'),
self.close) # this should work
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
Window1 = WindowLV1()
Window1.show()
sys.exit(app.exec_())
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3072787",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: gstreamer: gst/app/gstappsrc.h no such file or directory I have installed gstreamer1.0-plugins-base use command:
$ sudo apt-get install gstreamer1.0-plugins-base
but when I compile my code, it still gives me an error
gst/app/gstappsrc.h: no such file or directory
And I even can't find the directory /app at the directory /usr/include/gstremer1.0/gst
A: You will need the development header files. The package is probably named libgstreamer-plugins-base1.0-dev or close to that.
A: You need the include (headers) and link (libs) directories for gstreamer-app-1.0, part of the gstreamer base-plugins.
If you are using pkg-config, try the following command to get all the compilation flags you need:
pkg-config --cflags --libs gstreamer-app-1.0
In case of CMake with pkg-config:
# pkg-config
find_package(PkgConfig)
pkg_check_modules(GSTREAMER REQUIRED gstreamer-1.0)
pkg_check_modules(GSTREAMER_APP REQUIRED gstreamer-app-1.0)
# including header files directories
include_directories(
${GSTREAMER_INCLUDE_DIRS}
${GSTREAMER_APP_INCLUDE_DIRS}
)
# linking library directories
link_directories(
${GSTREAMER_LIBRARY_DIRS}
${GSTREAMER_APP_LIBRARY_DIRS}
)
# linking gstreamer library with target executable
target_link_libraries(${PROJECT_NAME} ${GSTREAMER_LIBRARIES})
target_link_libraries(${PROJECT_NAME} ${GSTREAMER_APP_LIBRARIES})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53156503",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Window owner in WPF without always-on-top behaviour Is it possible to get some of the functionality of Window.Owner without getting all of it?
There are two windows, window A and window B. I want to make it so that selecting either one will bring them on top of other applications, but either one can overlay the other. (In reality there more than just two, but they should all behave similarly.)
If I set window B's Owner to A, then switching to either window will bring both in front of other applications (which I want), but will also force B to always sit on top of A (which I don't want).
I actually already have code which is tracking the window hierarchy independently of Owner/OwnedWindows, so I can probably extend that to sort out the activation problem. So if that simplifies the problem, an alternative answer I'm looking for is:
How do I actually do "when this window is activated by the user, bring a specific set of windows (all the others in the app) to the Z-order just below me, while preserving their existing Z-orders relative to each other"?
A: One possible solution would be to have a hidden window that owns all the windows in your app.
You would declare it something like:
<Window
Opacity="0"
ShowInTaskbar="False"
AllowsTransparency="true"
WindowStyle="None">
Be sure to remove StartupUri from your App.xaml. And in your App.xaml.cs you would override OnStartup to look something like:
protected override void OnStartup(StartupEventArgs e)
{
HiddenMainWindow window = new HiddenMainWindow();
window.Show();
Window1 one = new Window1();
one.Owner = window;
one.Show();
Window2 two = new Window2();
two.Owner = window;
two.Show();
}
Another difficulty will be how you want to handle closing the actual application. If one of these windows is considered the MainWindow you can just change the application ShutdownMode to ShutdownMode.OnMainWindowClose and then set the MainWindow property to either of those windows. Otherwise you will need to determine when all windows are closed and call Shutdown explicitly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5455399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Adding a custom domain in PythonAnywhere does not work I added my application to pythonanywhere, now I'm trying to add a custom domain but I can not get a positive result.
My change I've added in pythonanywhere looks like this. Under my hidden field is my domain name.
According to the documentation, I added a CNAME record (at my domain provider, it looks like this.).
But after entering in the address www.ka ....pl I am not being redirected to my django application in pythonanywhere.
This is my first time when i added my domain, how to fix this error (so that my application will appear after entering the domain), any help will be appreciated.
A: When setting up your CNAME, you need to end its value with a dot. to be absolute
CNAME: webapp-*****.pythonanywhere.com.
Otherwise it will be relative to your custom domain and end up like this :
webapp-*****.pythonanywhere.com.$DOMAIN
See Domain names with dots at the end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55087080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Cannot read property of undefined angular2 ngif I am now able to get the object in the view however I cannot run an if statement. Per previous answer this is how I am bringing in the object.
public getPosts$(category, limit) {
return this.cartService.getPosts(category, limit).map(response => {
return response && response.data && response.data.children;
};
}
ngOnInit() {
this.getPosts$(this.category, this.limit).subscribe(cart => {
this.cart = cart;
}
}
I am trying to run but get cannot get property vegetable.
<h2 *ngIf="cart">{{cart.vegetable}}</h2>
<h2 *ngIf="cart.vegetable == 'carrot' ">{{cart.vegetable}}</h2>
The error is
Cannot read property 'vegtable' of undefined
A: The cart object is null until the service getPosts$ returns (callback). Therefore, the code *ngIf="cart.vegetable ... is equal to *ngIf="null.vegetable ... until that happens. That is what is happening.
What you could do is put a DOM element with *ngIf="cart" containing the other *ngIf. For example:
<div *ngIf="cart">
<h2 *ngIf="cart.vegetable == 'carrot' ">{{cart.vegetable}}</h2>
</div>
*Edit: As it is said in the next answer, a good alternative (and good practice) is the following:
<h2 *ngIf="cart?.vegetable == 'carrot' ">{{cart.vegetable}}</h2>
A: Use the safe-navigation operator to guard against null or undefined for async fetched data:
<h2 *ngIf="cart?.vegetable == 'carrot' ">{{cart.vegetable}}</h2>
A: I used {{ }} while they are not needed. Getting rid of them fixed it for me.
So this
<li *ngIf="{{house}}">
Should be
<li *ngIf="house">
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41985595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: How can I close dropdown if another dropdown is open I have some dynamic contents like sort of a news-feed and each element has a dropdown menu.
I am able to toggle the dropdown-menu of the exact element I click on and when I click outside or anywhere else on the window it closes the menu which is nice.
but problem arise when I click on another dropdown element. The previously clicked menu doesn't close instead it stays on the same page.
what I am trying to say is
when I click multiple dropdown elements, I have them all showing,
it only closes or disappears when I click outside of element.
For instance
When I click on dropdown-1, then click on dropdown-2, they both display at the same window. How do I close dropdown 1 while dropdown 2 is open instead of having them both open.
How can I toggle each dropdown as I click. I am unable to attach video to this post, but I have added an image to help clarify my question.
This is an example of my JQuery code to toggle dropdown.
/* toggle dropdown options */
$(document).on("click", ".dropdown-toggle", function (e) {
e.stopPropagation();
$(this).siblings().toggleClass('show');
});
/* // Close the dropdown if the user clicks outside of it */
$(window).click(function (e) {
if (!e.target.matches('.dropbtn') ) {
var dropdowns = $('.dropdown-content');
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if ($(openDropdown).hasClass("show") ) {
$(openDropdown).removeClass("show");
}
}
}
});
A: I have been able to solve this problem.
what I did was to hide all divs that may be visible then toggle the dropdown I clicked to show its content.
$(document).on("click", ".dropdown-toggle", function (e) {
e.stopPropagation();
// hide all dropdown that may be visible
var i;
var dropdowns = $('.dropdown-content');
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if ($(openDropdown).hasClass("show")) {
$(openDropdown).removeClass("show");
}
}
// toggle the dropdown
$(this).siblings().toggleClass('show');
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64173235",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Javascript global variable not updating outside any functions I'm trying to get the following code to work (the console.log are just to see what's going on). I've declared the global variables outside of any functions, but it only seems to be updating them inside functions.
<script type="text/javascript">
var map;
var geocoder;
var address;
function initialize(){
geocoder = new google.maps.Geocoder();
var mapOptions = {
center:new google.maps.LatLng(-76.146294, 43.052081),
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 15,
streetViewControl: false
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
loadAddress();
console.log("initialize function: " + address); //this correctly returns the updated address
}
function loadAddress(){
var property = <?php echo json_encode(urlencode($Residential['ReAddress'])); ?>;
var zipCode = <?php echo json_encode($Residential['zipCode']); ?>;
address = property + "," + zipCode;
geocoder.geocode({'address': address}, function(result, status){
if(status === "OK"){
map.setCenter(result[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: result[0].geometry.location
});
}
else {
alert("Failed to geocode: " + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
The above works fine - the 'address' variable updates properly, and when I log it to the console at the end of the initialize() function, it displays properly. The problem is if I try to log that same variable to the console further down the page:
<script type="text/javascript">
console.log("further down page: " + address); //this comes back as 'undefined'
</script>
When I try to do that, I just get 'undefined'. I'm pretty new to javascript, but my understanding was that if the variable is declared outside of any functions, it is a global variable, and it should be accessible anywhere. I feel like I'm missing something pretty obvious, but I don't know what (and I've spent quite a bit of time searching!).
My hunch is that it has to do with the initialize() not being called until after the page loads, but 'address' is trying to be logged before the page has finished loading. If that's the issue, I don't know how to fix it.
Also, I'm sure the above code is not the best way to do things, but this is really more of a learning experience. Thanks!
A: The problem is that the geocoder.geocode function is asynchronous : it doesn't block the code, the following lines are executed, but the inner callback isn't called until the server responds.
This means that you must put your console.log line inside the callback or in a function called from the callback :
geocoder.geocode({'address': address}, function(result, status){
if(status === "OK"){
map.setCenter(result[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: result[0].geometry.location
});
} else {
alert("Failed to geocode: " + status);
}
otherFunc();
});
function otherFunc(){
console.log("further down page: " + address);
}
A: Your hunch is correct. The code further down the page is executing in place before your initialize method is called. window.load is not fired until the DOM is loaded, including images:
The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.
A simple fix here would be to define address right away. Its components are static on the page, there's no reason to have that happen inside the function.
var property = <?php echo json_encode(urlencode($Residential['ReAddress'])); ?>;
var zipCode = <?php echo json_encode($Residential['zipCode']); ?>;
var address = property + "," + zipCode;
function loadAddress() {
// ...
}
A: The problem is that the second <script>-element is executed right away when the browser loads the page. In your first block you add the DOM-listener for the load-event, which should call initialize(). However, that is executed later when the browser has fully loaded and built the page.
If you log the value after it has been determined in the callback to geocoder.geocode() it should print the proper value.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19479290",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Query MYSQL - mysql query distinct count I have the following table:
ID_PERSON NAME_PERSON
001 JHON SLAVE
002 BRUCE WILLIAN
001 PAUL BYLING
I would like to know, for example, how many cases the ID_PERSON 001 is linked to different names (distinctly)
My current query:
SELECT ID_PERSON, COUNT(DISTINCT(NAME_PERSON))
GROUP BY ID_PERSON
HAVING COUNT(DISTINCT(NAME_PERSON)>1
The output I expect are 2 records: 001 from Jhon and 001 from Paul
As my table has millions of records, it is not performing
A: SELECT t1.*
FROM src_table t1
JOIN ( SELECT ID_PERSON
FROM src_table t2
GROUP BY ID_PERSON
HAVING COUNT(DISTINCT(NAME_PERSON) > 1 ) t3 USING (ID_PERSON)
SELECT *
FROM src_table t1
WHERE EXISTS ( SELECT NULL
FROM src_table t2
WHERE t1.ID_PERSON = t2.ID_PERSON
AND t1.NAME_PERSON <> t2.NAME_PERSON )
There are more variants.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71147537",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get consecutive nodes with following-sibling and condition My XML file looks like this, but bigger:
<w><forme>la</forme><lemme>le</lemme><categorie>DETDFS</categorie></w>
<w><forme>grande</forme><lemme>grand</lemme><categorie>ADJFS</categorie></w>
<w><forme>douleur</forme><lemme>douleur</lemme><categorie>NCFS</categorie></w>
<w><forme>du</forme><lemme>du</lemme><categorie>DETDMS</categorie></w>
<w><forme>père</forme><lemme>père</lemme><categorie>NCMS</categorie></w>
<w><forme>duchesne</forme><lemme>duchesne</lemme><categorie>NCMS</categorie></w>
<w><forme>exemple.</forme><lemme>exemple.</lemme><categorie>NCMS</categorie></w>
<!-- ... -->
I would like to get every <w> node recursively to get words to create sentences with.
For example, the final word here is "exemple.". So I would like to get every <forme> until .
to generate a sentence.
For now I can only match the node with the full stop. I don't know how to select the first <w> node (first word of the sentence) until the last <w> node (final word).
following-sibling::w[contains(forme, '.')][1]
My goal is to select every <w> node (or <forme>) until the word with the full stop, and recursively.
I started to write a template to concatenate strings:
<xsl:template name="concat">
<xsl:param name="liste" />
<xsl:param name="result" select="''"/>
<xsl:choose>
<xsl:when test="$liste">
<xsl:call-template name="concat">
<xsl:with-param name="liste" select="$liste[position() > 1]" />
<xsl:with-param name="result" select="concat($result, ' ', $liste[1])" />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$result" disable-output-escaping="no" />
</xsl:otherwise>
</xsl:choose>
</xsl:template>
Thx for the help. It's very important.
A: One approach would be to use an <xsl:key> in the following way.
Keys let you index nodes by a certain property, for example you could index all nodes by some attribute value. But you could also index them by a calculated value.
In your case you have many <w> nodes like this:
<doc> <!-- Sentence # -->
<w><forme>le</forme><lemme>le</lemme><categorie>DETDFS</categorie></w> <!-- 0 -->
<w><forme>grand</forme><lemme>grand</lemme><categorie>ADJFS</categorie></w> <!-- 0 -->
<w><forme>test.</forme><lemme>test.</lemme><categorie>NCMS</categorie></w> <!-- 0 -->
<w><forme>la</forme><lemme>le</lemme><categorie>DETDFS</categorie></w> <!-- 1 -->
<w><forme>grande</forme><lemme>grand</lemme><categorie>ADJFS</categorie></w> <!-- 1 -->
<w><forme>douleur</forme><lemme>douleur</lemme><categorie>NCFS</categorie></w> <!-- 1 -->
<w><forme>du</forme><lemme>du</lemme><categorie>DETDMS</categorie></w> <!-- 1 -->
<w><forme>père</forme><lemme>père</lemme><categorie>NCMS</categorie></w> <!-- 1 -->
<w><forme>duchesne</forme><lemme>duchesne</lemme><categorie>NCMS</categorie></w> <!-- 1 -->
<w><forme>exemple.</forme><lemme>exemple.</lemme><categorie>NCMS</categorie></w> <!-- 1 -->
<w><forme>phrase</forme><lemme>phrase</lemme><categorie>NCMS</categorie></w> <!-- 2 -->
<w><forme>suivante</forme><lemme>suivante</lemme><categorie>NCMS</categorie></w> <!-- 2 -->
</doc>
The ones with the full stop demarcate a sentence end. The preceding siblings up to the previous full stop are words of the same sentence.
We could say: "All words belong to the same sentence that are preceded by the same number of full stops."
The numbers in the comments above represent exactly that number. We can calculate it with count(preceding-sibling::w[substring(forme, string-length(forme), 1) = '.']). And we can create an <xsl:key> that indexes <w> nodes by this number.
And then it's a matter of going over each node that marks a sentence end and using key() to retrieve all the <w> nodes that belong to the same sentence:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes" />
<xsl:key
name="kSentence"
match="w"
use="count(preceding-sibling::w[substring(forme, string-length(forme), 1) = '.'])"
/>
<xsl:template match="/*">
<sentences>
<xsl:for-each select="w[substring(forme, string-length(forme), 1) = '.']">
<xsl:variable
name="sentenceNum"
select="count(preceding-sibling::w[substring(forme, string-length(forme), 1) = '.'])"
/>
<sentence>
<xsl:copy-of select="key('kSentence', $sentenceNum)/lemme" />
</sentence>
</xsl:for-each>
</sentences>
</xsl:template>
</xsl:stylesheet>
gives this result:
<sentences>
<sentence>
<lemme>le</lemme>
<lemme>grand</lemme>
<lemme>test.</lemme>
</sentence>
<sentence>
<lemme>le</lemme>
<lemme>grand</lemme>
<lemme>douleur</lemme>
<lemme>du</lemme>
<lemme>père</lemme>
<lemme>duchesne</lemme>
<lemme>exemple.</lemme>
</sentence>
</sentences>
The "phrase suivante" is not part of the result because it did not end with a full stop in my example.
A: Either use classical sibling recursion where you in the template matching the parent/container node of the w siblings start with <xsl:apply-templates select="w[1]"/> and then process <xsl:apply-templates select="following-sibling::w[1]"><xsl:with-param name="previous-ws" select="$previous-ws | ."/></xsl:apply-templates/> and have two template matches for e.g. <xsl:template match="w[not(substring(forme, string-length(forme)) = '.')]"> and <xsl:template match="w[substring(forme, string-length(forme)) = '.']"> or use a key <xsl:key name="siblings" match="w[not(substring(forme, string-length(forme)) = '.')]" use="generate-id(following-sibling::w[substring(forme, string-length(forme)) = '.'][1])"/>, then process all <xsl:apply-templates select="w[substring(forme, string-length(forme)) = '.']"/> and in the template matching w you can collect the preceding siblings simply with key('siblings', generate-id()).
A: This is very simple to do in XSLT 2.0 using xsl:fer each group with group-ending-with.
There are several methods to accomplish the same thing in XSLT 1.0 - among them "sibling recursion" or using a key to link each word to its nearest following sibling that ends with a period (both of these have been mentioned by Martin Honnen in his answer above).
The method you have attempted, using a recursive named template, is also an option. Here is a simplified example:
XML
<root>
<word>Joe</word>
<word>waited</word>
<word>for</word>
<word>train.</word>
<word>The</word>
<word>train</word>
<word>was</word>
<word>late.</word>
<word>Mary</word>
<word>and</word>
<word>Samantha</word>
<word>took</word>
<word>the</word>
<word>bus.</word>
<word>Orphan</word>
</root>
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/root">
<output>
<xsl:call-template name="combine-words">
<xsl:with-param name="words" select="word"/>
</xsl:call-template>
</output>
</xsl:template>
<xsl:template name="combine-words">
<xsl:param name="words" />
<xsl:param name="accumulated" select="/.."/>
<xsl:if test="$words">
<xsl:variable name="word" select="$words[1]" />
<xsl:variable name="isLast" select="substring($word, string-length($word), 1)='.'" />
<xsl:if test="$isLast">
<sentence>
<xsl:for-each select="$accumulated | $word">
<xsl:value-of select="." />
<xsl:if test="position()!=last()">
<xsl:text> </xsl:text>
</xsl:if>
</xsl:for-each>
</sentence>
</xsl:if>
<xsl:call-template name="combine-words">
<xsl:with-param name="words" select="$words[position() > 1]"/>
<xsl:with-param name="accumulated" select="$accumulated[not($isLast)] | $word[not($isLast)]"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
Result
<?xml version="1.0" encoding="UTF-8"?>
<output>
<sentence>Joe waited for train.</sentence>
<sentence>The train was late.</sentence>
<sentence>Mary and Samantha took the bus.</sentence>
</output>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67034123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: can we write that function in c form When I read some question to write random nuber generator ,I saw that function and it
efficient but it is written in C#. I want see that function in form of c
language,can anyone help?
IEnumerable<int> ForLargeQuantityAndRange(int quantity, int range)
{
for (int n = 0; n < quantity; n++)
{
int r = Random(range);
while (!used.Add(r))
r = Random(range);
yield return r;
}
}
A: Questions regarding number generators for C have been asked before here on SO, such as in the article "Create Random Number Sequence with No Repeats".
I'd suggest looking at the above article to see if anything is suitable and provides a useful alternative to the standard rand() function in C, assuming that you've already looked at the latter and rejected it.
A: This is not quite a function, as function in C or C++. This is a co-routine, which may be resumed.
To implement it in C, you will need to maintain external state, and provide a "next value" func.
The advantage of this function is that it guarantees unique values. Do you really need it? If not, use stdlib's rand, multiplied by proper factors.
A: Do you just want random numbers? If so, why don't you use one of the many libraries out there that can do it for you in a cross platform fashion? Here's one.
A: To write a co-routine in C, you need to maintain state. This simplest way to do this is to use a static variable. For this example, it would look something like:
int ForLargeQuantityAndRange(int init_quantity, int init_range)
{
static int n;
static int quantity, range;
if (init_quantity > 0)
{
n = 0;
quantity = init_quantity;
range = init_range;
}
if (n++ < quantity)
{
int r = Random(range);
while (!used_add(r))
r = Random(range);
return r;
}
/* Quantity exceeded */
return -1;
}
...where you would call it with (quantity, range) to intialise a new sequence, and (0, 0) to continue the previous sequence.
Note that you will have to supply implementations of the Random() and used_add() functions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3123704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: RecyclerView - How to select items by dpad/keyboard How can you select items of a RecyclerView using the dpad and/or keyboard?
A: Make your items focusable. It will let you navigate it via dpad. Then you'll need to add your logic to "select" focused item on press. (whatever your select key is)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27107714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to get openCL library for Hi3536 Mali GPU We are using Hi3536 Soc, which has Mali T720 core. The SDK of Hi3536 does not provide examples for OpenCL nor the library. Any suggestions how to get the cross-compiled SDK libraries for Mali T720?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50172306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: LINQ two Where clauses does anybody know how I can chain my where clauses?
I would like to filter the items in my main list by the items found in the second result.
I have the following example code
@foreach (var artikel in Controller.Artikel
.Where(x => x.LieferantenArtikel
.Where(y => y.Lieferant.LieferantId == bestellung.LieferantId)
)
{
<option value="@artikel.Artikelnummer">@artikel.Artikelnummer</option>
}
The first .Where is just to access the list of my object, which has the real check I need.
A: Your way of chaining .Where() into .Where() is technically correct. The problem is that the outer .Where() under the current situation does not evaluate to boolean. However, that's a requirement. The purpose of a .Where() is to define a filter for a collection that results in a subset of that collection. You can check whether .Any() item fulfills that condition:
@foreach (var artikel in Controller.Artikel
.Where(x => x.LieferantenArtikel
.Any(y => y.Lieferant.LieferantId == bestellung.LieferantId))
)
{
<option value="@artikel.Artikelnummer">@artikel.Artikelnummer</option>
}
.
A: To add a bit more context to the other answers, which hopefully helps you to understand how to efficiently use LINQ:
What you tried to program using .Where() is technically "where exists". Translated into LINQ naively, that would be
Controller.Artikel
.Where(x =>
x.LieferantenArtikel
.Where(y => y.Lieferant.LieferantId == bestellung.LieferantId)
.Count() > 0 // naive "exists", but bad; for reasons see below
)
.Count() > 0 however is very inefficient, since this would require the execution of .Count() to evaluate the statement, which in turn requires to determine the accurate result set.
This is where .Any() steps in: it only determines if there is at least one element in the IEnumerable by checking them and immediately returning true when the first item matches. So only if there is no match, all items of "LieferantenArtikel" have to be enumerated and checked, otherwise a smaller subset will do.
A: I find non-nested LINQs to be much more readable. Flatten things out with SelectMany, and then use Where. Note that you need to make sure Equals() is implemented in Artikel so Distinct() does its job properly.
var artikels = Controller.Artikel
.SelectMany(x => x.LieferantenArtikel, (x, l) => (Artikel: x, Lieferant: l))
.Where(x => x.Lieferant.LieferantId == bestellung.LieferantId)
.Select(x => x.Artikel)
.Distinct();
@foreach(var artikel in artikels)
{
<option value="@artikel.Artikelnummer">@artikel.Artikelnummer</option>
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64318386",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Align tables to each others side I have created two tables with bootstrap 4, which show on the one hand specifications and on the other hand earning statistics.
I put both tables in a col-xs-6-class and want one table aligned to the left and the other table to the right. However, currently the tables are somehow clued to each other. Please find below my minimum viable example:
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="row">
<div class="col-xs-6">
<h2>Specifications</h2>
<table class="table stats">
<tbody>
<tr>
<th>Price :</th>
<td class=" text-right">
100 </td>
</tr>
<tr>
<th>Manufacturer:</th>
<td class=" text-right">
Gigabyte </td>
</tr>
<tr>
<th>Wattage:</th>
<td class=" text-right">
150 </td>
</tr>
<tr>
<th>Product:</th>
<td class=" text-right">
Product 1 </td>
</tr>
</tbody>
</table>
</div>
<div class="col-xs-6">
<h2>Earning</h2>
<table class="table stats">
<tbody>
</tbody>
<thead>
<tr>
<th>Period</th>
<th class="text-right">Rev</th>
<th class="text-right">Cost</th>
<th class="text-right">Profit</th>
</tr>
</thead>
<tbody>
<tr>
<td>Hour</td>
<td class="text-right text-info">$
<span id="rev-hour">
0.022 </span>
</td>
<td class="text-right text-danger">$
<span id="cost-hour">
0.006 </span>
</td>
<td class="text-right text-success">$
<span id="earning-hour">
0.016 </span>
</td>
</tr>
<tr>
<td>Day</td>
<td class="text-right text-info">$
<span id="rev-day">
1.34 </span>
</td>
<td class="text-right text-danger">$
<span id="cost-day">
0.36 </span>
</td>
<td class="text-right text-success">$
<span id="earning-day">
0.98 </span>
</td>
</tr>
<tr>
<td>Week</td>
<td class="text-right text-info">$
<span id="rev-week">
9.37 </span>
</td>
<td class="text-right text-danger">$
<span id="cost-week">
2.52 </span>
</td>
<td class="text-right text-success">$
<span id="earning-week">
6.85 </span>
</td>
</tr>
<tr>
<td>Month</td>
<td class="text-right text-info">$
<span id="rev-month">
37.48 </span>
</td>
<td class="text-right text-danger">$
<span id="cost-month">
10.08 </span>
</td>
<td class="text-right text-success">$
<span id="earning-month">
27.40 </span>
</td>
</tr>
<tr>
<td>Year</td>
<td class="text-right text-info">$
<span id="rev-year">
449.77 </span>
</td>
<td class="text-right text-danger">$
<span id="cost-year">
120.96 </span>
</td>
<td class="text-right text-success">$
<span id="earning-year">
328.81 </span>
</td>
</tr>
</tbody>
</table>
</div>
</div>
Any suggestions how to align the Specification table to the left and the Earnings table to the right?
I appreciate your replies!
A: One ruleset:
table.table.stats {display:inline-table}
display: inline-table behavior is simply a table that will sit inline with elements instead of the default behavior of occupying the whole width and pushing everything at its left and right -- up and down.
you might have a more complicated environment with your real code so you can
Chain the classes to get higher specificity which may be overkill but with Bootstrap it is common necessity.
table.table.stats.table.stats {display:inline-table}
Demo
table.table.stats {
display: inline-table
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="row">
<div class="col-xs-6">
<h2>Specifications</h2>
<table class="table stats">
<tbody>
<tr>
<th>Price :</th>
<td class=" text-right">
100 </td>
</tr>
<tr>
<th>Manufacturer:</th>
<td class=" text-right">
Gigabyte </td>
</tr>
<tr>
<th>Wattage:</th>
<td class=" text-right">
150 </td>
</tr>
<tr>
<th>Product:</th>
<td class=" text-right">
Product 1 </td>
</tr>
</tbody>
</table>
</div>
<div class="col-xs-6">
<h2>Earning</h2>
<table class="table stats">
<tbody>
</tbody>
<thead>
<tr>
<th>Period</th>
<th class="text-right">Rev</th>
<th class="text-right">Cost</th>
<th class="text-right">Profit</th>
</tr>
</thead>
<tbody>
<tr>
<td>Hour</td>
<td class="text-right text-info">$
<span id="rev-hour">
0.022 </span>
</td>
<td class="text-right text-danger">$
<span id="cost-hour">
0.006 </span>
</td>
<td class="text-right text-success">$
<span id="earning-hour">
0.016 </span>
</td>
</tr>
<tr>
<td>Day</td>
<td class="text-right text-info">$
<span id="rev-day">
1.34 </span>
</td>
<td class="text-right text-danger">$
<span id="cost-day">
0.36 </span>
</td>
<td class="text-right text-success">$
<span id="earning-day">
0.98 </span>
</td>
</tr>
<tr>
<td>Week</td>
<td class="text-right text-info">$
<span id="rev-week">
9.37 </span>
</td>
<td class="text-right text-danger">$
<span id="cost-week">
2.52 </span>
</td>
<td class="text-right text-success">$
<span id="earning-week">
6.85 </span>
</td>
</tr>
<tr>
<td>Month</td>
<td class="text-right text-info">$
<span id="rev-month">
37.48 </span>
</td>
<td class="text-right text-danger">$
<span id="cost-month">
10.08 </span>
</td>
<td class="text-right text-success">$
<span id="earning-month">
27.40 </span>
</td>
</tr>
<tr>
<td>Year</td>
<td class="text-right text-info">$
<span id="rev-year">
449.77 </span>
</td>
<td class="text-right text-danger">$
<span id="cost-year">
120.96 </span>
</td>
<td class="text-right text-success">$
<span id="earning-year">
328.81 </span>
</td>
</tr>
</tbody>
</table>
</div>
</div>
A: Add the container-fluid class div around the row.
There is no such class as col-xs-6 instead use col-6
Added another div in col-6 and add padding to it for making some space between them.
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="container-fluid">
<div class="row">
<div class="col-6">
<div class="pr-1">
<h2>Specifications</h2>
<table class="table stats">
<tbody>
<tr>
<th>Price :</th>
<td class=" text-right">
100 </td>
</tr>
<tr>
<th>Manufacturer:</th>
<td class=" text-right">
Gigabyte </td>
</tr>
<tr>
<th>Wattage:</th>
<td class=" text-right">
150 </td>
</tr>
<tr>
<th>Product:</th>
<td class=" text-right">
Product 1 </td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="col-6">
<div class="pr-1">
<h2>Earning</h2>
<table class="table stats">
<tbody>
</tbody>
<thead>
<tr>
<th>Period</th>
<th class="text-right">Rev</th>
<th class="text-right">Cost</th>
<th class="text-right">Profit</th>
</tr>
</thead>
<tbody>
<tr>
<td>Hour</td>
<td class="text-right text-info">$
<span id="rev-hour">
0.022 </span>
</td>
<td class="text-right text-danger">$
<span id="cost-hour">
0.006 </span>
</td>
<td class="text-right text-success">$
<span id="earning-hour">
0.016 </span>
</td>
</tr>
<tr>
<td>Day</td>
<td class="text-right text-info">$
<span id="rev-day">
1.34 </span>
</td>
<td class="text-right text-danger">$
<span id="cost-day">
0.36 </span>
</td>
<td class="text-right text-success">$
<span id="earning-day">
0.98 </span>
</td>
</tr>
<tr>
<td>Week</td>
<td class="text-right text-info">$
<span id="rev-week">
9.37 </span>
</td>
<td class="text-right text-danger">$
<span id="cost-week">
2.52 </span>
</td>
<td class="text-right text-success">$
<span id="earning-week">
6.85 </span>
</td>
</tr>
<tr>
<td>Month</td>
<td class="text-right text-info">$
<span id="rev-month">
37.48 </span>
</td>
<td class="text-right text-danger">$
<span id="cost-month">
10.08 </span>
</td>
<td class="text-right text-success">$
<span id="earning-month">
27.40 </span>
</td>
</tr>
<tr>
<td>Year</td>
<td class="text-right text-info">$
<span id="rev-year">
449.77 </span>
</td>
<td class="text-right text-danger">$
<span id="cost-year">
120.96 </span>
</td>
<td class="text-right text-success">$
<span id="earning-year">
328.81 </span>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50928565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Reaction Delete channel | Discord.js I am making a ticket system with discord.js
I tried to when a member reacts to the message with the emoji, the ticket will close, but after running it, it shows an error
if (reaction.emoji.name == '') {
if(!reaction.channel.name.includes("ticket")) return;
channel.delete()
}
A: Even though you didn't specify the error I can see that you never defined "channel".
If you want to delete the channel in which the reaction was added use:
reaction.message.channel.delete();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64858045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: pyspark dataframe filter using variable list values I have a requirment to filter the pyspark dataframe where user will pass directly the filter column part as a string parameter. For example:
Sample Input data: df_input
|dim1|dim2| byvar|value1|value2|
| 101| 201|MTD0001| 1| 10|
| 201| 202|MTD0002| 2| 12|
| 301| 302|MTD0003| 3| 13|
| 401| 402|MTD0004| 5| 19|
Ex 1: filter_str = "dim2 = '201'"
I will filter the data as: df_input = df_input.filter(filter_str)
Output: (**I'm able to get the output**)
|dim1|dim2| byvar|value1|value2|
| 101| 201|MTD0001| 1| 10|
But, for multiple filter condition I'm getting error and not able to filter.
Scenario where I'm not able to filter the input dataframe:
valid Scr 1:
filter_str = "dim1 = '101' and dim2 in '['302', '402']'"
df_inp = df_inp.filter(filter_str)
Getting Error
valid Scr 2:
value_list = ['302', '402']
filter_str = "dim1 = '101' or dim2 in '(value_list)'"
df_inp = df_inp.filter(filter_str)
Getting Error
Could you please help in acheiving the scr 1 and 2 and how to modify the filter section if i get the filter_str string as mentioned I example.
A: Use & (or) | operators in your filter query and enclose each statement with brackets ().
df.filter((col("dim1") == '101') | (col("dim2").isin(['302','402']))).show()
#+----+----+-------+------+------+
#|dim1|dim2| byvar|value1|value2|
#+----+----+-------+------+------+
#| 101| 201|MTD0001| 1| 10|
#| 301| 302|MTD0003| 3| 13|
#| 401| 402|MTD0004| 5| 19|
#+----+----+-------+------+------+
df.filter((col("dim1") == '101') & (col("dim2").isin(['302','402']))).show()
#+----+----+-----+------+------+
#|dim1|dim2|byvar|value1|value2|
#+----+----+-----+------+------+
#+----+----+-----+------+------+
Using expr:
Here we need to convert list to tuple to perform in on value_list
#using filter_str
value_list = ['302', '402']
filter_str = "dim1 = '101' or dim2 in {0}".format(tuple(value_list))
filter_str
#"dim1 = '101' or dim2 in ('302', '402')"
df.filter(expr(filter_str)).show()
#+----+----+-------+------+------+
#|dim1|dim2| byvar|value1|value2|
#+----+----+-------+------+------+
#| 101| 201|MTD0001| 1| 10|
#| 301| 302|MTD0003| 3| 13|
#| 401| 402|MTD0004| 5| 19|
#+----+----+-------+------+------+
filter_str = "dim1 = '101' and dim2 in {0}".format(tuple(value_list))
df.filter(expr(filter_str)).show()
#+----+----+-----+------+------+
#|dim1|dim2|byvar|value1|value2|
#+----+----+-----+------+------+
#+----+----+-----+------+------+
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61915451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Multiple API Resources in one call using laravel I am using API Resources for laravel to transform resource to array for an API call,and its working fine,Is is possible that i can retrieve data of multiple models in one call ? As to get JSON data of users along with Pages JSON ? Or i need a separate call for this.
Here what i have tried so far
//Controller
public function index(Request $request)
{
$users = User::all();
$pages = Page::all();
return new UserCollection($users);
}
//API Resource
public function toArray($request)
{
return [
'name' => $this->name,
'username' => $this->username,
'bitcoin' => $this->bitcoin,
];
}
Any help will be highly appretiated
A: You can do the following:
public function index(Request $request)
{
$users = User::all();
$pages = Page::all();
return [
'users' => new UserCollection($users),
'pages' => new PageCollection($pages),
];
}
A: laravel 6..
This should work 100% if you do like the below, you actually helped me sort out a problem i was having and this is a return on that favour :3.
changes the below:
'advertisements' => new AdvertisementCollection(Advertisement::latest()->get()),
to
(Will work with a vatiable or just the strait db query)
'advertisements' => AdvertisementCollection::collection(Advertisement::latest()->get())
class HomeController extends Controller
{
public function index()
{
$ads = Advertisement::latest()->get();
$banners = Banner::latest()->get();
$sliders = Slider::latest()->get()
return [
'advertisements' => AdvertisementCollection::collection($ads),
'banners' => BannerCollection::collection($banners),
'sliders' => SliderCollection::collection($sliders),
];
}
}
A: I am using laravel 6.x, And i don't know laravel is converting the response or doing something but i am getting the response as JSON in following condition also:
class HomeController extends Controller
{
public function index()
{
return [
'advertisements' => new AdvertisementCollection(Advertisement::latest()->get()),
'banners' => new BannerCollection(Banner::latest()->get()),
'sliders' => new SliderCollection(Slider::latest()->get())
];
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53428303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: woocommerce UPS rates to have USD converted rates from INR on plugin Hi I am using woocommerce to build a ecommerce site and I use UPS shipping to do shipping, the ups I have signed is from India so the returned rates are in Indian Currency. Is there a way to convert the currency from INR to convert to USD and display the price to the customers of my site. Thanks in advance.
A: As per my knowledge if your woocommerce by default currency is dollar then currency always comes in same the currency.Can you please share your site Url then I can check what is the problem?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43983069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Compress files in a directory in a zip file with the shell I want to compress files from the filesystem to a directory within a new zip archive or update an old one. So here is my example:
directory/
|-file1.ext
|-file2.ext
|-file3.ext
in the zip archive it should look like this:
new_directory/
|-file1.ext
|-file2.ext
|-file3.ext
I could copy the files to a new directory and compress them from there but i do not want to have that extra step. I haven't found an answer to that problem on google. The man page doesn't mention anything like that aswell so I hope somebody can help me.
A: I don't think the zip utility supports this sort of transformation. A workaround is to use a symbolic link:
ln -s directory new_directory
zip -r foo.zip new_directory
rm new_directory
If other archive formats are an option for you, then this would be a bit easier with a tar archive, since GNU tar has a --transform option taking a sed command that it applies to the file name before adding the file to the archive.
In that case, you could use (for example)
tar czf foo.tar.gz --transform 's:^directory/:new_directory/:' directory
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28744500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Variable 'c' set but not used [-Wunused-but-set-variable] I have searched and haven't really found and understood this error. It's weird that I only get the error for c, d, e and not for a and b or them all.
Program is about Dooubly Link List.
This happens when I compile with:
gcc -Wall -g -c program.c
Error part:
void try_mymem(int argc, char** argv) {
strategies strat;
void *a, *b, *c, *d, *e;
if (argc > 1)
strat = strategyFromString(argv[1]);
else
strat = First;
/* A simple example.
Each algorithm should produce a different layout. */
initmem(strat, 500);
a = mymalloc(100);
b = mymalloc(100);
c = mymalloc(100);
myfree(b);
d = mymalloc(50);
myfree(a);
e = mymalloc(25);
print_memory();
print_memory_status();
}
What am I doing wrong?
A: They're not used, just like the compiler says. You assign but never read. a and b are used as arguments, the others are not.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64563878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android talkback element type announcement I am trying to make my app more accessible. I am having a hard time finding helpful things because there isn't a lot of documentation (at least I could not find it).
In my app, Talkback does not announce the element type for ImageViews. What I basically want is for Talkback to announce my contentDescription for the ImageView and follow it up with ", Image".
This link states that " Many accessibility services, such as TalkBack and BrailleBack, automatically announce an element's type after announcing its label, so you shouldn't include element types in your labels. For example, "submit" is a good label for a Button object, but "submitButton" isn't a good label." but it does not specify which element types it announces and which it does not.
https://developer.android.com/guide/topics/ui/accessibility/apps.html
*
*Does anyone have any idea if Talkback announces "Image" after the contentDescription for ImageViews?
*When does Talkback announce a link as a "Link"? Or is it the developer's responsibility to add it at the end of the contentDescription? Can I make talkback announce clickable text as a "Link"?
Any help/information/pointers is greatly appreciated. Thanks in advance.
A: A: don't add stuff to the end of the content description. It is an accessibility violation and in almost ALL circumstances just makes things less acessible (will explain more later).
B: A lot of contextual things are communicated to TalkBack users via earcons (bips, beeps, etc), you may just not be noticing.
C: Yes, this is confusing and difficult to determine, no images are not announced, though I think this is for good reason. For example, an image with a click listener may just be a fancy styled button. In iOS there are traits for you to change for this, Android has omitted this highly useful feature, so we're stuck with odd workarounds. The ideal solution would be for the Accessibility APIs to allow the developer to communicate this information.
As for links, typically inline links in text views are announced (basically anything android detects and underlines automatically), but otherwise are not. So, in practice A LOT of links are missed.
Now, as for when you should/should not supply this information yourself. If unsure, just don't and you'll obtain a reasonably high level of accessibility by following the above guidelines. In fact, any of the considerations below are really just fighting the Android OS limitations, and are their problem! However, the Android Accessibility Ecosystem is very weak, and if you want to provide a higher level of accessibility, it is understandable, however, difficult! In your attempts you can actually end up working against yourself. Let me explain:
In Accessibility there is a line between providing information and consistency. By adding contextual information to a content description you are walking along this line. What if Google said "We're not going to share contextual information, add it yourself!".
You would have buttons in music players across different music playing apps that announce in TalkBack like this:
App1: "Play, Button"
App2: "Play, Actionable"
App3: "Play, Clickable"
Do we have consistency here? Now a final example!
App4: "Play, Double Tap to click if you're on TalkBack, Hit enter if you're a keyboard user, use your select key for SwitchAccess users....."
Notice how complicated App4's Play Button is, this is illustrating that the information that TalkBack is using is NOT JUST FOR TALKBACK. The accessibility information from you app is consumed by a multitude of Accessibility services. When you "Hack" contextual information onto a content description, sure it might sound better for a TalkBack user, but what have you done to Braille Back users? To SwitchAccess users? In general, the content description of an element should describe the element, and leave contextual information for TalkBack to calculate/users to figure out given proximity to other controls.
TO ANSWER YOUR TWO PARTICULAR ISSUES (Images and Links):
What I recommend for images is in the content description make it obvious that the thing your describing is an image.
Let's say you have a picture of a kitten.
BAD: A kitten, Image
Good: A picture of a kitten.
See here, if TalkBack fails to announce this as an image (which it will) the user still gets the idea that it is a picture. You have added contextual information to the content description in a way that has ACTUALLY BETTER DESCRIBED THE CONTROL. This is actually the most accessible solution! Go figure.
Links:
For links this gets a bit tricky. There is a great debate in Accessibility about what constitutes a link vs a button. In the web browser world, this is a good debate. However, in native mobile I think we have a very clear definition:
Any button that when activated takes you away from your current Application Context, is a link.
The fact that the Context (Capital C Context!!!) is going to change significantly when a user interacts with a control is EXCEPTIONALLY important information.
TalkBack fails to recognize links A LOT, and as such, for this very important piece of information, if you find that TalkBack is not sharing this information, go ahead and append ", link" to your content description for this element. THIS IS THE ONLY EXCEPTION TO THIS RULE I HAVE FOUND, but believe it is a good exception. Reason being, YES it does add a violation or two for other Assistive Technologies, but it conveys important enough information to justify doing so. YOU CANNOT create a WCAG 2.0 compliant application of reasonable complex User Interface using the Android Accessibility APIs. They have too many limitations, you simply can't do everything you need to do to accomplish this without "hacks". So, we have to make judgement calls sometimes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43188627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to change network in metamask using react js I am developing my first Dapp, I am using metamask and web3 for this. As far now, I am able to get my wallet balance and connect account to metamask. Now I am trying switch between two networks, I am using handleChainChanged, also I am passing chainId and Networkversion but, it is giving me error. I am uncertain about returning anything from changeNetwork function or I only have to pass chainId and Networkversion.
import { useStoreApi } from "./storeApi";
import { useState } from "react";
import useWeb3 from "./useWeb3";
import { Button, TextField } from "@material-ui/core";
import "./App.css";
function App() {
const { balance, address, message, setAddress, setBalance } = useStoreApi();
const web3 = useWeb3();
// get user account on button click
const getUserAccount = async () => {
if (window.ethereum) {
try {
await window.ethereum.enable();
web3.eth.getAccounts().then((accounts) => {
setAddress(accounts[0]);
updateBalance(accounts[0]);
console.log(accounts);
});
} catch (error) {
console.error(error);
}
} else {
alert("Metamask extensions not detected!");
}
web3.eth.getChainId().then(console.log);
};
const updateBalance = async (fromAddress) => {
await web3.eth.getBalance(fromAddress).then((value) => {
setBalance(web3.utils.fromWei(value, "ether"));
});
};
const changeNetwork = async () => {
if (window.ethereum) {
try {
await window.ethereum.enable();
window.ethereum._handleChainChanged({
chainId: 0x1,
networkVersion: 1,
});
} catch (error) {
console.error(error);
}
}
};
return (
<div className="App">
<header className="App-header">
{address ? (
<>
<p> Balance: {balance} </p>
</>
) : null}
<Button
onClick={() => getUserAccount()}
variant="contained"
color="primary"
>
Connect your account
</Button>
<Button onClick={changeNetwork} variant="contained" color="primary">
Switch to mainnet ethereum
</Button>
</header>
</div>
);
}
export default App;
A: You can use wallet_switchEthereumChain method of RPC API of Metamask
Visit: https://docs.metamask.io/guide/rpc-api.html#wallet-switchethereumchain
A: const changeNetwork = async () => {
if (window.ethereum) {
try {
await window.ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: Web3.utils.toHex(chainId) }],
});
});
} catch (error) {
console.error(error);
}
}
changeNetwork()
A: What if the user doesn't have the required network added? Here is an expanded version which tries to switch, otherwise add the network to MetaMask:
const chainId = 137 // Polygon Mainnet
if (window.ethereum.networkVersion !== chainId) {
try {
await window.ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: web3.utils.toHex(chainId) }]
});
} catch (err) {
// This error code indicates that the chain has not been added to MetaMask
if (err.code === 4902) {
await window.ethereum.request({
method: 'wallet_addEthereumChain',
params: [
{
chainName: 'Polygon Mainnet',
chainId: web3.utils.toHex(chainId),
nativeCurrency: { name: 'MATIC', decimals: 18, symbol: 'MATIC' },
rpcUrls: ['https://polygon-rpc.com/']
}
]
});
}
}
}
A: export async function switchToNetwork({
library,
chainId,
}: SwitchNetworkArguments): Promise<null | void> {
if (!library?.provider?.request) {
return
}
const formattedChainId = hexStripZeros(
BigNumber.from(chainId).toHexString(),
)
try {
await library.provider.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: formattedChainId }],
})
} catch (error) {
// 4902 is the error code for attempting to switch to an unrecognized chainId
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if ((error as any).code === 4902) {
const info = CHAIN_INFO[chainId]
await library.provider.request({
method: 'wallet_addEthereumChain',
params: [
{
chainId: formattedChainId,
chainName: info.label,
rpcUrls: [info.addNetworkInfo.rpcUrl],
nativeCurrency: info.addNetworkInfo.nativeCurrency,
blockExplorerUrls: [info.explorer],
},
],
})
// metamask (only known implementer) automatically switches after a network is added
// the second call is done here because that behavior is not a part of the spec and cannot be relied upon in the future
// metamask's behavior when switching to the current network is just to return null (a no-op)
try {
await library.provider.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: formattedChainId }],
})
} catch (error) {
console.debug(
'Added network but could not switch chains',
error,
)
}
} else {
throw error
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67597665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Apply `dplyr::rowwise` in all variables I have a data:
df_1 <- data.frame(
x = replicate(4, runif(30, 20, 100)),
y = sample(1:3, 30, replace = TRUE)
)
The follow function work:
library(tidyverse)
df_1 %>%
select(-y) %>%
rowwise() %>%
mutate(var = sum(c(x.1, x.3)))
But, the follows functions (for all variables) dooesn't work:
with .:
df_1 %>%
select(-y) %>%
rowwise() %>%
mutate(var = sum(.))
with select_if:
df_1 %>%
select(-y) %>%
rowwise() %>%
mutate(var = sum(select_if(., is.numeric)))
The both methods return:
Source: local data frame [30 x 5]
Groups: <by row>
# A tibble: 30 x 5
x.1 x.2 x.3 x.4 var
<dbl> <dbl> <dbl> <dbl> <dbl>
1 32.7 42.7 50.1 20.8 7091.
2 75.9 71.3 83.6 77.6 7091.
3 49.6 28.7 97.0 59.7 7091.
4 47.4 96.1 31.9 79.7 7091.
5 54.2 47.1 81.7 41.6 7091.
6 27.9 58.1 97.4 25.9 7091.
7 61.8 78.3 52.6 67.7 7091.
8 85.4 51.3 38.8 82.0 7091.
9 27.9 72.6 68.9 25.2 7091.
10 87.2 42.1 27.6 73.9 7091.
# ... with 20 more rows
Where 7091 is a incorrect sum.
How adjustment this functions?
A: This can be done using purrr::pmap, which passes a list of arguments to a function that accepts "dots". Since most functions like mean, sd, etc. work with vectors, you need to pair the call with a domain lifter:
df_1 %>% select(-y) %>% mutate( var = pmap(., lift_vd(mean)) )
# x.1 x.2 x.3 x.4 var
# 1 70.12072 62.99024 54.00672 86.81358 68.48282
# 2 49.40462 47.00752 21.99248 78.87789 49.32063
df_1 %>% select(-y) %>% mutate( var = pmap(., lift_vd(sd)) )
# x.1 x.2 x.3 x.4 var
# 1 70.12072 62.99024 54.00672 86.81358 13.88555
# 2 49.40462 47.00752 21.99248 78.87789 23.27958
The function sum accepts dots directly, so you don't need to lift its domain:
df_1 %>% select(-y) %>% mutate( var = pmap(., sum) )
# x.1 x.2 x.3 x.4 var
# 1 70.12072 62.99024 54.00672 86.81358 273.9313
# 2 49.40462 47.00752 21.99248 78.87789 197.2825
Everything conforms to the standard dplyr data processing, so all three can be combined as separate arguments to mutate:
df_1 %>% select(-y) %>%
mutate( v1 = pmap(., lift_vd(mean)),
v2 = pmap(., lift_vd(sd)),
v3 = pmap(., sum) )
# x.1 x.2 x.3 x.4 v1 v2 v3
# 1 70.12072 62.99024 54.00672 86.81358 68.48282 13.88555 273.9313
# 2 49.40462 47.00752 21.99248 78.87789 49.32063 23.27958 197.2825
A: A few approaches I've taken in the past:
*
*use a pre-existing row-wise function (e.g. rowSums)
*using reduce (which doesn't apply to all functions)
*complicated transposing
*custom function with pmap
Using pre-existing row-wise functions
set.seed(1)
df_1 <- data.frame(
x = replicate(4, runif(30, 20, 100)),
y = sample(1:3, 30, replace = TRUE)
)
library(tidyverse)
# rowSums
df_1 %>%
mutate(var = rowSums(select(., -y))) %>%
head()
#> x.1 x.2 x.3 x.4 y var
#> 1 41.24069 58.56641 93.03007 39.17035 3 232.0075
#> 2 49.76991 67.96527 43.48827 24.71475 2 185.9382
#> 3 65.82827 59.48330 56.72526 71.38306 2 253.4199
#> 4 92.65662 34.89741 46.59157 90.10154 1 264.2471
#> 5 36.13455 86.18987 72.06964 82.31317 3 276.7072
#> 6 91.87117 73.47734 40.64134 83.78471 2 289.7746
Using Reduce
df_1 %>%
mutate(var = reduce(select(., -y),`+`)) %>%
head()
#> x.1 x.2 x.3 x.4 y var
#> 1 41.24069 58.56641 93.03007 39.17035 3 232.0075
#> 2 49.76991 67.96527 43.48827 24.71475 2 185.9382
#> 3 65.82827 59.48330 56.72526 71.38306 2 253.4199
#> 4 92.65662 34.89741 46.59157 90.10154 1 264.2471
#> 5 36.13455 86.18987 72.06964 82.31317 3 276.7072
#> 6 91.87117 73.47734 40.64134 83.78471 2 289.7746
ugly transposing and matrix / data.frame conversion
df_1 %>%
mutate(var = select(., -y) %>% as.matrix %>% t %>% as.data.frame %>% map_dbl(var)) %>%
head()
#> x.1 x.2 x.3 x.4 y var
#> 1 41.24069 58.56641 93.03007 39.17035 3 620.95228
#> 2 49.76991 67.96527 43.48827 24.71475 2 318.37221
#> 3 65.82827 59.48330 56.72526 71.38306 2 43.17011
#> 4 92.65662 34.89741 46.59157 90.10154 1 878.50087
#> 5 36.13455 86.18987 72.06964 82.31317 3 520.72241
#> 6 91.87117 73.47734 40.64134 83.78471 2 506.16785
Custom function with pmap
my_var <- function(...){
vec <- c(...)
var(vec)
}
df_1 %>%
mutate(var = select(., -y) %>% pmap(my_var)) %>%
head()
#> x.1 x.2 x.3 x.4 y var
#> 1 41.24069 58.56641 93.03007 39.17035 3 620.9523
#> 2 49.76991 67.96527 43.48827 24.71475 2 318.3722
#> 3 65.82827 59.48330 56.72526 71.38306 2 43.17011
#> 4 92.65662 34.89741 46.59157 90.10154 1 878.5009
#> 5 36.13455 86.18987 72.06964 82.31317 3 520.7224
#> 6 91.87117 73.47734 40.64134 83.78471 2 506.1679
Created on 2019-04-30 by the reprex package (v0.2.1)
A: I think this is tricky because the scoped variants of mutate (mutate_at, mutate_all, mutate_if) are generally aimed at executing a function on a specific column, instead of creating an operation that uses all columns.
The simplest solution I can come up with basically amounts to creating a vector (cols) that is then used to execute the summary operation:
library(dplyr)
library(purrr)
df_1 <- data.frame(
x = replicate(4, runif(30, 20, 100)),
y = sample(1:3, 30, replace = TRUE)
)
# create vector of columns to operate on
cols <- names(df_1)
cols <- cols[map_lgl(df_1, is.numeric)]
cols <- cols[! cols %in% c("y")]
cols
#> [1] "x.1" "x.2" "x.3" "x.4"
df_1 %>%
select(-y) %>%
rowwise() %>%
mutate(
var = sum(!!!map(cols, as.name), na.rm = TRUE)
)
#> Source: local data frame [30 x 5]
#> Groups: <by row>
#>
#> # A tibble: 30 x 5
#> x.1 x.2 x.3 x.4 var
#> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 46.1 28.9 28.9 50.7 155.
#> 2 26.8 68.0 67.1 26.5 188.
#> 3 35.2 63.8 62.5 28.5 190.
#> 4 31.3 44.9 67.3 68.2 212.
#> 5 52.6 23.9 83.2 43.4 203.
#> 6 55.7 92.8 86.3 57.2 292.
#> 7 56.9 50.0 77.6 25.6 210.
#> 8 95.0 82.6 86.1 22.7 286.
#> 9 62.7 26.5 61.0 88.9 239.
#> 10 65.2 23.1 25.5 51.0 165.
#> # … with 20 more rows
Created on 2019-04-30 by the reprex package (v0.2.1)
NOTE: if you are unfamiliar with purrr, you can also use something like lapply, etc.
You can read more about these types of more tricky dplyr operations (!!, !!!, etc.) here:
https://dplyr.tidyverse.org/articles/programming.html
A: This is a tricky problem since dplyr operates column-wise for many operations. I originally used apply from base R to apply over rows, but apply is problematic when handling character and numeric types.
Instead we can use (the aging) plyr and adply to do this simply, since plyr lets us treat a one-row data frame as a vector:
df_1 %>% select(-y) %>% adply(1, function(df) c(v1 = sd(df[1, ])))
Note some functions like var won't work on a one-row data frame so we need to convert to vector using as.numeric.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55922514",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to drill down data in one single click in excel? I have a year progress table, and one of the columns include (+) Sign, what I want is when I click on (+)
the rows from number 8 till 15 will drill down the data (Show Data) and the (+) sign in this case will be (-) Sign and, re click on (-) sign to drill up data (Hide data) and the (-) comes (+) again. I want this formula to be applicable in each row of entire table. Note: The problem with my code is only done for one row but i want for all , so is there any simple eay to make for all rows.
The Table when rows is Hidden
The Table when rows is Appeared
Trying Code
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Not Intersect(Target, Range("O:O")) Is Nothing And Target.Cells.CountLarge = 1 Then
If Range("A8:R15").EntireRow.Hidden = True Then
Range("A8:R15").EntireRow.Hidden = False
Else
Range("A8:R15").EntireRow.Hidden = True
End If
End If
End Sub
Update
Screenshot after using the correct Code
A: I's use the double-click event here: otherwise it's a bit awkward needing to click out of the cell and back again to reverse the hide/unhide.
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim rng As Range
'exit if not in monitored column
If Intersect(Target, Me.Range("O:O")) Is Nothing Then Exit Sub
'check for +/-
If Target.Value = "+" Or Target.Value = "-" Then
Set rng = Target.Offset(1, 0).Resize(8).EntireRow
rng.Hidden = Not rng.Hidden
Target.Value = IIf(rng.Hidden, "+", "-") 'reset cell text
Cancel = True 'don't enter edit mode in the clicked cell
End If
End Sub
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65791940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Loading JSON data into pandas data frame and creating custom columns Here is example JSON im working with.
{
":@computed_region_amqz_jbr4": "587",
":@computed_region_d3gw_znnf": "18",
":@computed_region_nmsq_hqvv": "55",
":@computed_region_r6rf_p9et": "36",
":@computed_region_rayf_jjgk": "295",
"arrests": "1",
"county_code": "44",
"county_code_text": "44",
"county_name": "Mifflin",
"fips_county_code": "087",
"fips_state_code": "42",
"incident_count": "1",
"lat_long": {
"type": "Point",
"coordinates": [
-77.620031,
40.612749
]
}
I have been able to pull out select columns I want except I'm having troubles with "lat_long". So far my code looks like:
# PRINTS OUT SPECIFIED COLUMNS
col_titles = ['county_name', 'incident_count', 'lat_long']
df = df.reindex(columns=col_titles)
However 'lat_long' is added to the data frame as such: {'type': 'Point', 'coordinates': [-75.71107, 4...
I thought once I figured out how properly add the coordinates to the data frame I would then create two seperate columns, one for latitude and one for longitude.
Any help with this matter would be appreciated. Thank you.
A: If I don't misunderstood your requirements then you can try this way with json_normalize. I just added the demo for single json, you can use apply or lambda for multiple datasets.
import pandas as pd
from pandas.io.json import json_normalize
df = {":@computed_region_amqz_jbr4":"587",":@computed_region_d3gw_znnf":"18",":@computed_region_nmsq_hqvv":"55",":@computed_region_r6rf_p9et":"36",":@computed_region_rayf_jjgk":"295","arrests":"1","county_code":"44","county_code_text":"44","county_name":"Mifflin","fips_county_code":"087","fips_state_code":"42","incident_count":"1","lat_long":{"type":"Point","coordinates":[-77.620031,40.612749]}}
df = pd.io.json.json_normalize(df)
df_modified = df[['county_name', 'incident_count', 'lat_long.type']]
df_modified['lat'] = df['lat_long.coordinates'][0][0]
df_modified['lng'] = df['lat_long.coordinates'][0][1]
print(df_modified)
A: Here is how you can do it as well:
df1 = pd.io.json.json_normalize(df)
pd.concat([df1, df1['lat_long.coordinates'].apply(pd.Series) \
.rename(columns={0: 'lat', 1: 'long'})], axis=1) \
.drop(columns=['lat_long.coordinates', 'lat_long.type'])
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54660975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Values not Populating in COMBOBOX even though it is fired the values from MVC I am Very new to EXTJS.
i am adding a new combo to my html page using EXTJS in xxx.js file and fetching the values from MVC controller with sample information.
while debugging the MVC application it is sending the sample information when i send URL: xxxx/getSite from EXTJS.
but it is not showing the values which are fetching from Controller. i am adding the below code which i am using.
Please let me know my mistake.
My Ext JS Code:
var siteidStore = new Ext.data.JsonStore({
reader: new Ext.data.JsonReader({
fields: ['SiteName','SiteId']
}),
root: 'Site',
proxy: new Ext.data.HttpProxy({
url: 'Site/getSite',
method: "POST",
type: 'ajax',
reader: 'json'
}),
autoLoad: true
});
var combo = Ext.create('Ext.form.field.ComboBox', {
queryMode: 'local',
store: siteidStore,
fieldLabel: 'Site ID',
name: 'siteid',
displayField: 'SiteName',
valueField: 'SiteId',
triggerAction: 'all',
typeAhead: false,
forceSelection: true,
emptyText: 'Select Site',
hiddenName: 'SiteId',
selectOnFocus: true
});
MY MVC Appln Code from Controller:
publicActionResult getSite()
{
List<Combo> siteid = newList<Combo>();
siteid.Add(newCombo(1, "IND"));
siteid.Add(newCombo(2, "USA"));
siteid.Add(newCombo(3, "UK"));
return Json(new
{
Site = siteid,
}, JsonRequestBehavior.AllowGet);
}
Output of my C# code or Json:
{"Site":[{"SiteName":"IND","SiteId":1},{"SiteName":"USA","SiteId":2},{"SiteName":"UK","SiteId":3}]}
A: may be you forgot
renderTo : Ext.getBody()
inside combobox...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19086963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JSON to Tuple operation in IBM Streams Is there a way to convert a JSON string to a SPL tuple type without using JSONtoTuple Operator?
I saw this documentation:
https://developer.ibm.com/streamsdev/docs/introducing-the-json-toolkit/
where they have mentioned a native function for converting tuple to json but not json to tuple.
How do I convert a JSON to Tuple inside a Custom operator?
A: version 1.4+ of the JSON toolkit includes functions that you can call from a custom.
This version must be downloaded from Github, as it is not yet included in the Streams product.
Download the latest version from Github, which is 1.4.4.
Build the toolkit: cd com.ibm.streamsx.json and run ant.
Then you can use the extractJSON function:
public T extractFromJSON(rstring jsonString, T value)
Pass the JSON string you want to parse, and a mutable tuple that will contain the parsed result as parameters.
For example:
composite ExtractFromJSON {
type
//the target output type. Nested JSON arrays are not supported.
Nested_t = tuple<rstring name, int32 age, list<rstring> relatives> person, tuple<rstring street, rstring city> address;
graph
() as Test = Custom() {
logic
onProcess : {
rstring jsonString = '{"person" : {"name" : "John", "age" : 42, "relatives" : ["Jane","Mike"]}, "address" : {"street" : "Allen Street", "city" : "New York City"}}';
mutable Nested_t nestedTuple = {};
println( extractFromJSON(jsonString, nestedTuple));
}
}
}
This is based on the ExtractFromJSON sample
that you can find in the repo on Github.
Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48849262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: question about tree i have question for example i want to implement binary tree with array i want understand what will indexes for left child and rigth child ?my array is 0 based i want implement searching in tree using array can anybody help me?
A: left child = parent * 2 + 1
right child = parent * 2 + 2
I imagine this is homework so I will let you figure out the searching algorithm.
A: To implement a binary tree as an array you put the left child for node i at 2*i+1 and the right child at 2*i+2.
So for instance, having 6 nodes here's the indices of the corresponding array
0
|
---------
| |
---1-- --2--
| | | |
3 4 5 6
A: I think you are looking for a heap. Or at least, you use a tree when an array structure is not enough for your needs so you can try to implement a tree inside an array but it wouldn't make much sense since every node contains references to its children without any need of indices.
But an heap is an array that can also be seen as a binary tree, look it out here. It's a tree in the sense that it organizes data as a tree but without having direct references to the children, they can be inferred from the position.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2930744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to Find the number zero in decimal part where add no value to the number and remove that part I am using the following code to convert cm to the meter.
public static double? ConvertCmToM(double? cm)
{
return cm.Value * 0.01;
}
When I input the number 8.8 output giving as
0.08800000000000001m
But I want to stop in the index where zero adds no value in the decimal part. In this case I want to display the value as
0.088m
This is already done in major converter websites. when you type the cm to m converter on google those sites will appear. How do they do it?
I took the same sample and put in their sites and this is how they show.
> 0.088m
I cannot blindly substring the value after converting to a string as the zero part will appear in 5th or 6th element.
That also handled in those sites.
This is a double data type. the letter "m" concat at the last minute. How to acehive this?
A: I would use decimal instead of double then:
public static decimal? ConvertCmToM(decimal? cm)
{
if(cm == null) return null;
return Decimal.Multiply(cm.Value, 0.01m);
}
static void Main()
{
Console.Write(ConvertCmToM(8.8m)); // 0.088
}
decimal vs double! - Which one should I use and when?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75048485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Retrieving all objects in code upfront for performance reasons How do you folks retrieve all objects in code upfront?
I figure you can increase performance if you bundle all the model calls together?
This makes for a bigger deal, especially if your DB cannot keep everything in memory
def hitDBSeperately {
get X users
...code
get Y users... code
get Z users... code
}
Versus:
def hitDBInSingleCall {
get X+Y+Z users
code for X
code for Y...
}
A: Are you looking for an explanation between the approach where you load in all users at once:
# Loads all users into memory simultaneously
@users = User.all
@users.each do |user|
# ...
end
Where you could load them individually for a smaller memory footprint?
@user_ids = User.connection.select_values("SELECT id FROM users")
@user_ids.each do |user_id|
user = User.find(user_id)
# ...
end
The second approach would be slower since it requires N+1 queries for N users, where the first loads them all with 1 query. However, you need to have sufficient memory for creating model instances for each and every User record at the same time. This is not a function of "DB memory", but of application memory.
For any application with a non-trivial number of users, you should use an approach where you load users either individually or in groups. You can do this using:
@user_ids.in_groups_of(10) do |user_ids|
User.find_all_by_id(user_ids).each do |user|
# ...
end
end
By tuning to use an appropriate grouping factor, you can balance between memory usage and performance.
A: Can you give a snipet of actual ruby on rails code, our pseudo code is a little confusing?
You can avoid the n+1 problem by using eager loading. You can accomplish this by using :includes => tag in your model.find method.
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2875861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: System.out.println - Java In Java, why can't we refer to
System.out.println
as just
out.println
...why can't the System call just be implicit since the System library is universal? Perhaps Groovy solved this one.
A: You can if you import static like
import static java.lang.System.out;
then you can do
public static void main(String[] args) {
out.println("Hello, World");
}
A: "Universal", as you're using it, means that you don't need to import System. You still need to qualify references to a field in a different class. What if you (as often happens) want a local field named out?
(And Groovy lets you simply use println.)
A: out.println() would then eliminate out as a valid instance name. By referencing System we know that out is not, for example, File out.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28934641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-7"
}
|
Q: tinyMCE 4.0.5 ObjectResizeStart doesn't work I have latest version of tinyMCE I need to use this function:
http://www.tinymce.com/wiki.php/api4:event.tinymce.Editor.ObjectResizeStart
to prevent image resizing when I'm in read mode because in Chrome images and tables can be rezised even when I'm saying readonly: true.
A: You can disable resizing with
object_resizing : false
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18675781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: OpenCV: Why SIFT and SURF detectors crashes? Why do the SIFT and SURF detectors crash?
using namespace std;
using namespace cv;
int main(int argc, char *argv[])
{
Mat image = imread("TestImage.jpg");
// Create smart pointer for SIFT feature detector.
Ptr<FeatureDetector> featureDetector = FeatureDetector::create("SIFT");
vector<KeyPoint> keypoints;
// Detect the keypoints
featureDetector->detect(image, keypoints); // here crash
// ...
}
The error is Segmentation fault (core dumped). I use OpenCV 2.4.8, gcc 4.9 and Ubuntu. If I use the other types of features it runs normally. What am I missing?
A: Have you tried to call initModule_nonfree()?
#include <opencv2/nonfree/nonfree.hpp>
using namespace std;
using namespace cv;
int main(int argc, char *argv[])
{
initModule_nonfree();
Mat image = imread("TestImage.jpg");
// Create smart pointer for SIFT feature detector.
Ptr<FeatureDetector> featureDetector = FeatureDetector::create("SIFT");
vector<KeyPoint> keypoints;
// Detect the keypoints
featureDetector->detect(image, keypoints); // here crash
// ...
}
Also, you didnt check the pointer featureDetector which is probably null (since you have not called initModule).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23630704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Answer queries about the number of distinct numbers in a given range The problem
I have an array with N numbers. The numbers may be disctints and may also be unordered. I have to answer Q queries about how many distinct numbers there are between A and B. Where A, B are indices between 0 <= A <= B < array.Length.
I know how to do it O(N) per query by using a HashTable but I'm asking for a more efficient solution.
I tried to improve it with sqrt decomposition and also with a segment tree but I couldn't. I'm not showing any code because I did not find any idea that worked.
I'm looking for someone to give an explanation of a faster solution.
UPDATE
I read you can collect the queries and then answer them all by using a Binary Indexed Tree (BIT). Can someone explain how to do it. Assume I know how a BIT works.
A: For each index i find the previous index prev[i] that has the same value (or -1 if there's no such index). It may be done in O(n) average by going left to right with hash_map, then the answer for range [l;r) of indices is number of elements i in range [l;r) such that their value is less then l (it require some thinking but should be clear)
Now we will solve problem "given range [l;r) and value c find number of elements that are less then c" on array prev. It may be done in O(log^2) using segment tree, if we save in each vertex all the numbers that are in its range(subtree). (On each query we will get O(log n) vertices and do binary search in them)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48134696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is JSF 2.0 View Scope back-button safe? Is the JSF 2.0 View Scope "back button" safe? e.g. if I store a model in View Scope and go from page 1, page 2, page 3, to page 4, modifying the model object along the way (via input fields), and then hit the back button twice to go back to page 2 and make changes (taking me again to page 3), will the model in view scope have only changes that were made when page 2 was originally rendered or will it have later pages' changes?
Oracle ADF had/has something called "process scope" that handles this by tokenizing what is placed into session, so each page has its own copy of the model.
A: To start, the view scope is bound to a particular page/view. Multiple views won't share the same view scoped bean. The view scope starts with an initial GET request and stops when a POST action navigates with a non-null return value.
There are in general the following scenarios, depending on whether the browser is instructed to cache the page or not and the JSF state saving configuration. I'll assume that the navigation between those pages took place by a POST request (as it sounds much like the "Wizard" scenario).
When the back button is pressed:
*
*If browser is instructed to save the page in cache, then browser will load the page from the cache. All previously entered input values will reappear from the browser cache (thus not from the view scoped bean in the server side!). The behavior when you perform a POST request on this page depends further on the javax.faces.STATE_SAVING_METHOD configuration setting:
*
*If set to server (default), then a ViewExpiredException will occur, because the view state is trashed at the server side right after POST navigation from one to other page.
*If set to client, then it will just work, because the entire view state is contained in a hidden input field of the form.
*Or, if browser is instructed to not save the page in cache, then browser will display a browser-default "Page expired" error page. Only when the POST-redirect-GET pattern was applied for navigation, then the browser will send a brand new GET request on the same URL as the redirect URL. All previously entered input values will by default get cleared out (because the view scoped bean is recreated), but if the browser has "autocomplete" turned on (configureable at browser level), then it will possibly autofill the inputs. This is disableable by adding autocomplete="off" attribute to the input components. When you perform a POST request on this page, it will just work regardless of the JSF state saving method.
It's easier to perform the "Wizard" scenario on a single view which contains conditionally rendered steps and offer a back button on the wizard section itself.
See also:
*
*javax.faces.application.ViewExpiredException: View could not be restored
*What scope to use in JSF 2.0 for Wizard pattern?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9930900",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Extract jsonb in Postgresql - dictionary and array structure in same jsonb field I am using postgresql and I have this table on dataset, that some columns are jsonb.
SELECT
external_id as cod,
title as name,
objectives
FROM table
So, the result for "objectives" column is like that:
{"blocks":
[
{"key":"dek2k",
"text":"Objetivo Geral",
"type":"unstyled",
"depth":0,
"inlineStyleRanges":
[
{"offset":0,"length":14,"style":"fontsize-12pt"},
{"offset":0,"length":14,"style":"fontfamily-Arial"},
{"offset":0,"length":14,"style":"fontsize-14"}
],
"entityRanges":[],
"data":{"text-align":"start"}},
{"key":"ct1vn",
"text":"Conhecer e aplicar ferramentas para análise da mídias em sua respectiva relação com a cognição e o design,",
"type":"unstyled","depth":0,"inlineStyleRanges":
[
{"offset":0,"length":216,"style":"color-rgb(0,0,0)"},
{"offset":0,"length":216,"style":"fontsize-12pt"},
{"offset":0,"length":216,"style":"fontfamily-Arial"},
{"offset":0,"length":216,"style":"fontsize-14"}
],
"entityRanges":[],
"data":{}},
{"key":"8jshq",
"text":"","type":"unstyled","depth":0,
"inlineStyleRanges":[],
"entityRanges":[],"data":{}},
{"key":"avq4h",
"text":"tendo como ênfase os estudos das materialidades dos meios de comunicaçõe e seus aspectos sensoriais.",
"type":"unstyled",
"depth":0,
"inlineStyleRanges":
[
{"offset":0,"length":23,"style":"color-rgb(0,0,0)"},
{"offset":0,"length":23,"style":"fontsize-12pt"},
{"offset":0,"length":23,"style":"fontfamily-Arial"},
{"offset":0,"length":23,"style":"fontsize-14"}
],
"entityRanges":[],
"data":{}}
],
"entityMap":{}
}
I want to get in result only what is in "text". Sometimes it has just one "text" value, sometimes it has up to 15 or more.
What i need is a result like this for all rows in table:
cod | name | objectives
----------+-----------------+----------
1 | A | Objetivo Geral Conhecer e aplicar ferramentas para análise da mídias em sua respectiva relação com a cognição e o design, tendo como ênfase os estudos das materialidades dos meios de comunicaçõe e seus aspectos sensoriais.
Any clue?
A: The json functions with string_agg() achieve what you want.
Using WITH ORDINALITY guarantees correct ordering of the text elements.
SELECT t.external_id as cod,
t.title as name,
string_agg(a.block->>'text', ' ' ORDER BY rn) as objectives
FROM "table" t
CROSS JOIN LATERAL jsonb_array_elements(t.objectives->'blocks')
WITH ORDINALITY as a(block, rn)
GROUP BY t.external_id, t.title;
|
{
"language": "pt",
"url": "https://stackoverflow.com/questions/63140622",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to display template parameter type name in natvis? I want to extend a natvis visualizer for a (C++) template class. Is there a way to display a type name of the first template parameter?
It would be great for boost::variant<int,bool> v; v=1; to display 1 (int) or something like that
A: In my opinion the best solution is to use the standard C++17 std::variant. MSVC comes with natvis for this type so that you have a pretty view of the value that is stored.
Here is some natvis code that I just wrote and tested:
<Type Name="boost::variant<*>">
<DisplayString Condition="which_==0">{*($T1*)storage_.data_.buf}</DisplayString>
<DisplayString Condition="which_==1" Optional="true">{*($T2*)storage_.data_.buf}</DisplayString>
<DisplayString Condition="which_==2" Optional="true">{*($T3*)storage_.data_.buf}</DisplayString>
<DisplayString Condition="which_==3" Optional="true">{*($T4*)storage_.data_.buf}</DisplayString>
<DisplayString Condition="which_==4" Optional="true">{*($T5*)storage_.data_.buf}</DisplayString>
<DisplayString Condition="which_==5" Optional="true">{*($T6*)storage_.data_.buf}</DisplayString>
<DisplayString Condition="which_==6" Optional="true">{*($T7*)storage_.data_.buf}</DisplayString>
<Expand>
<Item Name="which">which_</Item>
<Item Name="value0" Condition="which_==0">*($T1*)storage_.data_.buf</Item>
<Item Name="value1" Condition="which_==1" Optional="true">*($T2*)storage_.data_.buf</Item>
<Item Name="value2" Condition="which_==2" Optional="true">*($T3*)storage_.data_.buf</Item>
<Item Name="value3" Condition="which_==3" Optional="true">*($T4*)storage_.data_.buf</Item>
<Item Name="value4" Condition="which_==4" Optional="true">*($T5*)storage_.data_.buf</Item>
<Item Name="value5" Condition="which_==5" Optional="true">*($T6*)storage_.data_.buf</Item>
<Item Name="value6" Condition="which_==6" Optional="true">*($T7*)storage_.data_.buf</Item>
</Expand>
</Type>
It works for any boost::variant<type_or_types>.
It has a DisplayString that takes the variant's member storage_ and extracts the buffer buf. The address of the buffer is then cast to a pointer to the type that was provided to std::variant. As you can see in my code which_ is zero based, whereas the template parameters are 1 based. I am not interested in the address but in the value, so I am adding a * in front of the value.
I also added an Expand section so that you can expand a variant. This allows me to show which_ and to show the value again - this time the column Type will show the correct type as you can see in my screen capture (for the variant itself the type is displayed as boost::variant<…> and I do not know how to add the type name into the DisplayString).
Please note that the Optional="true" are required because otherwise we would get a parsing error in cases where less than 7 type parameters are passed (as in boost::variant<int,bool>and natvis does not have a $T7.
If you need more template parameters, you can easily extend the code.
If you want the DisplayString to also shows the index (as an explicit value or coded into the name value…), you can easily change it accordingly as in
<DisplayString Condition="which_==0">{{which={which_} value0={*($T1*)storage_.data_.buf}}}</DisplayString>
Last but not least please note that I did not test very much and that I did not look into boost::variant into detail. I saw that storage_ has members suggesting that there is some alignment in place. So it might not be sufficient to just use storage_.data_.buf. It might be necessary to adjust the pointer depending on the alignment being used.
A: If you want to show $T1 as a string, wrap it with ". For example, for
<DisplayString>{*($T1*)storage_.data_.buf} {"$T1"}</DisplayString>
in your case you will see 1 "int"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54458842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: What should I use in ANSI C to create linked lists? In Java I used LinkedList<T>.
Is there any standard, or maybe some other libraries, to create LinkedLists in C?
A: No, C doesn't have anything like that. If you can use C++, there's std::list.
You'll have to write the structure yourself in C.
A: As others have said, there is no standard library support for linked lists in C. That means you either get to roll your own (like most people have done at one or more times in their C coding career), or you look at other libraries for support.
For most uses, you will find that an 'intrusive' implementation is appropriate. You modify your existing structure to include a pointer to the next item in the list (and, if you're doing a doubly linked list, the previous item).
typedef struct TheStruct TheStruct;
struct TheStruct
{
...the real data...
TheStruct *next;
//TheStruct *prev;
};
Your list now consists of a simple pointer to the head item:
TheStruct *head = 0;
TheStruct *allocated_node = new_TheStruct(value1, value2, ...);
assert(allocated_node->next == 0);
// Insert new allocated node at head of list
allocated_node->next;
head = allocated_node;
You have to worry about threading issues if you've got threads access the same list, and so on and so forth.
Because this code is so simple, this is how it is most frequently handled. Deleting a node from a list is trickier, but you can write a function to do it.
People have dressed up this basic scheme with macros of varying degrees of complexity so that the code manipulating different types of lists can use the same macros. The Linux kernel uses a macro-based set of linked lists for managing its linked list data structures.
The alternative to the 'intrusive' implementation (which is so-called because it requires a change to the structure to include the list pointers) is to have some generic list mechanism:
typedef struct GenericList GenericList;
struct GenericList
{
void *data;
GenericList *next;
//GenericList *prev;
};
Now you have the ability to put (pointers to) unmodified structures into the list. You lose some type safety; there is nothing to stop you adding random different structure types to a list that should be homogeneous. You also have to allocate memory for the GenericList structures separately from the pointed at data.
*
*One advantage of this is that a single data item can be on multiple separate lists simultaneously. * One disadvantage of this is that a single data item can accidentally be on multiple lists, or multiple times in a single list, simultaneously.
You also have to make sure you understand the ownership properties for the data, so that the data is released properly (not leaked, not multiply-freed, not accessed after being freed). Managing the memory for the list itself is child's play by comparison.
With the GenericList mechanism, you will likely have a library of functions that manage the list operations for you. Again, searching should reveal implementations of such lists.
A: C does not (as yet) provide any standard container structures. You'll have to roll your own.
A: It doesn't exist by default, but it can be made quite easily.
Basically a linked list is a header pointer that points to 1st element, and an ending file pointing to null.
The elements are actually nodes, containing the object and a pointer to the next node.
So making a basic one is quite easy, though in C it might be painful as no classes, only structs.
A: There are no Lists in the standard C library. A very good C library you can use is PBL - The Program Base Library here. Its interface is Java like. You can download it from here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9555788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Domino Rest service API to get Tentative status in Ateendee's calendar Is there any way to find the Tentative status of my meetings as an Attendee from the response of "GET /{db}/api/calendar/events" or "GET /{db}/api/calendar/events/meetingId" ?
Some documents say x-lotus-noticetype property with "P" indicates a tentative acceptance. But I am getting a status "A" instead, after tentative accept meeting in both 8.5.3 and 9.0.1 versions of domino.
Use case: To show my(Attendee's) tentatively accepted meetings in Yellow color , in my Web App's calendar.
A: You should look at the JSON transparency property. When an attendee tentatively accepts a meeting, the property will look like this:
"transparency": "transparent"
On the other hand, when an attendee accepts a meeting, the property will look like this:
"transparency": "opaque"
In other words, a transparent event doesn't block busy time; an opaque event does block busy time. This terminology comes from the iCalendar specification. See the TRANSP property in iCalendar.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33406419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Exchange Information between two windows Im not sure how to explain my problem in short at the title, so forgive me for this. Lets say I opened my website in some random page, and I have a register button. Really simple, but in my case I require the registration form to appear in other tab(or window). Not "RederPartial", nor popup window of some kind, legit new tab. The problem is, I want to be able do detect, from that random page of mine, when the registration completed (ie a new user has been created). How can I pass this information? without reloading the first page
A: There are various ways to make two windows talk with each other (through server, with cookies, using FileSystem API or Local Storage.
Locale Storage is by far the easiest way to talk between two windows who come from the same domain, but it is not supported in older browsers. Since you need to contact the server anyway to find out when someone has registered, I recommend using the server (Ajax//web sockets).
Here's a somewhat simple AJAX solution which you could use in your random page:
(function(){
var formOpened = false;
var registered = false;
//Change to whatever interaction is needed to open the form
$('#registerbutton').on('click', function(){
if (!formOpened){
formOpened = true;
//Will try to poll the server every 3 seconds
(function pollServer(){
$.ajax({
url: "/ajax/pollregistered",
type: "GET",
success: function(data) {
if (data.registered){
registered = true;
//do other stuff here that is needed after registration
}
},
dataType: "json",
complete: setTimeout(function() {if (!registered) pollServer();}, 3000),
//will timeout if request takes longer than 2 seconds
timeout: 2000,
})
})();
//opens the new tab
var win = window.open('/registrationform', '_blank');
win.focus();
}
});
})();
You can then use the session key of the visitor in the '/ajax/pollregistered' action to write your backend code to check if and when this visitor registered as user to your site.
If you don't mind using the local storage, you could poll the storage instead of the server and have the registration page write to local storage upon registration. This is less stressing for your server, but might not work for users with ancient browsers.
Also worth nothing that this method of opening a new tab is not completely reliable. Technically there is not a sure shot way of opening a new tab with javascript. It depends on browser and the preferences of the user. Opening a new tab might get blocked for users who are using anti popup plugins.
That being said, I strongly recommend revising your design and try finding a way to work with just one window instead. It's probably better for both yourself and your users.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38347859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Adjust border to content I have a simple grid with 2 columns with border and two columns Fiddle
The problem is I want to adjust the border to the content and the content has left padding, so I want to remove that free space.
I tried to use box-sizing: border-box; but it causes no effect
HTML:
<div class="totalContainer totalContainer__space" *ngIf="selectedMenuItem === menu[3]">
<div class="totalContainer__text">
<label><strong>Annual</strong> Test Test </label>
</div>
<div class="totalContainer__text totalContainer__result">
<label><strong>80</strong></label>
</div>
</div>
SCSS:
.totalContainer {
display: grid;
grid-template-columns: 2fr 1fr;
margin-top: 30px;
border: 1px solid rgba(72, 82, 93, 0.8);
border-radius: 12px;
box-sizing: border-box;
&__row {
background-color: #E5E5E5;
}
&__space {
padding: 10px 0 10px 140px;
}
&__text {
font-size: 13px;
}
&__result {
text-align: right;
}
}
A: Using margin-left instead of padding:
&__space {
padding: 10px 0 10px 10px;
margin-left: 140px;
}
A: I think you are missing the big picture here.
Making up a block box in CSS we have the:
Content box: The area where your content is displayed, which can be
sized using properties like width and height. Padding box: The padding
sits around the content as white space; its size can be controlled
using padding and related properties.
Border box: The border box wraps
the content and any padding. Its size and style can be controlled
using border and related properties.
Margin box: The margin is the
outermost layer, wrapping the content, padding, and border as
whitespace between this box and other elements. Its size can be
controlled using margin and related properties.
So in short the border includes the padding (it wraps the content as well as the padding), while the margin lays outside of it (pushing the content with border and padding included). I would recomand to check the box model docs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69666975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: middleman Invalid byte sequence in UTF-8 I want to edit a webpage for someone who is using middleman. Anytime I run middleman in the console I get this error:
Traceback (most recent call last):
68: from /Users/apple/.rvm/gems/ruby-2.6.0/bin/ruby_executable_hooks:24:in `<main>'
67: from /Users/apple/.rvm/gems/ruby-2.6.0/bin/ruby_executable_hooks:24:in `eval'
66: from /Users/apple/.rvm/gems/ruby-2.6.0/bin/middleman:23:in `<main>'
65: from /Users/apple/.rvm/gems/ruby-2.6.0/bin/middleman:23:in `load'
64: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-cli-4.3.3/bin/middleman:49:in `<top (required)>'
63: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-cli-4.3.3/bin/middleman:49:in `new'
62: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/application.rb:283:in `initialize'
61: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/callback_manager.rb:28:in `block in install_methods!'
60: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
59: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
58: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
57: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/callback_manager.rb:57:in `execute'
56: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/hamster-3.0.0/lib/hamster/vector.rb:431:in `each'
55: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/hamster-3.0.0/lib/hamster/vector.rb:1316:in `traverse_depth_first'
54: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/hamster-3.0.0/lib/hamster/vector.rb:1316:in `each'
53: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/callback_manager.rb:57:in `block in execute'
52: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/callback_manager.rb:57:in `instance_exec'
51: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
50: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
49: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
48: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/core_extensions/file_watcher.rb:47:in `before_configuration'
47: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
46: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
45: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
44: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/sources.rb:241:in `poll_once!'
43: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/sources.rb:241:in `reduce'
42: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/sources.rb:241:in `each'
41: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/sources.rb:241:in `block in poll_once!'
40: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
39: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
38: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
37: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/sources/source_watcher.rb:212:in `poll_once!'
36: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
35: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
34: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
33: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/sources/source_watcher.rb:288:in `update'
32: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/callback_manager.rb:28:in `block in install_methods!'
31: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
30: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
29: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
28: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/callback_manager.rb:57:in `execute'
27: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/hamster-3.0.0/lib/hamster/vector.rb:431:in `each'
26: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/hamster-3.0.0/lib/hamster/vector.rb:1316:in `traverse_depth_first'
25: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/hamster-3.0.0/lib/hamster/vector.rb:1316:in `each'
24: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/callback_manager.rb:57:in `block in execute'
23: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/callback_manager.rb:57:in `instance_exec'
22: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
21: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
20: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
19: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/sources.rb:351:in `did_change'
18: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
17: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
16: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
15: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/sources.rb:361:in `run_callbacks'
14: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/hamster-3.0.0/lib/hamster/vector.rb:431:in `each'
13: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/hamster-3.0.0/lib/hamster/vector.rb:1316:in `traverse_depth_first'
12: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/hamster-3.0.0/lib/hamster/vector.rb:1316:in `each'
11: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/sources.rb:368:in `block in run_callbacks'
10: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
9: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
8: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
7: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/core_extensions/data.rb:89:in `update_files'
6: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/core_extensions/data.rb:89:in `each'
5: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
4: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
3: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
2: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/core_extensions/data.rb:108:in `touch_file'
1: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/util/data.rb:60:in `parse'
/Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/util/data.rb:60:in `match': invalid byte sequence in UTF-8 (ArgumentError)
Is there a way to find out what is causing this error? I didn't build this website, I just cloned the repository but I don't know where to start.
I've looked this up earlier and found people with a similar problem that said that it had something to do with the font files. Even when I removed those I still have this error. If anyone could help me out I would appreciate it. Thanks in advance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54962740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Create Shape drawable with stroke color, corner and solid drawable I Want to create a shape: solid is a Bitmap (repeat tiles), and stroke is a color. I use LayerList:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/additional_image"
android:drawable="@drawable/bg_detail_loop"
>
</item>
<item android:id="@+id/rounded_corners"
android:drawable="@drawable/shape_box_dlg">
</item>
</layer-list>
File bg_detail_loop.xml:
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:filter="true"
android:gravity="center"
android:tileMode="repeat"
android:src="@drawable/tile_detail"
/>
File shape_box_dlg.xml:
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<stroke
android:width="2dip"
android:color="#EE6A1F" />
<gradient android:angle="270" />
<corners android:radius="6dp" />
</shape>
But, in the corner, the background Bitmap not clip. I want rounded the corner. Anyone help me? Thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14475018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: zshell passing argument to function I put this in my zshrc:
function picofl() {
openocd -f interface/picoprobe.cfg -f target/rp2040.cfg -c 'program "$1" reset exit'
}
Then I run: picofl myblink.elf but it errors with unexpected argument. What am I doing wrong?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74444217",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Custom Sinatra route I'm looking to make a custom route for my Sinatra blog project which shows the user the last entered post in the database.
get "/most-recent-job" do
Job.last
Can anyone help? I can't find info in my curriculum for such a request.
A: The Sinatra documentation on routes is pretty thorough. Assuming you're just trying to call a class method of Jobs::last, and that the method returns something stringifyable, then:
get '/most-recent-job' do
Jobs.last
end
should get it done. If that's insufficient for your use case, you'll have to expand your question to include code and output showing what Jobs.last is supposed to return, whatever errors you're getting from the route currently, and what you think the route's output ought to look like if you're expecting a MIME type other than text/plain.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62027704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: Layers in Hexagonal Architecture I'm reading a lot about hexagonal architecture, but in all the examples that i'm looking, all folders and class ubication are different, and this looks a bit confusing to me.
I've done a simple spring boot application with below folder structure. Adapter folder contains implementation of repository interface and the rest controller.
In domain folder, I've model, which is a simple POJO, ports, that are interfaces of service class which contains all the business logic of Product, and the interface of repository which exposes the methods to be implemented in repository.
In another folder I've service implementation, and as i told before, with the business logic of product.
Is this a correct way to implement an hexagonal architecture for a simple use case? If not, why? Where i should put every class and why? This is what it's not clear...
Much appreciate!
A: You are totally free to organise your code however you wish. This is unrelated to hexagonal architecture.
With that being said, if you want to use hexagonal architecture efficiently, you should probably follow a domain-driven design, that is to say, you should organise your code based on domain/business logic, and not based on technical similarities.
For example, instead of having the following structure:
controller
product
cart
customer
service
product
cart
customer
repository
product
cart
customer
DDD recommends the following structure:
product
controller
service
repository
cart
controller
service
repository
customer
controller
service
repository
Once you've done this, if it helps, you could wrap these in three packages for the differents parts of the hexagonal architecture: user side, business logic and server side. This is something I've done in the past; it helps me keep the different layers clear.
userside
product
controller
cart
controller
customer
controller
businesslogic
product
service
cart
service
customer
service
serverside
product
service
cart
repository
customer
repository
Again, the structure of your packages is not the most important concept. The hexagonal architecture focuses on three principles:
*
*Explicitly separate user side, business logic, and server side layers. A clear package structure helps, but you can separate these layers in other ways.
*Dependencies go from user side and server side layers to the business logic. This is done by defining interfaces and adapters in the business logic (see below). The goal is that code in the user side and server side may be changed without impacting the business logic layer. For example, if you wish to change your repository from a MySQL implementation to a PostgreSQL implementation (in the server side layer), this change should not impact your business logic: the new implementation need only comply with the interface in the business logic.
*Dependency injection: the business logic defines interfaces (commonly called "ports") and transformers ("adapters") with which the user side and server side layers must comply for communication.
It's a very DDD oriented architecture; the idea is that the business logic remain as close to the domain as possible, and unadulterated by technical requirements.
A: Hexagonal architecture doesn't say snything about how to organize the hexagon code (business logic). You can implement however you want to.
Take a look at these articles:
https://jmgarridopaz.github.io/content/articles.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66971751",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Tensorflow input pipeline for distributed training I am trying to figure out how to setup my input pipeline for tensorflow in distributed training. It's not clear whether the readers will read from a single process and send the data to all workers or each server will start it's own input pipeline? How do we ensure that every worker has a different input going to it?
A: I will give an example of how I do it:
import tensorflow as tf
batch_size = 50
task_index = 2
num_workers = 10
input_pattern = "gs://backet/dir/part-00*"
get all names of files in the bucket that correspond to input_pattern
files_names = tf.train.match_filenames_once(
input_pattern, name = "myFiles")
select names for worker task_index. tf.strided_slice is like slice for lists: a[::,task_index] (select every task_indexth file for worker task_index)
to_process = tf.strided_slice(files_names, [task_index],
[999999999], strides=[num_workers])
filename_queue = tf.train.string_input_producer(to_process,
shuffle=True, #shufle files
num_epochs=num_epochs)
reader = tf.TextLineReader()
_ , value = reader.read(filename_queue)
col1,col2 = tf.decode_csv(value,
record_defaults=[[1],[1]], field_delim="\t")
train_inputs, train_labels = tf.train.shuffle_batch([col1,[col2]],
batch_size=batch_size,
capacity=50*batch_size,
num_threads=10,
min_after_dequeue = 10*batch_size,
allow_smaller_final_batch = True)
loss = f(...,train_inputs, train_labels)
optimizer = ...
with tf.train.MonitoredTrainingSession(...) as mon_sess:
coord = tf.train.Coordinator()
with coord.stop_on_exception():
_ = tf.train.start_queue_runners(sess = mon_sess, coord=coord)
while not coord.should_stop() and not mon_sess.should_stop():
optimizer.run()
I'm not sure my method is the best way to implement input pipeline in case of distributed TensorFlow implementation because each worker reads names of all files in the bucket
Good lecture about input pipeline in TensorFlow: http://web.stanford.edu/class/cs20si/lectures/notes_09.pdf
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45287431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Django Design Pattern - request.user in Model I run into this pattern all the time and I'm wondering if there's a better way to handle it. Lots of my models contemplate the idea of 'creator' - in other words, I want to make sure the user who created the object is saved as the creator. As such, my models almost always include
creator = models.ForeignKey(User)
There doesn't seem to be a way of defaulting this user to the user who created it (request.user). As such I find myself building model forms and adding creator as a HiddenInput()
class MyModelForm(ModelForm):
class Meta:
model = MyModelForm
fields = ['name', 'creator']
widgets = {
'creator': HiddenInput()
}
and then binding the form in the view with initial
form = MyModelForm(initial={'creator': request.user})
and checking on POST to make sure no one dickered with the form (full view):
def create(request):
form = MyModelForm(initial={'creator': request.user})
if request.method == 'POST':
if int(request.POST['creator']) != int(request.user.id):
return render(request,'500.html', {'message':'form tampering detected'})
form = FeedGroupForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('index'))
return render(request, 'mymodelformpage.html',{'form':form})
I'm fine with this but it seems like an anti-pattern. It strikes me that there ought to be a way to default the creator in the model.
creator = models.ForeignKey(User, default=request.user)
Or do it in a post_save perhaps?
A: No, this is not the right way. The correct way is to exclude the creator field from the form, then set it on save:
if form.is_valid:
obj = form.save(commit=False)
obj.creator = request.user
obj.save()
... redirect ...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21078229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Running Android Studio Volley in different API levels The app I made ran on different API levels but the volley library only works API level 26.
I was puzzled when I can't login in the app using my phone (android 9) but a later model works just fine. I found out that I can only login in Android 8 phones (API level 26). I tested multiple virtual devices with different API levels and API level 26 let's me login and the rest just doesn't work. I was wondering how can I make volley library work on API level 26 and higher.
Edit: It was a big mistake for me but I now enabled the log for errors and I found these.
(Using http://)
(Using https://)
plugins {
id 'com.android.application'
}
android {
compileSdk 31
defaultConfig {
applicationId "com.example.studentplanner"
minSdk 26
targetSdk 31
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
buildFeatures {
viewBinding true
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
namespace 'com.example.studentplanner'
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.4.2'
implementation 'com.google.android.material:material:1.6.1'
implementation 'com.github.xabaras:RecyclerViewSwipeDecorator:1.3'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'com.android.volley:volley:1.2.1'
implementation 'com.google.code.gson:gson:2.9.1'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.recyclerview:recyclerview:1.1.0-alpha04'
implementation 'com.google.android.material:material:1.1.0'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
A: Add this line in your application tag
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application
...
android:usesCleartextTraffic="true"
...>
...
</application>
</manifest>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75052379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WooCommerce product categories are not displayed properly in menu I got this strange behavior in Wordpress, I have about 90 product categories/subcategories.
All the related functions are working fine, except when I go to Appearance -> Menu and try to add product categories to my menu.
The thing is that only two pages of product categories are viewed with many missing categories.
please see the attached screenshot.
I am using Woocommerce v3.3.4
Server info:
A: Go to the ‘Tools’ tab inside the WooCommerce > System Status of your WordPress administration panel. Here you first use the ‘Recount terms’ button and after that use the ‘Clear transients’ button. This will force the system to recount all the products the next time a category is loaded.
A: File Manager >> public_html >> wp-admin >> includes >> nav-menu.php
search for paginate there is two it will be the one in line 692 (it was for me).
// Paginate browsing for large numbers of objects.
$per_page = 50;
Change 50 to your needs
Also add to child theme functions.php
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49581230",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: EJS not rendering on placing image url I am trying to add image using EJS, the page on the browser doesn't render as I want.
Here is the image of the browser
ejs code for this rendering page is
<% layout('layout/boilerplate') -%>
<% for (let camps of allCamps){%>
<div class="card mb-3">
<div class="row">
<div class="col-md-4">
<img class="img-fluid" src="<%= camps.image[0].url %>">
</div>
<div class="col-md-8">
<div class="card-body">
<h5 class="card-title "><%= camps.title %> </h5>
<p class="card-text"><%= camps.description %></p>
<p class="card-text">
<small class="text-muted"><%= camps.location%></small>
</p>
<a class="btn btn-primary" href="/campgrounds/<%=camps._id%>">View <%=camps.title%></a>
</div>
</div>
</div>
</div>
<% }%>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74179545",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Add SSH Connection with pem key to Apache Airflow connection Is there a way to add an ssh connection to Apache Airflow from the UI either via connections or vairables tab that allow connection using a pem key and not a username and password.
A: DISCLAIMER: Following answer is purely speculative
*
*I think key_file param of SSHHook is meant for this purpose
*And the idiomatic way to supply it is to pass it's name via extra args in Airflow Connection entry (web UI)
*
*Of course when neither key_file nor credentials are provided, then SSHHook falls back to identityfile to initialize paramiko client.
*Also have a look how SFTPHook is handling this
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54885695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Facing problem with material mat-select dropdown position issue Facing problem with material mat-select dropdown position issue. Dropdown position is keep on changing on select of item. How to keep position as fixed. Can you someone support please.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71353232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Issue while using webservice to call some java application method which is using resource file Issue while using webservice to call some java application method which is using resource file
I have created one java application which contains following directory structure in my src folder of java..
Src/
Transcriber.java
config.xml
digits.gram
transcriber.manifest
I have successfully created web-service of this java application with .aar file and putting into axis2 service folder
I am packaging this whole in Transcriber.aar file with the following structure
Transcriber\edu\cmu\sphinx\demo\transcriber
and in that all 4 file above I listed.
I have two method in above Transcriber.java class.. 1st method is just processing without any of other file use like (e.g. config.xml,digits.gram and transcriber.manifest). and its working fine and I can call easily that method from android.
but my second method uses the other files also(e.g. config.xml,digits.gram and transcriber.manifest) to process some logic I want.
But some how I'm getting error when I call the second method and its give me error while I'm calling this 2nd method from android device .
My Error is as follows:
at java.lang.Thread.run(Thread.java:662)
Caused by: Property exception component:'jsgfGrammar' property:'grammarLocation'
- Can't locate resource:/edu/cmu/sphinx/demo/transcriber
edu.cmu.sphinx.util.props.InternalConfigurationException: Can't locate resource:
/edu/cmu/sphinx/demo/transcriber
its give me error that some how it cant locate the grammar file digits.gram which is i use to add via the config.xml file with this code in config.xml
<component name="jsgfGrammar" type="edu.cmu.sphinx.jsgf.JSGFGrammar">
<property name="dictionary" value="dictionary"/>
<property name="grammarLocation"
value="resource:/edu/cmu/sphinx/demo/transcriber"/>
<property name="grammarName" value="digits"/>
<property name="logMath" value="logMath"/>
</component>
Why I'm Having this kind of error?enter code here
My CODE WHERE I HAVE FIRST GET THE CONFIG.XML AND THEN CONFIG.XML GET ANOTHER RESOURCE FILE....its successfully finds the config.xml but then the code in config.xml cant locate other resource file
package edu.cmu.sphinx.demo.transcriber;
import edu.cmu.sphinx.frontend.util.AudioFileDataSource;
import edu.cmu.sphinx.recognizer.Recognizer;
import edu.cmu.sphinx.result.Result;
import edu.cmu.sphinx.util.props.ConfigurationManager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
/** A simple example that shows how to transcribe a continuous audio file that has multiple utterances in it. */
public class TranscribeSimpleGrammar {
private static final String PATH = "file:///D:\\Sound\\";
@SuppressWarnings({ "null", "null" })
public String recognize_wave(String wavePath) throws MalformedURLException{
URL audioURL;
// if (args.length > 0) {
// audioURL = new File(args[0]).toURI().toURL();
// } else {
//audioURL = TranscribeSimpleGrammar.class.getResource("hello.wav");
//audioURL = new URL(PATH + "turn-on-light-kitchen-male.wav");
//audioURL = new URL(PATH + "turn-down-tv-volume-female.wav");
// audioURL = new URL(PATH + wavePath);
audioURL = new URL(wavePath);
//audioURL = new URL(PATH + "turn-down-dining-room-music-player-volume-male.wav");
// }
URL configURL = TranscribeSimpleGrammar.class.getResource("config.xml");
ConfigurationManager cm = new ConfigurationManager(configURL);
Recognizer recognizer = (Recognizer) cm.lookup("recognizer");
/* allocate the resource necessary for the recognizer */
recognizer.allocate();
// configure the audio input for the recognizer
AudioFileDataSource dataSource = (AudioFileDataSource) cm.lookup("audioFileDataSource");
dataSource.setAudioFile(audioURL, null);
// Loop until last utterance in the audio file has been decoded, in which case the recognizer will return null.
Result result;
while ((result = recognizer.recognize())!= null) {
String resultText = result.getBestResultNoFiller();
System.out.println(resultText);
}
return result.getBestResultNoFiller();
}
public String get_wav_byte(byte[] wavbite,String path){
String result1="null";
try
{
File dstFile = new File(path);
FileOutputStream out = new FileOutputStream(dstFile);
out.write(wavbite, 0, wavbite.length);
out.close();
}
catch (IOException e)
{
System.out.println("IOException : " + e);
}
try {
result1=recognize_wave(path);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result1;
}
}
A: Have you ever tried to change
<property name="grammarLocation" value="resource:/edu/cmu/sphinx/demo/transcriber"/>
to
<property name="grammarLocation" value="resource:edu/cmu/sphinx/demo/transcriber"/>
(meaning just removing the leading slash before edu)?
Class.getResource() and ClassLoader.getResource() do interpret the provided name differently: while Class.getResource( "/edu/cmu/sphinx/demo/transcriber/transcriber.manifest" ) would find the resource, you have to use ClassLoader.getResource() with the argument "edu/cmu/sphinx/demo/transcriber/transcriber.manifest" to find the same resource. As you do not know which method is used by the library code you call to load the other resources, you should give it a try.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12594842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: menu accordion with first voice open i have this menu
I can not copy the code of the menu on the topic , so I put everything on jsfiddle , Practically What I would like the menu stays open without clicking on ParalleloR so I would like the open class is fixed on the first menu item
(function ($) {
$(document).ready(function () {
$('#cssmenu li.has-sub>a').on('click', function () {
$(this).removeAttr('href');
var element = $(this).parent('li');
if (element.hasClass('open')) {
element.removeClass('open'); element.find('li').removeClass('open');
element.find('ul').slideUp();
}
else {
element.addClass('open');
element.children('ul').slideDown(); element.siblings('li').children('ul').slideUp(); element.siblings('li').removeClass('open'); element.siblings('li').find('li').removeClass('open'); element.siblings('li').find('ul').slideUp();
}
});
$('#cssmenu>ul>li.has-sub>a').append('<span class="holder"></span>');
(function getColor() {
var r, g, b;
var textColor = $('#cssmenu').css('color');
textColor = textColor.slice(4);
r = textColor.slice(0, textColor.indexOf(','));
textColor = textColor.slice(textColor.indexOf(' ') + 1);
g = textColor.slice(0, textColor.indexOf(','));
textColor = textColor.slice(textColor.indexOf(' ') + 1);
b = textColor.slice(0, textColor.indexOf(')'));
var l = rgbToHsl(r, g, b);
if (l > 0.7) {
$('#cssmenu>ul>li>a').css('text-shadow', '0 0px 0px rgba(0, 0, 0, .0)');
}
else {
$('#cssmenu>ul>li>a').css('text-shadow', '0 0px 0 rgba(255, 255, 255, .0)');
}
})();
function rgbToHsl(r, g, b) {
r /= 255, g /= 255, b /= 255;
var max = Math.max(r, g, b), min = Math.min(r, g, b);
var h, s, l = (max + min) / 2;
if (max == min) {
h = s = 0;
}
else {
var d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return l;
}
});
})(jQuery);
.widget-area .widget {
padding: 40px 10px 40px 0px;
}
#cssmenu,
#cssmenu ul,
#cssmenu ul li,
#cssmenu ul li a {
margin: 0;
padding: 0;
border: 0;
list-style: none;
line-height: 1;
display: block;
position: relative;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#cssmenu {
width: 100%;
font-family: Roboto;
color: #ffffff;
}
#cssmenu ul ul {
display: none;
}
.align-right {
float: right;
}
#cssmenu > ul > li > a {
padding: 15px 25px 16px 10px;
border-top: 1px solid #CACACA;
cursor: pointer;
z-index: 2;
font-size: 12px;
font-weight: 300;
text-decoration: none;
color: #000000;
/*background: #F9F9F9;*/
}
#cssmenu > ul > li > a:hover,
#cssmenu > ul > li.active > a,
#cssmenu > ul > li.open > a {
color: #000000;
}
#cssmenu > ul > li.open > a {
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 1px 5px rgba(0, 0, 0, 0.15);
border-bottom: 0px solid #1682ba;
}
#cssmenu > ul > li:last-child > a,
#cssmenu > ul > li.last > a {
border-bottom: 0px solid #1682ba;
}
.holder {
width: 0;
height: 0;
position: absolute;
top: 0;
right: -11px;
}
.holder::after,
.holder::before {
display: block;
position: absolute;
content: "";
width: 6px;
height: 6px;
right: 20px;
z-index: 10;
-webkit-transform: rotate(-135deg);
-moz-transform: rotate(-135deg);
-ms-transform: rotate(-135deg);
-o-transform: rotate(-135deg);
transform: rotate(-135deg);
}
.holder::after {
top: 17px;
border-top: 2px solid #000;
border-left: 2px solid #000;
}
#cssmenu > ul > li > a:hover > span::after,
#cssmenu > ul > li.active > a > span::after,
#cssmenu > ul > li.open > a > span::after {
border-color: #eee;
}
.holder::before {
top: 18px;
border-top: 2px solid;
border-left: 2px solid;
border-top-color: inherit;
border-left-color: inherit;
}
#cssmenu ul ul li a {
cursor: pointer;
border-bottom: 1px solid #F5F5F5;
/* border-left: 1px solid #32373e; */
/* border-right: 1px solid #32373e; */
padding: 12px 42px 12px 16px;
z-index: 1;
text-decoration: none;
font-size: 13px;
color: #32373e;
background: #FFFFFF;
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1);
}
#cssmenu ul ul li:hover > a,
#cssmenu ul ul li.open > a,
#cssmenu ul ul li.active > a {
background: rgb(255, 255, 255);
color: #23282d;
}
#cssmenu ul ul li:first-child > a {
box-shadow: none;
}
#cssmenu ul ul ul li:first-child > a {
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1);
}
#cssmenu ul ul ul li a {
padding-left: 30px;
}
#cssmenu > ul > li > ul > li:last-child > a,
#cssmenu > ul > li > ul > li.last > a {
border-bottom: 0;
}
#cssmenu > ul > li > ul > li.open:last-child > a,
#cssmenu > ul > li > ul > li.last.open > a {
border-bottom: 0px solid #32373e;
}
#cssmenu > ul > li > ul > li.open:last-child > ul > li:last-child > a {
border-bottom: 0;
}
#cssmenu ul ul li.has-sub > a::after {
display: block;
position: absolute;
content: "";
width: 5px;
height: 5px;
right: 20px;
z-index: 10;
top: 11.5px;
border-top: 2px solid #000;
border-left: 2px solid #000;
-webkit-transform: rotate(-135deg);
-moz-transform: rotate(-135deg);
-ms-transform: rotate(-135deg);
-o-transform: rotate(-135deg);
transform: rotate(-135deg);
}
#cssmenu ul ul li.active > a::after,
#cssmenu ul ul li.open > a::after,
#cssmenu ul ul li > a:hover::after {
border-color: #000;
}
.subsubm {
padding-left: 44px !important;
background-color: #FFFFFF !important;
border: 1px !important;
color: black !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='cssmenu'>
<ul>
<li class='active has-sub'><a href='#'><span style="font-weight: 400; font-size: 16px;">ParalleloR</span></a>
<ul>
<li class='active has-sub'><a href='#'><span>Consulenza legale in outsourcing per aziende</span></a>
<ul>
<li class="last"><a class="subsubm" href='#'><span>Modello contratto di outsourcing</span></a></li>
</ul>
</li>
<li class='active'><a href='#'><span>Temporary management</span></a></li>
<li class='active'><a href='#'><span>Consulenza società estere</span></a></li>
<li class='active has-sub'><a href='#'><span>Consulenza crisi aziendale</span></a>
<ul>
<li><a class="subsubm" href='#'><span>Consulenza risanamento aziendale e rilancio</span></a></li>
<li class="last"><a class="subsubm" href='#'><span>Cpnsulenza ristrutturazione del debito</span></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
https://jsfiddle.net/exolon82/vpfLf78s/3/
I can not copy the code of the menu on the topic , so I put everything on jsfiddle , Practically What I would like the menu stays open without clicking on ParalleloR so I would like the open class is fixed on the first menu item
A: Just add this style
#cssmenu > ul > li > ul{display: block!important;}
Here is the FIDDLE
A: if you need the first menu to open on page load and you still want it to work as an accordion, trigger click event, on first menu item in top accordion, onload.
$('#cssmenu li.has-sub>a').on('click', function(){
...
});
$('#cssmenu>ul>li.has-sub>a').click();
check the fiddle
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34312158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP getting expiring time of a cookie Can I get the expiring time of a cookie which is already set?
For example, I have set a cookie:
setcookie("test_cookie","some value", time()+3600*24*30);
Now can i get the time when the test_cookie is expiring?
One option could be that when i set the test_cookie, i can set the expiring time in another cookie, but i'm wondering if there's alternative, better way without setting other cookie?
Thanks.
A: Setting it in another cookie is the best method, that or simply appending it to the end of the data you're storing with a delimeter such as #.
A: There's no way to get the expiry time because the browser doesn't send it. So the olny way is to store the time somewhere in another cookie or in session maybe.
A: Check this link How to get cookie's expire time
cookie expiration date can be set in another cookie.This cookie can then be read later to get the expiration date
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6437138",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Why using array in command cancels output redirection? I have this (simplified) code:
elems="${array[@]}"
do_cmd "xxx" "for_each \"$elems\" func" ">> $log_file" || return $?
which redirects output to $log_file (as expected).
However, if the code above is simplified as:
do_cmd "xxx" "for_each \"${array[@]}\" func" ">> $log_file" || return $?
then the output is no longer redirected to $log_file (instead it outputs to stdout).
Any ideas why?
Note: internally do_cmd uses eval. The for_each is:
for_each()
{
local elems=$1
local func_and_args=$2
for elem in $elems
do
$func_and_args $elem
done
}
A: Why The Original Code Broke
When you put ${array[@]} in a context that can only ever evaluate to a single string, it acts just like ${array[*]}. This is what your "working" code was doing (and why it wouldn't keep looking like it was working if your array values had spaces in their values or were otherwise at all interesting).
When you put ${array[@]} in a context that evaluates to multiple words (like a command), it generates breaks between words at every boundary between the individual array items.
Thus, your string starting with for_each was split up into several different arguments, rather than passing the entire array's contents at once; so the redirection was no longer present in do_cmd's $3 at all.
How To Do This Well
Starting with some general points:
*
*Array contents are data. Data is not parsed as syntax (unless you use eval, and that opens a can of worms that the whole purpose of using arrays in bash is to avoid).
*Flattening your array into a string (string=${array[@]}) defeats all the benefits that might lead you to use an array in the first place; it behaves exactly like string=${array[*]}, destroying the original item boundaries.
*To safely inject data into an evaled context, it needs to be escaped with bash 5.0's ${var@Q}, or older versions' printf %q; there's a lot of care that needs to be taken to do that correctly, and it's much easier to analyze code for correctness/safety if one doesn't even try. (To expand a full array of items into a single string with eval-safe escaping for all in bash 5.0+, one uses ${var[*]@Q}).
Don't do any of that; the primitives you're trying to build can be accomplished without eval, without squashing arrays to strings, without blurring the boundary between data and syntax. To provide a concrete example:
appending_output_to() {
local appending_output_to__dest=$1; shift
"$@" >>"$appending_output_to__dest"
}
for_each() {
local -n for_each__source=$1; shift
local for_each__elem
for for_each__elem in "${for_each__source[@]}"; do
"$@" "$for_each__elem"
done
}
cmd=( redirecting_to "$log_file" func )
array=( item1 item2 item3 )
for_each array "${cmd[@]}"
(The long variable names are to prevent conflicting with names used by the functions being wrapped; even a local is not quite without side effects when a function called from the function declaring the local is trying to reuse the same name).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74377530",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android Studio - Failed to refresh Gradle project - failed to find target 4.4w
I'm trying to move my project from eclipse into android studio so that I can start building an android wear app. I exported the app from eclipse and imported it into android studio. However, when I try and add the android wear app, I start getting the error message "failed to find target 4.4w" see screen shot.
When creating a brand new project, this error does not occur. I noticed that i'm still running on android api 19 for external libraries, but I can't upgrade it since it can't find it.
The 4.4w is installed via sdk manager, why can't android studio see this?
A: For some reason, the wear project had '4.4w' as the build target, i updated this to 20 and the error went away.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24515494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How do I Add PHP code in WordPress POST without using a plugin I am trying to add php code(2000 lines) to WordPress post manually without using any plugin or third party tool. But I have not been successful in this... If anybody knows how I can do this please feel free to post an answer. So far I have been able to add my php code to WP Page but not WP Post. I will be looking forward to you! Thanks!
A: I was able to do this by creating a separate .php file in my theme "twentytwentytwo" folder and then I pasted the following code in it...
"<?php
/*
*
*Template Name: new Theme
*Template Post Type: post
*/
?>"
""
""
By doing this I created a Separate theme for my post. Then simple pasted my php code under the get_header() line....
After this I logged in to my WP admin and clicked on the edit post and in the template dropdown section I found my theme name "new Theme" just selected that and published. Job done!
A: Use 'the_content' filter https://developer.wordpress.org/reference/hooks/the_content/
example :
function custom_content($content)
{
global $post;
if ($post && $post->post_type == 'post') {
if ($post->ID == '145'()) { // target a specific post by ID
// do something
}
}
return $content;
}
add_filter('the_content', 'custom_content');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72869564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Running two loops at the same time ? moving and traveling using loops I am a first year Computer Engineer so I am a little bit amatuer in coding C++, anyway I am creating a game where there are two spaceships shooting each other. I currently succeeded making the first spaceship move by using a while loop and the GetASyncKeyState function. but now I am making the bullets travel. I used for loop, and I did succeed in making the bullet travel upward. But there's a problem, I can't move the spaceship until the for loop stop or the bullet reach the top of the console window (I am using console btw). is there a way to both run the for loop and while at the same time ? or to run two different function at the same time since GameMovement() is for the movement of spaceship and BulletTravel() is for the bullet. and I am calling BulletTravel() from GameMovement().
void GameMovements()
{
bool FirstInitialization = true;
int Player1XCoordinate = 55, Player2XCoordinate = 55;
int Player1YCoordinateU = 28, Player1YCoordinateD = 29;
while (true)
{
BulletPattern(Player1XCoordinate);
if (FirstInitialization == true)
{
GameBorderAndStatus();
SetCoordinate(Player1XCoordinate, Player1YCoordinateU);
cout << " ^ \n";
SetCoordinate(Player1XCoordinate, Player1YCoordinateD);
cout << "^==|==^ \n";
FirstInitialization = false;
}
//MOVEMENTS FOR PLAYER 1
else if (GetAsyncKeyState(VK_LEFT) && Player1XCoordinate != 16)
{
system("cls");
GameBorderAndStatus();
Sleep(10);
Player1XCoordinate -= 3;
SetCoordinate(Player1XCoordinate, Player1YCoordinateU);
cout << " ^ \n";
SetCoordinate(Player1XCoordinate, Player1YCoordinateD);
cout << "^==|==^ \n";
}
else if (GetAsyncKeyState(VK_RIGHT) && Player1XCoordinate != 94)
{
system("cls");
GameBorderAndStatus();
Player1XCoordinate += 3;
Sleep(10);
SetCoordinate(Player1XCoordinate, Player1YCoordinateU);
cout << " ^ \n";
SetCoordinate(Player1XCoordinate, Player1YCoordinateD);
cout << "^==|==^ \n";
}
else if (GetAsyncKeyState(VK_UP) && Player1YCoordinateU != 24)
{
system("cls");
GameBorderAndStatus();
Player1YCoordinateU -= 2;
Player1YCoordinateD -= 2;
Sleep(10);
SetCoordinate(Player1XCoordinate, Player1YCoordinateU);
cout << " ^ \n";
SetCoordinate(Player1XCoordinate, Player1YCoordinateD);
cout << "^==|==^ \n";
}
else if (GetAsyncKeyState(VK_DOWN) && Player1YCoordinateU != 28)
{
system("cls");
GameBorderAndStatus();
Player1YCoordinateU += 2;
Player1YCoordinateD += 2;
Sleep(10);
SetCoordinate(Player1XCoordinate, Player1YCoordinateU);
cout << " ^ \n";
SetCoordinate(Player1XCoordinate, Player1YCoordinateD);
cout << "^==|==^ \n";
}
}
}
void GameBorderAndStatus()
{
//Draw game border
for (int i = 0; i < 31; i++)
{
SetCoordinate(15, i);
cout << "|";
SetCoordinate(104, i);
cout << "|";
}
}
void BulletPattern(int Player1MuzzleLocation)
{
for (int i = 25; i != 3; i--)
{
Sleep(100);
SetCoordinate(Player1MuzzleLocation + 3, i);
}
}
void SetCoordinate(int CoordinateX, int CoordinateY)
{
COORD Coordinate;
Coordinate.X = CoordinateX;
Coordinate.Y = CoordinateY;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), Coordinate);
}
A: Rather than using two different functions and moving one object within each, you might find better results keeping track of where each object should be, and using one function to draw both.
It's a little hard to tell what's going on in your code since some functions and variable declarations are missing (I don't see you ever actually drawing a bullet, for example - might be a bug in your BulletPattern?), but something like this might do the trick:
void GameMovements()
{
while (true)
{
//MOVEMENTS FOR PLAYER 1
if (GetAsyncKeyState(VK_LEFT) && Player1XCoordinate != GAMEBOARD_LEFT)
{
Player1XCoordinate -= 3;
}
else if (GetAsyncKeyState(VK_RIGHT) && Player1XCoordinate != GAMEBOARD_RIGHT)
{
Player1XCoordinate += 3;
}
else if (GetAsyncKeyState(VK_UP) && Player1YCoordinate != SPACESHIP_TOP)
{
Player1YCoordinate -= 2;
}
else if (GetAsyncKeyState(VK_DOWN) && Player1YCoordinate != SPACESHIP_BOTTOM)
{
Player1YCoordinate += 2;
}
Sleep(10);
UpdateBulletPosition();
DrawObjects();
}
}
void UpdateBulletPosition()
{
//if the bullet hits the top of the screen, remove it
if (bulletYCoordinate == GAMEBOARD_TOP)
{
bulletXCoordinate = 0;
bulletYCoordinate = 0;
}
//I assume you're automatically generating bullets whenever possible; you'll have to adjust this conditional if that's not the case
//no bullet? generate one
if (bulletXCoordinate == 0)
{
bulletXCoordinate = Player1XCoordinate + 3;
bulletYCoordinate = 25;
}
else
{
bulletYCoordinate--;
Sleep(100);
}
}
void DrawObjects()
{
//wipe the screen and show status first
system("cls");
GameBorderAndStatus();
SetCoordinate(Player1XCoordinate, Player1YCoordinate);
cout << " ^ \n";
SetCoordinate(Player1XCoordinate, Player1YCoordinate + 1);
cout << "^==|==^ \n";
//only draw the bullet if there's a bullet there to draw
if (bulletXCoordinate != 0)
{
SetCoordinate(bulletXCoordinate, bulletYCoordinate);
cout << ".\n";
}
}
const int GAMEBOARD_LEFT = 16;
const int GAMEBOARD_RIGHT = 94;
const int GAMEBOARD_TOP = 3;
const int SPACESHIP_TOP = 24;
const int SPACESHIP_BOTTOM = 28;
int Player1XCoordinate = 55, Player2XCoordinate = 55;
int Player1YCoordinate = 28;
int bulletXCoordinate = 0, bulletYCoordinate = 0;
I also made some tweaks to the rest of your code. Every case in your if-else block used the same basic drawing code, so I pulled that out of the if-else entirely. That also let me drop the entire initialization if-else.
I also dropped one of your vertical coordinates for the spaceship. You really don't need two; just keep track of the upper coordinate and draw the lower half of the ship at Player1YCoordinate + 1.
Finally, I replaced your hardcoded board edges with constants. Magic numbers are generally frowned upon; using named constants makes it easier to determine why you're using a given value in a given location, as well as making it easier to update the code in the future (perhaps you need to update for a different console size).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36660161",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: LUIS not returning the correct entity values I am trying to learn how to use LUIS to train for an intent to search my data on my database using NLP. I created an Intent UIM.Search and added the following Utterance for which the token view is as below:
I mapped them to the entities so that I can get the actual user values for API based queries as shown below
Issue I am having is when I use the testing panel and enter texts like:
show customers in paris for chocolatemagic the entities it returns are as below
where as when I enter an exact phrase used for training I get the correct result like:
show me cakemagic customers from bangalore
returns
Can someone please help me understand what am I missing here to translate the user query to actual intent and then get the query parameters as entities to convert to SQL queries.
EDIT1:
Adding the Model details, but this time including the Phrases, which actually works. But this is not something i would like to do as then i'll have to add all possible combinations of words that can be used in the query
{
"luis_schema_version": "3.1.0",
"versionId": "0.1",
"name": "UIM",
"desc": "",
"culture": "en-us",
"intents": [
{
"name": "None"
},
{
"name": "UIM.Search"
}
],
"entities": [
{
"name": "address.city",
"roles": []
},
{
"name": "address.country",
"roles": []
},
{
"name": "count",
"roles": []
},
{
"name": "search.order",
"roles": []
},
{
"name": "search.type",
"roles": []
},
{
"name": "subsidiary",
"roles": []
}
],
"composites": [
{
"name": "address",
"children": [
"address.city",
"address.country"
],
"roles": []
}
],
"closedLists": [],
"patternAnyEntities": [],
"regex_entities": [],
"prebuiltEntities": [
{
"name": "number",
"roles": []
}
],
"model_features": [
{
"name": "company Names",
"mode": true,
"words": "honeywell,chocolatemagic,boeing,jeppesen,cakemagic",
"activated": true
},
{
"name": "City Names",
"mode": true,
"words": "bangalore,paris,london,bellevue,berlin,amsterdam,rome,new york,madrid,moscow,sydney,tokyo,kirkland,redmond,frankfurt,barcelona,milan,vienna,prague,brussels,athens,lisbon,stockholm,munich,zurich,budapest,warsaw,copenhagen,dublin,hamburg,istanbul,oslo,bucharest,venice,helsinki,shanghai,geneva,beijing,zagreb,malaga,luxembourg,sofia,kiev,manchester,buenos aires,bangkok,singapore,tallinn,riga,seoul,melbourne,vilnius,toronto,cairo,dubai,los angeles,san francisco,montreal,vancouver,chicago,boston,mumbai,johannesburg,rio de janeiro,miami,seattle,new orleans,san diego,las vegas,houston,philadelphia,atlanta,dallas,denver,orlando,tampa,jacksonville,washington,detroit,phoenix,memphis,cleveland,pittsburgh,portland,baltimore,richmond,madison,nashville,san antonio,sacramento,charlotte,austin,indianapolis,minneapolis,columbus,buffalo,oakland,louisville,cincinnati,newark,milwaukee,san jose,birmingham,raleigh",
"activated": true
},
{
"name": "Country Names",
"mode": true,
"words": "india,usa,uk,france,australia,germany,u.s.a.,u.k.,ireland,austria,finland,denmark,spain,netherlands,sweden,italy,poland,norway,greece,cyprus,belgium,belfast,switzerland,russia,malta,romania,hungary,slovenia,croatia,portugal,european,iceland,slovakia,bulgaria,prague,serbia,estonia,lithuania,latvia,ukraine,albania,armenia,moldova,belarus,kazakhstan,ghana,uruguay,azerbaijan,moscow,paraguay,montenegro,eurovision,venezuela,algeria,burkina,cameroon,tunisia,guatemala,honduras,lesotho,angola,bolivia,nicaragua,grenada,liberia,tanzania,ecuador,cuba,tobago,zimbabwe,ethiopia,rwanda,trinidad,fiji,mozambique,guyana,namibia,belize,haiti,barbados,cambodia,mauritania,mauritius,uganda,maldives,nigeria,kenya,botswana,bahamas,vanuatu,seychelles,africa",
"activated": true
},
{
"name": "Entity Names",
"mode": true,
"words": "customers,suppliers,fleets,transactions,companies,services,employees,retailers,manufacturers,partners,fleet,products,transaction,events,contact,projects,clients,programs,facilities,client,consultant",
"activated": true
},
{
"name": "Services Names",
"mode": true,
"words": "parts,services,planes,applications,components,systems,subsystems,sensors,software,equipment,accessories,electronics,cakes",
"activated": true
}
],
"regex_features": [],
"patterns": [
{
"pattern": "show me {subsidiary} from {search.type} in {address.city}",
"intent": "UIM.Search"
},
{
"pattern": "show me {count} {search.type} from {address.city} in {address.country}",
"intent": "UIM.Search"
},
{
"pattern": "show me all {search.type} from {address.city}",
"intent": "UIM.Search"
}
],
"utterances": [
{
"text": "show 4 customers who bought cakes",
"intent": "UIM.Search",
"entities": [
{
"entity": "search.type",
"startPos": 7,
"endPos": 15
},
{
"entity": "search.order",
"startPos": 28,
"endPos": 32
}
]
},
{
"text": "show 5 customers who bought cakes from bangalore",
"intent": "UIM.Search",
"entities": [
{
"entity": "search.type",
"startPos": 7,
"endPos": 15
},
{
"entity": "search.order",
"startPos": 28,
"endPos": 32
},
{
"entity": "address.city",
"startPos": 39,
"endPos": 47
}
]
},
{
"text": "show all customers form bangalore",
"intent": "UIM.Search",
"entities": [
{
"entity": "search.type",
"startPos": 9,
"endPos": 17
},
{
"entity": "address.city",
"startPos": 24,
"endPos": 32
}
]
},
{
"text": "show customers in bangalore for cakemagic",
"intent": "UIM.Search",
"entities": [
{
"entity": "search.type",
"startPos": 5,
"endPos": 13
},
{
"entity": "address.city",
"startPos": 18,
"endPos": 26
},
{
"entity": "subsidiary",
"startPos": 32,
"endPos": 40
}
]
},
{
"text": "show me all indian customers for cakemagic",
"intent": "UIM.Search",
"entities": [
{
"entity": "address.country",
"startPos": 12,
"endPos": 17
},
{
"entity": "search.type",
"startPos": 19,
"endPos": 27
},
{
"entity": "search.order",
"startPos": 33,
"endPos": 41
}
]
},
{
"text": "show me cakemagic customers from bangalore",
"intent": "UIM.Search",
"entities": [
{
"entity": "subsidiary",
"startPos": 8,
"endPos": 16
},
{
"entity": "search.type",
"startPos": 18,
"endPos": 26
},
{
"entity": "address.city",
"startPos": 33,
"endPos": 41
}
]
},
{
"text": "show me customers from bangalore who liked our cakes",
"intent": "UIM.Search",
"entities": [
{
"entity": "search.type",
"startPos": 8,
"endPos": 16
},
{
"entity": "address.city",
"startPos": 23,
"endPos": 31
},
{
"entity": "search.order",
"startPos": 47,
"endPos": 51
}
]
},
{
"text": "show me customers from usa",
"intent": "UIM.Search",
"entities": [
{
"entity": "search.type",
"startPos": 8,
"endPos": 16
},
{
"entity": "address.country",
"startPos": 23,
"endPos": 25
}
]
},
{
"text": "show me customers who have ordered cake",
"intent": "UIM.Search",
"entities": [
{
"entity": "search.type",
"startPos": 8,
"endPos": 16
},
{
"entity": "search.order",
"startPos": 35,
"endPos": 38
}
]
},
{
"text": "show me customers who likes our cake",
"intent": "None",
"entities": [
{
"entity": "search.type",
"startPos": 8,
"endPos": 16
},
{
"entity": "search.order",
"startPos": 32,
"endPos": 35
}
]
},
{
"text": "show me top 3 customers from bangalore in india",
"intent": "UIM.Search",
"entities": [
{
"entity": "search.type",
"startPos": 14,
"endPos": 22
},
{
"entity": "address.city",
"startPos": 29,
"endPos": 37
},
{
"entity": "address.country",
"startPos": 42,
"endPos": 46
}
]
},
{
"text": "show me top 3 customers from india",
"intent": "UIM.Search",
"entities": [
{
"entity": "search.type",
"startPos": 14,
"endPos": 22
},
{
"entity": "address.country",
"startPos": 29,
"endPos": 33
}
]
},
{
"text": "show top 3 customers form bangalore who have ordered cakes in last 3 months",
"intent": "UIM.Search",
"entities": [
{
"entity": "search.type",
"startPos": 11,
"endPos": 19
},
{
"entity": "address.city",
"startPos": 26,
"endPos": 34
},
{
"entity": "search.order",
"startPos": 53,
"endPos": 57
}
]
},
{
"text": "which customers from usa bought cakes from me",
"intent": "UIM.Search",
"entities": [
{
"entity": "search.type",
"startPos": 6,
"endPos": 14
},
{
"entity": "address.country",
"startPos": 21,
"endPos": 23
},
{
"entity": "search.order",
"startPos": 32,
"endPos": 36
}
]
}
],
"settings": []
}
Regards
Kiran
A: Kiran, the issue is you only have two utterances in your app that contain the subsidiary entity. Additional to that, the word 'cakemagic' is not a real word and, thus, LUIS doesn't know how to handle that word. The option is to either include more utterances from which you can train LUIS with (i.e. more examples of context, where the entity can show up in the utterance, or different values the subsidiary can be), use real words LUIS would naturally recognize, or build out the phrase list to include all the words you are looking to have included.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52464106",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Using ODBC connection with Azure Data Studio In order to connect to an IBM DB2 database, I am using DBeaver with an ODBC type of connection. But since I found Azure Data Studio very lightweight and portable, I want to ask if there is a way to connect to such databases because all I get is Microsoft SQL Server as connection type.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72023792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Implicitly redirect in Apache I have Apache and want to implicitly redirect http request to a file.
That is, when a user hits http://example.com/foo/bar, I wish a user to see a content on .xml file under /some/folder/file.xml and at the same time a user must see http://example.com/foo/bar in the address bar.
Redirect instruction in httpd.conf makes a URL being changed once it gets redirected, but I want to keep the URL same.
A: Try this.
RewriteEngine on
RewriteRule "/foo/bar$" "/some/folder/file.xml" [PT]
you can even specify mime-type.
RewriteRule "/foo/bar$" "/some/folder/file.xml" [PT,H=application/xml]
You need internal remapping.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46353432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unable to extract JSON fields in Splunk I'm trying to extract JSON fields from syslog inputs.
In ./etc/system/default/props.conf I've added the following lines:
[mylogtype]
SEDCMD-StripHeader = s/^[^{]+//
INDEXED_EXTRACTIONS = json
KV_MODE = none
pulldown_type = true
The SEDCMD works; the syslogs headers are removed.
But the JSON fields are not parsed.
Any ideas?
A: Resolved. Use the following configuration in props.conf
[yourlogtype]
SEDCMD-StripHeader = s/^[^{]+//
KV_MODE = json
pulldown_type = true
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47513001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Storing class files in dll and using the dll for multiple websites in asp.net I want to create a class file in VS2005 and be able to use it in other websites on my computer / production server. How do I create this dll and store it in a common place where I can reference it while developing and also on the production server ?
A: Avoid the GAC unless you have full administration rights on the host server.
What you could do is create a project containing the source for your shared DLL. You can then add this project into each of your web site solutions, and add a reference in your site solutions to the project. This has the added advantage of enabling you to step into your shared source during debugging.
A: First add a class library project to your solution. Add this class into this library. And deploy this class to Global Assembly Cache (GAC). You can follow these steps to install your assembly to GAC.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1963101",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Convert time string in XSLT How do I convert a time string like
20101115083000 +0200
to
2010-11-15 08:30:00 +0200
using XSLT?
A: If you have XSLT 2.0, you can use date parsing and formatting functions.
If you have XSLT 1.0, but can use EXSLT, it provides similar functions.
These would be less transparent to use than @Peter's explicit code, but maybe more robust if your input format can vary.
A: Here is a most generic formatDateTime processing. Input and output format are completely configyrable and passed as parameters:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
<xsl:call-template name="convertDateTime">
<xsl:with-param name="pDateTime" select="."/>
</xsl:call-template>
</xsl:template>
<xsl:template name="convertDateTime">
<xsl:param name="pDateTime"/>
<xsl:param name="pInFormat">
<year offset="0" length="4"/>
<month offset="4" length="2"/>
<day offset="6" length="2"/>
<hour offset="8" length="2"/>
<minutes offset="10" length="2"/>
<seconds offset="12" length="2"/>
<zone offset="15" length="5"/>
</xsl:param>
<xsl:param name="pOutFormat">
<y/>-<mo/>-<d/> <h/>:<m/>:<s/> <z/>
</xsl:param>
<xsl:variable name="vInFormat" select=
"document('')/*/xsl:template[@name='convertDateTime']
/xsl:param[@name='pInFormat']"/>
<xsl:variable name="vOutFormat" select=
"document('')/*/xsl:template[@name='convertDateTime']
/xsl:param[@name='pOutFormat']"/>
<xsl:apply-templates select="$vOutFormat/node()"
mode="_convertDateTime">
<xsl:with-param name="pDateTime" select="$pDateTime"/>
<xsl:with-param name="pInFormat" select="$vInFormat"/>
</xsl:apply-templates>
</xsl:template>
<xsl:template match="y" mode="_convertDateTime">
<xsl:param name="pDateTime"/>
<xsl:param name="pInFormat"/>
<xsl:value-of select=
"substring($pDateTime,
1+$pInFormat/year/@offset,
$pInFormat/year/@length)"/>
</xsl:template>
<xsl:template match="mo" mode="_convertDateTime">
<xsl:param name="pDateTime"/>
<xsl:param name="pInFormat"/>
<xsl:value-of select=
"substring($pDateTime,
1+$pInFormat/month/@offset,
$pInFormat/month/@length)"/>
</xsl:template>
<xsl:template match="d" mode="_convertDateTime">
<xsl:param name="pDateTime"/>
<xsl:param name="pInFormat"/>
<xsl:value-of select=
"substring($pDateTime,
1+$pInFormat/day/@offset,
$pInFormat/day/@length)"/>
</xsl:template>
<xsl:template match="h" mode="_convertDateTime">
<xsl:param name="pDateTime"/>
<xsl:param name="pInFormat"/>
<xsl:value-of select=
"substring($pDateTime,
1+$pInFormat/hour/@offset,
$pInFormat/hour/@length)"/>
</xsl:template>
<xsl:template match="m" mode="_convertDateTime">
<xsl:param name="pDateTime"/>
<xsl:param name="pInFormat"/>
<xsl:value-of select=
"substring($pDateTime,
1+$pInFormat/minutes/@offset,
$pInFormat/minutes/@length)"/>
</xsl:template>
<xsl:template match="s" mode="_convertDateTime">
<xsl:param name="pDateTime"/>
<xsl:param name="pInFormat"/>
<xsl:value-of select=
"substring($pDateTime,
1+$pInFormat/seconds/@offset,
$pInFormat/seconds/@length)"/>
</xsl:template>
<xsl:template match="z" mode="_convertDateTime">
<xsl:param name="pDateTime"/>
<xsl:param name="pInFormat"/>
<xsl:value-of select=
"substring($pDateTime,
1+$pInFormat/zone/@offset,
$pInFormat/zone/@length)"/>
</xsl:template>
</xsl:stylesheet>
when this transformation is applied to the following XML document:
<dateTime>20101115083000 +0200</dateTime>
the wanted, correct result is produced:
2010-11-15 08:30:00 +0200
A: We use templates:
<xsl:template name="format-date-time">
<xsl:param name="date" select="'%Y-%m-%dT%H:%M:%S%z'"/>
<xsl:value-of select="substring($date, 9, 2)"/>
<xsl:text>/</xsl:text>
<xsl:value-of select="substring($date, 6, 2)"/>
<xsl:text>/</xsl:text>
<xsl:value-of select="substring($date, 1, 4)"/>
<xsl:text> </xsl:text>
<xsl:value-of select="substring($date, 12, 2)"/>
<xsl:text>:</xsl:text>
<xsl:value-of select="substring($date, 15, 2)"/>
<xsl:text>:</xsl:text>
<xsl:value-of select="substring($date, 18, 2)"/>
</xsl:template>
We call these templates like this:
<xsl:call-template name="format-date-time">
<xsl:with-param name="date" select="./Startdate"/>
</xsl:call-template>
./Startdate is an XML date, but with the substring technique, I think you could solve your problem too.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4183956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What is dynamic DAO? This blog talked about using dynamic DAO instead of activerecord. What exactly is meant by "dynamic" DAO in the context of statically typed languages? Does this apply only to statically typed languages on a VM or also to compiled languages?
A: Both DAO and ActiveRecord are patterns to access data in a Database. DAO stands for "Data Acess Object". Following are the links to the relevant Wikipedia pages to read more about the individual patterns.
*
*ActiveRecord: http://en.wikipedia.org/wiki/Active_record_pattern
*DAO: http://en.wikipedia.org/wiki/Data_access_object
Note that the ruby gem activerecord is an implementation of the "Active Record" patterns, which happens to have the same name as the pattern.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14136929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to ignore empty cell in google script function I'm trying to create a function that highlights any cells when they are changed ignoring any changes to empty cells, the function below does highlight changes but to ALL cells including empty ones, any help would be greatly appreciated.
function onEdit() {
var sheetsToWatch = ['IC', 'FTE'];
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var cell = sheet.getActiveCell();
var val = cell.getValue();
var sheetName = sheet.getName();
var matchFound = false;
for (var i = 0; i < sheetsToWatch.length; i++) {
if (sheetName.match(sheetsToWatch[i])) matchFound = true;
}
if (val && matchFound){
var rowColLabel =
sheet.getRange(cell.getRow(),cell.getColumn()).setBackground('#faec15');
I tried a bunch of different if statements to try filter empty cells but nothing changes the result
A: Take advantage of the event object e, like this:
function onEdit(e) {
if (!e) {
throw new Error('Do not run this code in the script editor.');
}
if (!e.oldValue
|| !e.range.getSheet().getName().match(/^(IC|FTE)$/i)) {
return;
}
e.range.setBackground('#faec15');
}
See Apps Script at Stack Overflow, Clean Code JavaScript, and these onEdit(e) optimization tips.
A: some ways to ignore empty data in apps-script:
// 1. assume you have one column of data:
// if your data may contains 0 or false:
function test1() {
const values = [
['value_1'],
[0],
['value_2'],
[false],
['value_3'],
[''],
['value_4']
]
for(const row of values) {
if(row[0]==undefined || row[0]=='') continue;
console.log(row);
}
}
function test2() {
// if your data do not contains 0 or false:
const values = [
['value_1'],
[''],
['value_2'],
[''],
['value_3'],
[''],
['value_4']
]
for(const row of values) {
if(!row[0]) continue;
console.log(row);
}
}
test1()
/** output:
["value_1"]
["value_2"]
["value_3"]
["value_4"]
*/
test2()
/** output:
["value_1"]
["value_2"]
["value_3"]
["value_4"]
*/
// 2. Assume you have a set rows and columns as data:
// Assume all the test samples below does not contains 0 or false:
function test3(arg) {
const values = [
['value_1-1','value_1-2','value_1-3'],
['','value_2-2','value_2-3'],
['value_3-1','','value_3-3'],
['value_4-1','value_4-2',''],
['','',''],
['value_5-1','value_5-2','value_5-3']
];
switch(arg) {
case 1: // 2-1. if you only want to check one column:
{
for(row of values) {
if(!row[1]) continue; // check only column B of each row.
console.log(row);
}
}
break;
case 2: // 2-2. if you need to check the whole row and skip only if the entire row is empty:
{
for(row of values) {
if(row.every(col => !col)) continue; // check every columns of each row.
console.log(row);
}
}
break;
case 3: // 2-3. if you need to check the whole row and skip if that row contains 1 or more empty cell:
{
for(row of values) {
if(row.some(col => !col)) continue; // check every columns of each row.
console.log(row);
}
}
break;
}
}
test3(1)
/** output:
["value_1-1","value_1-2","value_1-3"]
["","value_2-2","value_2-3"]
["value_4-1","value_4-2",""]
["value_5-1","value_5-2","value_5-3"]
*/
test3(2)
/** output:
["value_1-1","value_1-2","value_1-3"]
["","value_2-2","value_2-3"]
["value_3-1","","value_3-3"]
["value_4-1","value_4-2",""]
["value_5-1","value_5-2","value_5-3"]
*/
test3(3)
/** output:
["value_1-1","value_1-2","value_1-3"]
["value_5-1","value_5-2","value_5-3"]
*/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74759865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can you use TFS API with only query strings? Trying to queue build from Slack Using On-Premise TFS 2017 and Slack. Just trying to find a way for people to manually queue builds. Slack Slash Commands will almost work, but can't seem to send JSON bodies, so I'm trying to find out how to send credentials and definition IDs using only query strings...
Some background:
*
*Our people cannot run unsigned Powershell Scripts because of Group Policy overrides for ExecutionPolicy.
*Don't want to give people access to queue builds through web interface.
*We are using CI/CD, but need to manually queue for QA/Demo builds.
*Wanted to avoid using another app as a go-between if possible, since new environments for hosting are hard to come by here.
Is there a way to hit the TFS API through Slack Slash Commands?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56241938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Django Model Foreign Key Casting Integer to Char Edited
I have two tables Table1 and Table2. Table1 has a field x of type int and Table2 has primary key y of type char. I am trying to do x = models.ForeignKey(Table2, ...) but it tries to cast y to an int first. In doing so, this overflows the int. I am wondering if it is possible to first cast x to a char and then do the foreign key relationship.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49799351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What is the purpose of & in (a & 1) I am trying to solve a problem in codefights, after browsing the net, i found this solution.But i am not clear how it works.
a * (a & 1) ^ b * !(b & 1) ^ !!(((a ^ b) + 1) & 2)
A: A single & is a bitwise AND, which means that the result is the bits that are set on BOTH left and right side of the operator.
As an example 15 & 7 or as they are represented in binary:
1111
&
0111
The bitwise AND will result in the a number with the common bits set:
1111 & 0111 = 0111
When you make the (a & 1) you are testing whether the least significant bit (lsb) is set, since you are performing a test like this:
a
&
00000001
If a had the bitwise value: 00000110 then the result would be 0, since there are no common bits set, if a had the bitwise value: 00000111 then the result would be 1 since the lsb is set on a.
This is used for different situations, if the lsb is set you know that the number is odd, so this test is really whether the number is odd or not (1, 3, 5, 7, ...).
Looking at the first part of your solution: a * (a & 1) you are multiplying a with the value of (0 or 1 remember), 1 if a is odd, and 0 if it is even.
A: Here & is a Bitwise Operator(works on bits and perform bit-by-bit operation).For more details see this and this
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40485527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.