text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: MVC Razor WebGrid Nullable Complex Types I have an entity called Lookup who has a complex Type Description with two string English and French. There has arise a time where no value will be store into the lookup. Now other entities have lookups as properties so we could have foo.Lookup.Description.English for example.
I'm trying to use a Web Grid to display the information being selected.
Originally my controller looked like
public ViewResult Index()
{
var foos = db.Foos;
return View(foo.ToList());
}
and my view looked like
@model IEnumerable<Foo>
@{
ViewBag.Title = "Index";
}
<h2>Stay Manager</h2>
@{
var grid = new WebGrid(Model, defaultSort: "sortMe", rowsPerPage: 3);
grid.GetHtml(htmlAttributes: new { id = "DataTable" });
}
@grid.GetHtml(columns: grid.Columns(
grid.Column("Lookup.Description.English", "Column Header")
))
My issue is that Lookup can at times be null and ill will get an error saying the the Column Lookup.Description.English does not exist.
I found a solution but not a very elegant one and was hoping that there was a better a way. My solution was to change my controller action to
public ViewResult Index()
{
var foos = db.Foos;
foreach (Foo currentFoo in Foos.Where(s => s.Lookup == null))
{
Foo.Lookup = new Lookup();
Foo.Lookup.Description.English = "";
Foo.Lookup.Description.French = "";
}
return View(foos.ToList());
}
Any suggestions on how to get the Web Grid to work better with null-able complex types?
A: Not at all that familair with webgrid, but would the following be a solution for you?
I made the following simple model:
public class Foo
{
public string Name { get; set; }
public Lookup Lookup { get; set; }
}
public class Lookup
{
public string Name { get; set; }
public Description Description { get; set; }
}
public class Description
{
public string English { get; set; }
public string French { get; set; }
}
controller action (i don't have a db, so I mocked some data):
public ViewResult Index()
{
//var foos = db.Foos;
var foos = new List<Foo>();
foos.Add(new Foo { Name = "Foo1" });
foos.Add(new Foo
{
Name = "Foo2",
Lookup = new Lookup
{
Name = "Lookup2",
Description = new Description
{
English = "englishFoo2",
French = "frenchFoo2"
}
}
});
foos.Add(new Foo
{
Name = "Foo3",
Lookup = new Lookup
{
Name = "Lookup3",
Description = new Description
{
//English = "englishFoo3",
French = "frenchFoo3"
}
}
});
foos.Add(new Foo { Name = "Foo4" });
foos.Add(new Foo
{
Name = "Foo5",
Lookup = new Lookup
{
Description = new Description
{
English = "englishFoo5",
French = "frenchFoo5"
}
}
});
foos.Add(new Foo {
Name = "Foo6",
Lookup = new Lookup
{
Name = "Lookup6"
}
});
return View(foos);
}
So, I now have Foos with or without Lookups (with or without Description).
The view is as follows:
@model IEnumerable<Foo>
@{
var grid = new WebGrid(Model, defaultSort: "sortMe", rowsPerPage: 10);
grid.GetHtml(htmlAttributes: new { id = "DataTable" });
}
@grid.GetHtml(
columns: grid.Columns(
grid.Column(
columnName: "Name",
header: "Foo"
),
grid.Column(
columnName: "Lookup.Name",
header: "Lookup",
format: @<span>@if (item.Lookup != null)
{ @item.Lookup.Name }
</span>
),
grid.Column(
columnName: "Lookup.Description.English",
header: "Description.English",
format: @<span>@if (item.Lookup != null && item.Lookup.Description != null)
{ @item.Lookup.Description.English }
</span>
),
grid.Column(
columnName: "Lookup.Description.French",
header: "Description.French",
format: @<span>@if (item.Lookup != null && item.Lookup.Description != null)
{ @item.Lookup.Description.French }
</span>
)
)
)
which works just fine for me (Asp.Net MVC 3), it procudes the following html:
[snip]
<tr>
<td>Foo4</td>
<td><span></span></td>
<td><span></span></td>
<td><span></span></td>
</tr>
<tr>
<td>Foo5</td>
<td><span></span></td>
<td><span>englishFoo5 </span></td>
<td><span>frenchFoo5 </span></td>
</tr>
<tr>
<td>Foo6</td>
<td><span>Lookup6</span></td>
<td><span></span></td>
<td><span></span></td>
</tr>
[/snip]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7285577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Count The Number of Duplicate Values during the preceding timeperiod I am looking to count how many duplicate values there are in a previous time period (24 hours to make it simple).
For example in this data set
I am looking to come up with values such as this
Here is some how to create the below dataframe
data = [("5812", "2020-12-27T17:28:32.000+0000"),("5812", "2020-12-25T17:35:32.000+0000"), ("5812", "2020-12-25T13:04:05.000+0000"), ("7999", "2020-12-25T09:23:01.000+0000"),("5999","2020-12-25T07:29:52.000+0000"), ("5814", "2020-12-25T12:23:05.000+0000"), ("5814", "2020-12-25T11:52:57.000+0000"), ("5814", "2020-12-24T11:00:57.000+0000") ,("5999", "2020-12-24T07:29:52.000+0000")]
df = spark.createDataFrame(data).toDF(*columns)
I have been using windowed functions to get things such as distinct counts, sums etc, but I can't quite figure out how to get a count of duplicate values over the same time period.
A: Let's try this step by step
*
*Cast column timestamp to TimestampType format.
*Create a column of collect_list of mcc (say mcc_list) in the last 24 hours using window with range between interval 24 hours and current row frame.
*Create a column of set/unique collection of mc_list (say mcc_set) using array_distinct function. This column could also be created using collect_set over the same window in step 2.
*For each value of mcc_set, get its count in the mcc_list. Duplicated mcc value will have a count of > 1 so we can filter it. After that, the array will only contain the duplicated mcc, use size to count how many mcc are duplicated in the last 24 hours.
These steps put into a code could be like this
import pyspark.sql.functions as F
from pyspark.sql.types import *
df = (df
.withColumn('ts', F.col('timestamp').cast(TimestampType()))
.withColumn('mcc_list', F.expr("collect_list(mcc) over (order by ts range between interval 24 hours preceding and current row)"))
.withColumn('mcc_set', F.array_distinct('mcc_list'))
.withColumn('dups', F.expr("size(filter(transform(mcc_set, a -> size(filter(mcc_list, b -> b = a))), c -> c > 1))"))
# .drop(*['ts', 'mcc_list', 'mcc_set']))
)
df.show(truncate=False)
# +----+----------------------------+-------------------+------------------------------------+------------------------+----+
# |mcc |timestamp |ts |mcc_list |mcc_set |dups|
# +----+----------------------------+-------------------+------------------------------------+------------------------+----+
# |5812|2020-12-27T17:28:32.000+0000|2020-12-27 17:28:32|[5812] |[5812] |0 |
# |5812|2020-12-25T17:35:32.000+0000|2020-12-25 17:35:32|[5999, 7999, 5814, 5814, 5812, 5812]|[5999, 7999, 5814, 5812]|2 |
# |5812|2020-12-25T13:04:05.000+0000|2020-12-25 13:04:05|[5999, 7999, 5814, 5814, 5812] |[5999, 7999, 5814, 5812]|1 |
# |5814|2020-12-25T12:23:05.000+0000|2020-12-25 12:23:05|[5999, 7999, 5814, 5814] |[5999, 7999, 5814] |1 |
# |5814|2020-12-25T11:52:57.000+0000|2020-12-25 11:52:57|[5999, 7999, 5814] |[5999, 7999, 5814] |0 |
# |7999|2020-12-25T09:23:01.000+0000|2020-12-25 09:23:01|[5814, 5999, 7999] |[5814, 5999, 7999] |0 |
# |5999|2020-12-25T07:29:52.000+0000|2020-12-25 07:29:52|[5999, 5814, 5999] |[5999, 5814] |1 |
# |5814|2020-12-24T11:00:57.000+0000|2020-12-24 11:00:57|[5999, 5814] |[5999, 5814] |0 |
# |5999|2020-12-24T07:29:52.000+0000|2020-12-24 07:29:52|[5999] |[5999] |0 |
# +----+----------------------------+-------------------+------------------------------------+------------------------+----+
You can drop unwanted columns afterwards.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68945258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Formatting off in Safari vs Chrome I am using this template to build this website.
In chrome and edge, the services tiles look right:
In safari, the rows are messed up:
I am not a pro at this stuff ... I am just a freelancer trying to do everything ... and poked around and cannot spot the source of this problem. The index.html and style.css code is pasted below.
[index.html header]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Velodu - Market Research & Consulting</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css?family=Raleway:100,200,300,400,500,600,700,800,900" rel="stylesheet">
<!-- Favicon -->
<link rel="shortcut icon" href="img/favicon.png">
<!-- Template CSS Files -->
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="css/font-awesome.min.css" />
<link rel="stylesheet" type="text/css" href="css/magnific-popup.css" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<link rel="stylesheet" type="text/css" href="css/skins/purple.css" />
<!-- Revolution Slider CSS Files -->
<link rel="stylesheet" type="text/css" href="js/plugins/revolution/css/settings.css" />
<link rel="stylesheet" type="text/css" href="js/plugins/revolution/css/layers.css" />
<link rel="stylesheet" type="text/css" href="js/plugins/revolution/css/navigation.css" />
<!-- Template JS Files -->
<script type="text/javascript" src="js/modernizr.js"></script>
</head>
["Services" code in index.html]
<!-- About Section Starts -->
<section id="about" class="about">
<!-- Container Starts -->
<div class="container">
<!-- Main Heading Starts -->
<div class="text-center top-text">
<h1><span>About</span> Us</h1>
<h4>Who We Are</h4>
</div>
<!-- Main Heading Ends -->
<!-- Divider Starts -->
<div class="divider text-center">
<span class="outer-line"></span>
<span class="fa fa-user" aria-hidden="true"></span>
<span class="outer-line"></span>
</div>
<!-- Divider Ends -->
<!-- About Content Starts -->
<div class="row about-content">
<div class="col-sm-12 col-md-12 col-lg-6 about-left-side">
<p>Business keeps moving faster, so nobody has time for slow agencies who add complexity.</p>
<p>We deliver high-quality, high-velocity market research and consulting services because we are great at identifying and removing bottlenecks, especially when the bottleneck is us.</p>
<a class="custom-button scroll-to-target" href="#services">Our Services</a>
<div>
<p><br /></p>
<a style="color:#795DB4" target="_blank" href="https://www.linkedin.com/in/garypansino/">Founder's LinkedIn Profile</a>
</div>
</div>
<div class="col-md-12 col-lg-6 about-right-side">
<div class="full-image-container hovered">
<img class="img-fluid d-none d-md-block" src="img/about.jpg" alt="">
<div class="full-image-overlay">
<h3>Why <strong>Choose Us</strong></h3>
<ul class="list-why-choose-us">
<li>Diverse experience across tech, CPG, retail, etc.</li>
<li>Deep knowledge of research methodologies</li>
<li>Strategic business lens</li>
<li>Leverage the latest tools and tech</li>
</ul>
</div>
</div>
</div>
</div>
<!-- About Content Ends -->
</div>
<!-- Container Ends -->
</section>
<!-- About Section Ends --> <!-- Services Section Starts -->
<section id="services" class="services">
<!-- Container Starts -->
<div class="container">
<!-- Main Heading Starts -->
<div class="text-center top-text">
<h1><span>Our</span> Services</h1>
<h4>What We Do</h4>
</div>
<!-- Main Heading Starts -->
<!-- Divider Starts -->
<div class="divider text-center">
<span class="outer-line"></span>
<span class="fa fa-cogs" aria-hidden="true"></span>
<span class="outer-line"></span>
</div>
<!-- Divider Ends -->
<!-- Services Starts -->
<div class="row services-box">
<!-- Service Item Starts -->
<div class="col-lg-4 col-md-6 col-sm-12 services-box-item">
<!-- Service Item Cover Starts -->
<span class="services-box-item-cover fa fa-bar-chart" data-headline="Quantitative Research"></span>
<!-- Service Item Cover Ends -->
<!-- Service Item Content Starts -->
<div class="services-box-item-content fa fa-bar-chart">
<h2>Quantitative Research</h2>
<p>Of course we do surveys. Concept tests, attitude and usage studies, pricing studies, brand tracking ... the list is long. We do them better because of our advanced programming, and dashboarding skills that complement our deep methodological knowledge.</p>
</div>
<!-- Service Item Content Ends -->
</div>
<!-- Service Item Ends -->
<!-- Service Item Starts -->
<div class="col-lg-4 col-md-6 col-sm-12 services-box-item">
<!-- Service Item Cover Starts -->
<span class="services-box-item-cover fa fa-comments-o" data-headline="Qualitative Research"></span>
<!-- Service Item Cover Ends -->
<!-- Service Item Content Starts -->
<div class="services-box-item-content fa fa-comments-o">
<h2>Qualitative Research</h2>
<p>We're experts at setting up and conducting interviews, ethnographical research, and focus groups. At the end, you'll get concise insights that tell a strategic story, rather than a text-heavy mess that you have to decipher yourself.</p>
</div>
<!-- Service Item Content Ends -->
</div>
<!-- Service Item Ends -->
<!-- Service Item Starts -->
<div class="col-lg-4 col-md-6 col-sm-12 services-box-item">
<!-- Service Item Cover Starts -->
<span class="services-box-item-cover fa fa-search" data-headline="Secondary Research"></span>
<!-- Service Item Cover Ends -->
<!-- Service Item Content Starts -->
<div class="services-box-item-content fa fa-search">
<h2>Secondary Research</h2>
<p>The best data is data that already exists. Let us help you find information that is already out there, and compile it in a story that inspires action.</p>
</div>
<!-- Service Item Content Ends -->
</div>
<!-- Service Item Ends -->
<!-- Service Item Starts -->
<div class="col-lg-4 col-md-6 col-sm-12 services-box-item">
<!-- Service Item Cover Starts -->
<span class="services-box-item-cover fa fa-puzzle-piece" data-headline="Innovation"></span>
<!-- Service Item Cover Ends -->
<div class="services-box-item-content fa fa-puzzle-piece">
<h2>Innovation</h2>
<p>Achieve breakthrough results by defining your problem, vision, hypotheses, experiments, etc. in addition to developing new concepts. We help you add structure to the innovation process so it is more efficient and fruitful.</p>
</div>
</div>
<!-- Service Item Ends -->
<!-- Service Item Starts -->
<div class="col-lg-4 col-md-6 col-sm-12 services-box-item">
<!-- Service Item Cover Starts -->
<span class="services-box-item-cover fa fa-sticky-note" data-headline="Facilitation"></span>
<!-- Service Item Cover Ends -->
<!-- Service Item Content Starts -->
<div class="services-box-item-content fa fa-sticky-note">
<h2>Facilitation</h2>
<p>Running a good meeting or workshop requires preparation and reflection time, which you may not have to devote. Let us help you with your next brainstorming, team-building, or alignment-gathering session.</p>
</div>
<!-- Service Item Content Ends -->
</div>
<!-- Service Item Ends -->
<!-- Service Item Starts -->
<div class="col-lg-4 col-md-6 col-sm-12 services-box-item">
<!-- Service Item Cover Starts -->
<span class="services-box-item-cover fa fa-question-circle" data-headline="Other"></span>
<!-- Service Item Cover Ends -->
<!-- Service Item Content Starts -->
<div class="services-box-item-content fa fa-question-circle">
<h2>Other</h2>
<p>Have another need? Surprise us with a new request.</p>
</div>
<!-- Service Item Content Ends -->
</div>
<!-- Service Item Ends -->
</div>
<!-- Services Ends -->
</div>
</body>
</html>
["Services" code in style.css]
/* Services
---------------------------------------- */
.services {
background-color: #efefef;
}
.services .services-box {
margin: 25px 0;
}
.services .services-box:before {
content: "";
display: table;
}
.services .services-box:after {
content: "";
display: table;
clear: both;
}
.services .services-box-item {
position: relative;
color: #717c8e;
text-decoration: none;
-webkit-perspective: 750px;
-ms-perspective: 750px;
-o-perspective: 750px;
perspective: 750px;
margin: 15px 0;
float: left;
}
.services .services-box-item:hover,
.services .services-box-item:focus,
.services .services-box-item.hover {
text-decoration: none;
}
.services .services-box-item:hover> .services-box-item-cover,
.services .services-box-item:focus> .services-box-item-cover,
.services .services-box-item.hover> .services-box-item-cover {
-webkit-transform: rotateY(180deg);
transform: rotateY(180deg);
}
.services .services-box-item:hover> .services-box-item-content,
.services .services-box-item:focus> .services-box-item-content,
.services .services-box-item.hover> .services-box-item-content {
-webkit-transform: rotateY(360deg);
transform: rotateY(360deg);
}
.services .services-box-item-cover,
.services .services-box-item-content {
position: relative;
border-radius: 3px;
background: #fff;
-webkit-transition: -webkit-transform 0.3s;
transition: -webkit-transform 0.3s;
transition: transform 0.3s;
transition: transform 0.3s, -webkit-transform 0.3s;
-webkit-transform: rotateY(0deg);
transform: rotateY(0deg);
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
}
.services .services-box-item-cover {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: 0px 15px;
box-shadow: 0px 0px 3px 1px #ddd;
border-radius: 7px;
}
.services .services-box-item-cover:before,
.services .services-box-item-cover:after {
position: absolute;
top: 50%;
left: 50%;
}
.services .services-box-item-cover:before {
margin: -40px 0px 0px -20px;
font-size: 40px;
}
.services .services-box-item-cover:after {
content: attr(data-headline);
font-family: "Raleway";
left: 0;
width: 100%;
margin: 20px 0 0;
font-size: 18px;
text-align: center;
font-weight: 500;
}
.services .services-box-item-content {
overflow: hidden;
margin: -16px -6px;
padding: 30px 40px;
font-size: 14px;
-webkit-transform: rotateY(180deg);
transform: rotateY(180deg);
border-radius: 7px;
}
.services .services-box-item-content:before {
position: absolute;
top: 0;
right: 0;
margin: -60px;
font-size: 228px;
opacity: 0.2;
}
.services .services-box-item-content h2 {
position: relative;
margin: 8px 0;
font-size: 16px;
font-weight: 500;
text-transform: Capitalize;
}
.services .services-box-item-content p {
line-height: 23px;
position: relative;
margin: 12px 0;
font-size: 13px;
}
.services[data-icon]:before,
.services[class^="icon-"]:before,
.services[class*=" icon-"]:before {
-webkit-font-smoothing: antialiased;
font-smoothing: antialiased;
text-rendering: geometricPrecision;
text-indent: 0;
display: inline-block;
position: relative;
}
.services[data-icon]:before {
content: attr(data-icon);
}
.services[data-icon].after:before {
content: none;
}
.services[data-icon].after:after {
content: attr(data-icon);
-webkit-font-smoothing: antialiased;
font-smoothing: antialiased;
text-rendering: geometricPrecision;
text-indent: 0;
display: inline-block;
position: relative;
margin-left: 4px;
}
Any ideas/help is appreciated!
A: I was able to figure it out with more googling.
This great article.
I replaced this in style.css:
.services .services-box:before {
content: "";
display: table;
}
.services .services-box:after {
content: "";
display: table;
clear: both;
}
With this:
.services .services-box:before {
content: "";
display: table;
table-layout: fixed;
max-width: none;
width: auto;
min-width: 100%;
}
.services .services-box:after {
content: "";
display: table;
clear: both;
table-layout: fixed;
max-width: none;
width: auto;
min-width: 100%;
}
And problem solved.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50953267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to do a Second Commit in Github Can anybody explain how can use github to store my project. I have created an account,created a repository, uploaded my files to it all these are done mechanically by following their help. But i dont know what to do next. How can i do a second commit.
and what is mean by branch please explain it as to a beginner i am not understanding their help too.
A: As noted in the comments, the Git Community Book is a great resource for learning all about git, from basic usage right up to really advanced stuff.
If for some reason that's not to your liking, then this question links to a large number of reference guides for using git. You may want to look at the "beginner's references" section. Also some answers to that question point to GUI tools for Git that you may find useful.
The basic commands you're going to need to learn to use git effectively include add, status, diff, commit, pull, push, checkout, merge, and branch. You can get basic help for each command by using git help followed by the command you need help for (e.g. git help add).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9842698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android Circle Shape in 16 to 23 Android Version I want to make a circle that is perfect in all Android versions.
I tried to create a drawable like this:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
...color..stroke...
</shape>
And in my layout, I created a TextView like:
<TextView
android:background="@drawable/shape_circle"
android:layout_width="64dp"
android:layout_height="64dp"
/>
The problem is that is some devices shows a circle view, and some others shows a oval view.
*
*Moto G2 - 5.0.2 = Circle
*Samsung S2 - API 16 = Oval
*Samsung S3 - API 18 = Circle
*Samsung S3 - API 16 = Oval
*Nexus 5 - API 22 = Circle
EDIT:
layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
>
<TextView
android:id="@+id/text_table_empty"
android:text="14"
android:gravity="center"
android:textColor="@color/medium_gray"
android:textSize="18sp"
android:background="@drawable/shape_table"
android:layout_width="64dp"
android:layout_height="64dp"
/>
<TextView
android:id="@+id/text_table_used"
android:text="14"
android:gravity="center"
android:textColor="@color/white"
android:textSize="18sp"
android:background="@drawable/shape_table_used"
android:layout_width="64dp"
android:layout_height="64dp"
/>
<TextView
android:layout_marginTop="2dp"
android:layout_marginRight="2dp"
android:textSize="12sp"
android:textColor="@color/white"
android:id="@+id/text_table_num_orders"
android:layout_alignRight="@+id/text_table_used"
android:layout_alignTop="@+id/text_table_used"
android:gravity="center"
android:background="@color/light_green"
android:text="1"
android:layout_width="20dp"
android:layout_height="20dp"/>
</RelativeLayout>
drawable shape_table:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<solid android:color="@color/light_gray"/>
<stroke android:width="1dp"
android:color="@color/medium_gray"
/>
<size
android:width="64dp"
android:height="64dp"/>
</shape>
OBS: The drawable shape_table_used is the same as shape_table, without stroke and other color.
A: please use this
you can also remove the size tag but in this case your view hight and width must be equal
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<stroke
android:width="1dp"
android:color="#E0D8D0" />
<size
android:width="80dp"
android:height="80dp"/>
</shape>
A: Actually you almost get it right. A circle is an oval with with same width and height so you can just set the width and height inside the shape and you will get circle in every device
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid
android:color="@color/white"/>
<size
android:width="100dp"
android:height="100dp"/>
</shape>
A: if You want a circle You use this but your View hight and width must be equal
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<gradient
android:angle="270"
android:endColor="#80FF00FF"
android:startColor="#FFFF0000" />
</shape>
and You also use this
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<gradient
android:angle="270"
android:endColor="#80FF00FF"
android:startColor="#FFFF0000" />
<size
android:width="80dp"
android:height="80dp"/>
</shape>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33405757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Javascript array of hrefs I am trying to create an array with different hrefs to then attach to 5 separate elements.
This is my code:
var link = new Array('link1', 'link2', 'link3', 'link4', 'link5');
$(document.createElement("li"))
.attr('class',options.numericId + (i+1))
.html('<a rel='+ i +' href=\"page.php# + 'link'\">'+ '</a>')
.appendTo($("."+ options.numericId))
As you can see I am trying to append these items from the array to the end of my page so each link will take the user to a different section of the page. But i have not been able to do this. Is there a way to to create elements with different links?
I am new to javascript so I am sorry if this doesn't make a whole lot of sense. If anyone is confused by what i am asking here I can try to clarify if I get some feedback.
The code I would Like output is:
<ul class="controls">
<li class="controls1"><a href="page.php#link1"></a></li>
<li class="controls2"><a href="page.php#link2"></a></li>
<li class="controls3"><a href="page.php#link3"></a></li>
<li class="controls4"><a href="page.php#link4"></a></li>
<li class="controls5"><a href="page.php#link5"></a></li>
</ul>
Which is similar to what I am getting, however when I apply the fix that andres descalzo has supplied, my list elements are each repeating themselves 5 times.
Any solutions would be greatly appreciated.
Thanks,
jason
A: I'm not sure exactly what you want, as there is some undefined values and syntax errors in your code, but here is an example on how to create elements from an array and add to an existing ul element:
$(function(){
$.each(['link1', 'link2', 'link3', 'link4', 'link5'], function(i, link){
$('<li/>')
.append(
$('<a/>')
.attr({ 'class': 'c' + i, ref: i, href: 'page.php#' + link })
.text(link)
).appendTo('ul');
});
});
With the existing ul element, it produces:
<ul>
<li><a class="c0" ref="0" href="page.php#link1">link1</a></li>
<li><a class="c1" ref="1" href="page.php#link2">link2</a></li>
<li><a class="c2" ref="2" href="page.php#link3">link3</a></li>
<li><a class="c3" ref="3" href="page.php#link4">link4</a></li>
<li><a class="c4" ref="4" href="page.php#link5">link5</a></li>
</ul>
(In place of the array literal [...] you could of course use an array variable.)
A: something like this?:
*Edit II * for comment
var link = ['strategy', 'branding', 'marketing', 'media', 'management'],
refNumericId = $("."+ numericId);
$(link).each(function(i, el){
$("<li></li>")
.attr("id", numericId + "_" + (i+1))
.attr("class", numericId + (i+1))
.html("<a href=\"capabilities.php#"+el+"\"></a>")
.appendTo(refNumericId);
});
I saw your code in the file 'easySlider1.7.js' and you're including in 'for' of the line 123 the code 'var link = [' strategy,''which should go after this 'for'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2774980",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Write this function without bitsets Trying to write a function that gives all ways to cover a R rows by 2 columns figure, I find this function but uses a approach with bitsets, was wondering how can i do this wihtout using binary operators.
This the function explanation: left_obstacles is a bitset of size R in which each 1 represents an obstacle in the left column, in which this function generates all possible ways to cover the rest of the left column using 1x1 and 2x2 blocks, and for each of them it returns the bitset of cells covered in the right column.
def place22blocks(left_obstacles):
options = set([ (left_obstacles,0) ])
for add in range(R//2):
new_options = set()
for option in options:
new_options.add(option)
left, right = option
for i in range(R-1):
if (left & (3<<i)) == 0:
new_options.add( (left | (3<<i), right | (3<<i)) )
options = new_options
return [ option[1] for option in options ]
A: If I understand you correctly, you want to have 2 "columns" (variables) that contain obstacles but cannot both contain obstacles in the same "row" (bit)
If this is the case the first observation I would make is that any time there is a blockage in the left column the possible options of the right column on both sides of that blockage are totally independent, in fact if my left column looks something like this:
000110000
Then really I just need to find all combinations of obstacles for R=3 and also for R=4 then the final answer will be the Cartesian product of filling those 2 gaps with the combinations.
So first we can write some code to make all possible permutations of obstacles for a given R which we can do recursively, you indicated you wanted to move away from bitwise so I'll use tuple concatenation as it will likely be a little easier to manipulate for your actual task than bit operations.
def obstacle_combos(R):
"""
yields all sequences of obstacles with size 'size'
obstacle_patterns is a set of tuples representing different obstacles
"""
if R==0:
# cannot fit any blocks of size 0
yield ()
return
if R==1:
# this ensures the loop below can always check combo[-1] without index error
yield (0,)
return
for combo in obstacle_combos(R-1):
yield combo + (0,)
if combo[-1] == 0:
# when the last element is empty we could instead put a block of 1s as well.
yield combo[:-1] + (1,1)
print(*obstacle_combos(5), sep="\n")
The way this works is relatively straight forward, the base case of R=0 and R=1 are the trivial case, otherwise we check for R-1 and that combo with an extra 0 at the end is a valid obstacle combo for R, but also if the last element is 0 we can stick a 11 at the end as well so that becomes a conditional extra case.
The next step would be to identify runs of consecutive 0s, this is also not particularly complicated we just iterate over the sequence and implement some logic when we switch from 0 to 1 or 1 to 0 etc:
def find_gaps(obstacle_sequence):
"yields (slice, size) for each range of concecutive 0s in the sequence"
in_seq = False #whether we are currently in a run of 0s
for i,elem in enumerate(obstacle_sequence):
if not in_seq and elem == 0:
in_seq = True
start_idx = i
elif in_seq and elem == 1:
in_seq = False
yield slice(start_idx, i), i-start_idx
# after the loop if the last elements were 0s then yield the final sequence
if in_seq:
yield slice(start_idx, len(obstacle_sequence)), len(obstacle_sequence)-start_idx
One thing here that is slightly unorthodox is that I am creating slice objects directly, this is what happens internally if you do x[a:b] it is the same as x[slice(a,b)], the goal here being that later we can use the values this function produces to do something like:
Y = [0]*len(X) # some sequence of same size as X
for idx_range, size in find_gaps(X):
Y[idx_range] = generate_seq_of_length(size)
to set ranges of Y (which will end up being our right_obstacles eventually) with minimal effort outside the find_gaps function.
Now the tricky part, we want a function to take a left_obstacles sequence of 1s and 0s, find all the runs of 0s by calling find_gaps and at the same time find all the combinations of obstacles we could put in that section. Then go over all combinations (cartesian product) of the obstacles that can be laid out in each region.
import itertools
def place22blocks(left_obstacles):
# start by making a sequence of the same size as left_obstacles
right_obstacles = [0 for _ in left_obstacles]
# then we will find all the gaps and setup the obstacle_combos for each one
gap_ranges = []
seq_filling_iterators = []
for idx_range, size in find_gaps(left_obstacles):
gap_ranges.append(idx_range)
seq_filling_iterators.append(obstacle_combos(size))
# at this point each element of seq_filling_iterators is an iterator
# that will give the different possibilities of obstacles for each region,
# the final result of possible obstacles is the cartesian product of all of them
for list_of_obstacles_per_gap in itertools.product(*seq_filling_iterators):
# list_of_obstacles_per_gap is now a list of the sequences to fill in each gap, it is the "generate_seq_of_length(size)" in the previous example essentially.
for idx_range, seq in zip(gap_ranges, list_of_obstacles_per_gap):
right_obstacles[idx_range] = seq
# since we are reusing the right_obstacles variable every loop we will need to make a copy for each valid obstacle list, will make it a tuple so it is immutable but you could also do list(right_obstacles) if you wanted.
yield tuple(right_obstacles)
print(*place22blocks((0,0,0,1,1,0,0,0)),sep="\n")
This function I will admit is very complicated to fully wrap your head around for how short it is. gap_ranges is the list of ranges where we have space to put obstacles which is parallel to list_of_obstacles_per_gap that is the list of sequences, each element matching with the indices stored in gap_ranges which is why we zip them together. The way list_of_obstacles_per_gap is generated is a little harder to grasp though, the first thing is that product is like a nested loop:
# example loop:
for x in range(5):
for y in ["a","b","c"]:
for z in range(10):
things = (x,y,z)
# that would be equivalent to
for things in itertools.product(range(5), ["a","b","c"], range(10)):
pass
so an example that might help would be to think about how the code would work if there were exactly 2 gaps to put obstacles:
for obs_seq1 in obstacle_combos(3):
for obs_seq2 in obstacle_combos(4):
right_obstacles[0:3] = obs_seq1
right_obstacles[5:9] = obs_seq2
print(right_obstacles)
so in the function above the outer loop is collapsing an arbitrary number of nested loops and the inner loop is performing all those sequence assignments.
No idea if any of this will actually help you, I'm still not sure exactly what you are trying to accomplish but I had fun working through this, happy coding :)
Also note if you wanted to implement this more efficient algorithm with bitwise operations that would be very doable as well:
import itertools
def obstacle_combos(R):
"""
yields all sequences of obstacles with size 'size'
obstacle_patterns is a set of tuples representing different obstacles
"""
if R<=1:
# cannot fit any blocks of size 0
yield 0
return
for c in obstacle_combos(R-1):
# shift the original combo so that we are inserting at the least significant bits,
# is a little simpler than tracking how much to shift the 3 by.
combo = c<<1
yield combo
if combo&3 == 0:
# when the last element is empty we could instead put a block of 1s as well.
yield combo | 3
#print(*obstacle_combos(5), sep="\n")
def find_gaps(obstacle_sequence, R):
"yields (slice, size) for each range of consecutive 0s in the sequence, where slice is the bit position of the least significant bit that is 0"
in_seq = False #whether we are currently in a run of 0s
for i in range(R):
elem = obstacle_sequence & (1<<i)
if not in_seq and elem == 0:
in_seq = True
start_idx = i
elif in_seq and elem > 0:
in_seq = False
yield start_idx, i-start_idx
# after the loop if the last elements were 0s then yield the final sequence
if in_seq:
yield start_idx, R-start_idx
def place22blocks(left_obstacles, R):
# start by making a sequence of the same size as left_obstacles
gap_ranges = []
seq_filling_iterators = []
for idx_range, size in find_gaps(left_obstacles, R):
gap_ranges.append(idx_range)
seq_filling_iterators.append(obstacle_combos(size))
for list_of_obstacles_per_gap in itertools.product(*seq_filling_iterators):
yield sum(x<<i for i,x in zip(gap_ranges, list_of_obstacles_per_gap))
print("\n\n")
print(*map("{:09b}".format, place22blocks(0b000110000, 9)),sep="\n")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74694682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Draw Line between two Geo Points in JMapViewer I'm working with OpenStreet Maps in Java with JMap Viwer http://wiki.openstreetmap.org/wiki/JMapViewer I can load the maps and everything ok but I don't know how to draw a line between two points from a latitude and longitude.
Any body know the function to draw this kind of lines?
Thank you.
A: The addMapPolygon() method of JMapViewer works for this, but paintPolygon() silently rejects a polygon having fewer than three vertices. For a line between two points, just repeat the last Coordinate.
Coordinate one = new Coordinate(...);
Coordinate two = new Coordinate(...);
List<Coordinate> route = new ArrayList<Coordinate>(Arrays.asList(one, two, two));
map.addMapPolygon(new MapPolygonImpl(route));
A: I am also working on this software and using the JMapviewer.jar. Yet, I do not seem to have the addMapPolygon nor the MapPolygonImpl ... Is there a specific version I should be working with ? (I downloaded my version here: enter link description here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10744798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: C# Linq-to-SQL Insert row into datacontext without committing to database I'm writing this Web app that is associated with a Microsoft sql database.
I want the user to be able to insert rows, view rows, and then edit those rows on the page.
When the user clicks a submit button, I want to commit all of the changes that the user made to the database in one large transaction.
Now I have this System.Data.Linq.DataContext object and I'm trying to insert a row into it without submitting changes to the database.
how do i do this?
A: InsertOnSubmit shouldn't actually write anything until you call SubmitChanges(). Failing that, stick all your objects to add in a list or something, and iterate over them later to insert.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8882173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How to mount context-referenced Tomcat application with mod_jk? I have an WAR application running in Tomcat at /foo context, meaning that its URL is http://example.com:8080/foo. Now I'm trying to connect Apache HTTP Server to Tomcat through mod_jk. This is my workers.properties file:
worker.list=foo
worker.foo.port=8009
worker.foo.host=localhost
worker.foo.type=ajp13
worker.foo.mount=/foo/*
Works fine, but at this URL: http://example.com/foo. I would like it to be at http://example.com. What am I missing?
ps. This is my mod-jk.conf, which is included into httpd.conf:
LoadModule jk_module modules/mod_jk.so
JkWorkersFile /usr/local/tomcat/conf/workers.properties
<VirtualHost *:80>
ServerName foo.example.com
JkMount /* foo
</VirtualHost>
A: You basically have two options:
*
*Modify your Tomcat configuration to mount the WAR at the root. How this is done depends on how exactly you're deploying your application. This is the cleaner approach unless there's some preventing factor.
*Handle the problem on the Apache side by using mod_rewrite to rewrite URLs starting with / to /foo, at which point it will be passed through your JkMount to Tomcat
For the second option, your Apache configuration would look something like this:
# Turn on mod_rewrite
RewriteEngine On
# This is the rule. Use regexp to match any URL beginning with /, and rewrite it to
# /foo/remaining_part_of_URL. The [PT] (pass-through) is necessary to make rewritten
# requests go through JkMount
RewriteRule ^/(.*) /foo/$1 [PT]
# Forward all URLs starting with foo to Tomcat
JkMount /foo/* worker
(this isn't actually tested, hope it works as is!). You may also need to enable mod_rewrite in your Apache (check out your distribution, a mods-enabled directory might be the answer).
And if you need to know more about mod_rewrite (quite a powerful beast), go here:
http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html#rewriterule
A: Here is a Mod Rewrite Solution
WORKERS.PROPERTIES
worker.list=worker1
worker.worker1.port=8009
worker.worker1.host=localhost
worker.worker1.type=ajp13
worker.worker1.mount=/foo/* #THIS IS THE APP NAME: "FOO"
HTTPD.CONF
<VirtualHost *:80>
RewriteEngine On
RewriteRule ^/(.*)/Foo/$1 [PT]
ServerName example.com #DOMAIN NAME: "example.com"
ServerAlias www.example.com
JkMount /foo/* worker1
</VirtualHost>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5138865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Android OpenGL reading pixel color at the center of the screen I'm rendering a texture in OpenGL. I want to retrieve the pixel color value at the center of the screen.
ByteBuffer byteBuffer = ByteBuffer.allocate(4);
byteBuffer.order(ByteOrder.nativeOrder());
GLES20.glFinish();
GLES20.glReadPixels(0, 0, 1, 1, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, byteBuffer);
byte[] byteArray = new byte[4];
byteBuffer.get(byteArray);
int r = ((int) byteArray[0]) & 0xFF;
int g = ((int) byteArray[1]) & 0xFF;
int b = ((int) byteArray[2]) & 0xFF;
String key = r + " " + g + " " + b;
Log.i(TAG, key);
As a test, I'm rendering a red square to the center of the screen, and expect to log (255 0 0) but I only get back (255 0 0) when I render the entire screen red.
A: The coordinates/sizes passed to glReadPixels() are in window coordinates. The window coordinate system has its origin in the lower left corner of the window, with a unit of pixels.
This is not to be confused with the NDC (normalized device coordinates) system used for vertex coordinates, which has its origin in the center of the window, and has a range of [-1.0, 1.0] in both the x- and y-directions.
So in your example:
GLES20.glReadPixels(0, 0, 1, 1,
GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, byteBuffer);
you are reading one pixel in the lower left corner of the rendering surface. To read a pixel in the center, you need:
GLES20.glReadPixels(width / 2, height / 2, 1, 1,
GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, byteBuffer);
where width and height are the dimensions of the rendering surface in pixels.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34081833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to write Powershell script to identify any azure resource with a creation date in the last 30 days in multiple subscriptions how to identify all azure resources with a creation date in the last 30 days in multiple subscriptions using PowerShell script
A: Well, first you should note what you are using is a really old AzureRm module command, it was deprecated and will not be updated. So I recommend you to use the new Az module, you could refer to the doc to migrate Azure PowerShell from AzureRM to Az.
Then use the script below, it will get all the resources from all the subscriptions your logged user account/service principals can access.
$subs= Get-AzSubscription
foreach($sub in $subs){
Set-AzContext -Subscription $sub.Id -Tenant $sub.TenantId
Write-Host "login to subscription - "$sub.Name
$groups = (Get-AzResourceGroup).ResourceGroupName
foreach($group in $groups){
Get-AzResourceGroupDeployment -ResourceGroupName $group | Where-Object {$_.Timestamp -gt '12/15/2020'}
}
}
If you still want to use the old AzureRm module, then the script should be:
$subs= Get-AzureRmSubscription
foreach($sub in $subs){
Set-AzureRmContext -Subscription $sub.Id -Tenant $sub.TenantId
Write-Host "login to subscription - "$sub.Name
$groups = (Get-AzureRmResourceGroup).ResourceGroupName
foreach($group in $groups){
Get-AzureRmResourceGroupDeployment -ResourceGroupName $group | Where-Object {$_.Timestamp -gt '12/15/2020'}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65627056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: NHibernate/Hibernate - Forced to apply sorting twice on pagination I'm having an issue currently where I have to apply sorting twice in a query.
Since I want paginated results, I'm using a DetachedCriteria approach and using it as a Subquery for the main Criteria.
Issue is, that if I apply the sorting only on the DetachedCriteria, I don't get back the results sorted.
This is because the sql "IN" clause does not guarantee that the results will come back sorted.
So I need to apply the same sorting again on the main Criteria.
var detachedCriteria = DetachedCriteria.For<User>()
.SetProjection(Projections.Id())
.setMaxResults(20).setFirstResult(0)
.AddOrder(Order.Asc("Name"));
session.CreateCriteria<User>
.Add(Subqueries.PropertyIn("Id", detachedCriteria))
.AddOrder(Order.Asc("Name"))
.List();
This would work, if could instead apply the DetachedCriteria as a JOIN clause, but as far as I know this is not supported by NHibernate.
Does anybody know of a different approach?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32985921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Adjust the width of the mat-side-nav while it is open When the nav-bar is clicked open, the width of the nav-bar is to be adjusted automatically with the content.
<mat-sidenav #sidenav mode="side" class="primary-color main-sidenav nav-
shadow" opened="true" [@sidenavState]="sidenavState"
(@sidenavState.done)="endAnimation()" *ngIf="layout === 'modern' ||
forceModern">
....
</mat-sidenav>
When I set the width of the side-nav in SCSS as
.mat-side-nav{
width: auto !important
}
The nav-bar is opened by default without being clicked to open. Also it is not closed with the click
A: Your problem:
when you are doing the below:
.mat-side-nav{
width: auto !important
}
This is kind of hard coding the width to take whatever it contains.
Solution:
Find the class which is active while its open and set the width: auto, for that class.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53269760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why I can't insert new data in my database using SQLITE? public class SQLiteJDBCDriverConnection {
This block is to connect to sqlite database and create "warehouses" table with three columns.
public static Connection connect() {
Connection conn = null;
try {
// db parameters
String url = "jdbc:sqlite:chinook.db";
String sql = "CREATE TABLE IF NOT EXISTS warehouses (\n"
+ " id integer PRIMARY KEY,\n"
+ " name text NOT NULL,\n"
+ " capacity real\n"
+ ")";
// create a connection to the database
conn = DriverManager.getConnection(url);
//Create table
Statement state = conn.createStatement();
state.executeUpdate(sql);
System.out.println("Connection to SQLite has been established.");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
return conn;
}
This block is to create object with three parameters to insert new records for three columns.
public static void newItem(int id, String name, int capacity) {
Connection con = connect();
PreparedStatement state;
String sql = "INSERT INTO warehouses(id,name,capacity) VALUES(?,?,?)";
try {
state = con.prepareStatement(sql);
state.executeUpdate();
}catch(Exception e) {
}
}
This block executes the newItem function.
public static void main(String[] args) {
newItem(4009,"plywood",5000);
}
}
A: You do not set parameters to your SQL query.
After state = con.prepareStatement(sql); you need to set actual parameters using state.setXXX(index, value);
state = con.prepareStatement(sql);
state.setInt(1, id);
state.setString(2, name);
state.setInt(3, capacity);
state.executeUpdate();
And as mentioned in comments you need to at least add logging to your catch blocks. And connection and preparedStatement objects should be closed when are not needed anymore.
EDIT
In your connect method you close connection object in finally block and return closed connection. And then you try to use closed connection in your newItem() method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53010463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to tell a gem not to be installed on JRuby? How can I configure a gem so that it couldn't be installed on JRuby?
A: in *.gemspec:
s.platform = 'ruby'
possible platform values:
ruby
C Ruby (MRI) or Rubinius, but NOT Windows
ruby_18
ruby AND version 1.8
ruby_19
ruby AND version 1.9
mri
Same as ruby, but not Rubinius
mri_18
mri AND version 1.8
mri_19
mri AND version 1.9
rbx
Same as ruby, but only Rubinius (not MRI)
jruby
JRuby
mswin
Windows
mingw
Windows 'mingw32' platform (aka RubyInstaller)
mingw_18
mingw AND version 1.8
mingw_19
mingw AND version 1.9
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9363127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Clearing the screen for new graphics in Java (awt) I have this code which is basically a home menu with two clickable rectangles.
*
*Start Game
*Info
Start Game works fine.
Info is what is not really working. When pressed, the info screen will appear, but the home menu buttons will still be there though not visible (can be clicked).. it seems that when the info menu is appearing, the home menu buttons are not getting cleared.
Also, any point on the info menu is clickable and will show the home menu again. (not what intended, only the back buttons should do that).
How can I fix those problems ?
package test;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.Rectangle2D;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
public class HomeMenu extends JComponent implements MouseListener, MouseMotionListener {
private static final String GAME_TITLE = "BRICK DESTROY";
private static final String START_TEXT = "START";
private static final String INFO_TEXT = "INFO";
private static final String howtoPlay = """
1- Click Start\n
2- Choose the mode\n
3- Each mode has 3 levels\n
4- To play/pause press space, use 'A' and 'D' to move\n
5- To open pause menu press 'ESC'\n
6- To open DebugPanel press 'ALT-SHIFT-F1'""";
private static final String backText = "BACK";
private static final Color BORDER_COLOR = new Color(200,8,21); //Venetian Red
private static final Color DASH_BORDER_COLOR = new Color(255, 216, 0);//school bus yellow
private static final Color TEXT_COLOR = new Color(255, 255, 255);//white
private static final Color CLICKED_BUTTON_COLOR = Color.ORANGE.darker();;
private static final Color CLICKED_TEXT = Color.ORANGE.darker();
private static final int BORDER_SIZE = 5;
private static final float[] DASHES = {12,6};
private Rectangle menuFace;
private Rectangle infoFace;
private Rectangle startButton;
private Rectangle infoButton;
private Rectangle backButton;
private BasicStroke borderStoke;
private BasicStroke borderStoke_noDashes;
private Image img = Toolkit.getDefaultToolkit().createImage("1.jpeg");
private Font gameTitleFont;
private Font infoFont;
private Font buttonFont;
private Font howtoPlayFont;
private GameFrame owner;
private boolean startClicked;
private boolean infoClicked = false;
private boolean backClicked = false;
public HomeMenu(GameFrame owner,Dimension area){
this.setFocusable(true);
this.requestFocusInWindow();
this.addMouseListener(this);
this.addMouseMotionListener(this);
this.owner = owner;
menuFace = new Rectangle(new Point(0,0),area);
infoFace = new Rectangle(new Point(0,0),area);
this.setPreferredSize(area);
Dimension btnDim = new Dimension(area.width / 3, area.height / 12);
startButton = new Rectangle(btnDim);
infoButton = new Rectangle(btnDim);
backButton = new Rectangle(btnDim);
borderStoke = new BasicStroke(BORDER_SIZE,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND,0,DASHES,0);
borderStoke_noDashes = new BasicStroke(BORDER_SIZE,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
gameTitleFont = new Font("Calibri",Font.BOLD,28);
infoFont = new Font("Calibri",Font.BOLD,24);
buttonFont = new Font("Calibri",Font.BOLD,startButton.height-2);
howtoPlayFont = new Font("Calibri",Font.PLAIN,14);
}
public void paint(Graphics g){
drawMenu((Graphics2D)g);
}
public void drawMenu(Graphics2D g2d){
if(infoClicked) {
drawInfoMenu(g2d);
return;
}else{
drawContainer(g2d);
Color prevColor = g2d.getColor();
Font prevFont = g2d.getFont();
double x = menuFace.getX();
double y = menuFace.getY();
g2d.translate(x,y);
//methods calls
drawText(g2d);
drawButton(g2d);
//end of methods calls
g2d.translate(-x,-y);
g2d.setFont(prevFont);
g2d.setColor(prevColor);
}
Toolkit.getDefaultToolkit().sync();
}
private void drawContainer(Graphics2D g2d){
Color prev = g2d.getColor();
//g2d.setColor(BG_COLOR);
g2d.drawImage(img,0,0,menuFace.width,menuFace.height,this);
//g2d.fill(menuFace);
Stroke tmp = g2d.getStroke();
g2d.setStroke(borderStoke_noDashes);
g2d.setColor(DASH_BORDER_COLOR);
g2d.draw(menuFace);
g2d.setStroke(borderStoke);
g2d.setColor(BORDER_COLOR);
g2d.draw(menuFace);
g2d.setStroke(tmp);
g2d.setColor(prev);
}
private void drawText(Graphics2D g2d){
g2d.setColor(TEXT_COLOR);
FontRenderContext frc = g2d.getFontRenderContext();
Rectangle2D gameTitleRect = gameTitleFont.getStringBounds(GAME_TITLE,frc);
int sX,sY;
sY = (int)(menuFace.getHeight() / 4);
sX = (int)(menuFace.getWidth() - gameTitleRect.getWidth()) / 2;
sY += (int) gameTitleRect.getHeight() * 1.1;//add 10% of String height between the two strings
g2d.setFont(gameTitleFont);
g2d.drawString(GAME_TITLE,sX,sY);
}
private void drawButton(Graphics2D g2d){
FontRenderContext frc = g2d.getFontRenderContext();
Rectangle2D txtRect = buttonFont.getStringBounds(START_TEXT,frc);
Rectangle2D mTxtRect = buttonFont.getStringBounds(INFO_TEXT,frc);
g2d.setFont(buttonFont);
int x = (menuFace.width - startButton.width) / 2;
int y =(int) ((menuFace.height - startButton.height) * 0.5);
startButton.setLocation(x,y);
x = (int)(startButton.getWidth() - txtRect.getWidth()) / 2;
y = (int)(startButton.getHeight() - txtRect.getHeight()) / 2;
x += startButton.x;
y += startButton.y + (startButton.height * 0.9);
if(startClicked){
Color tmp = g2d.getColor();
g2d.setColor(CLICKED_BUTTON_COLOR);
g2d.draw(startButton);
g2d.setColor(CLICKED_TEXT);
g2d.drawString(START_TEXT,x,y);
g2d.setColor(tmp);
}
else{
g2d.draw(startButton);
g2d.drawString(START_TEXT,x,y);
}
x = startButton.x;
y = startButton.y;
y *= 1.3;
infoButton.setLocation(x,y);
x = (int)(infoButton.getWidth() - mTxtRect.getWidth()) / 2;
y = (int)(infoButton.getHeight() - mTxtRect.getHeight()) / 2;
x += infoButton.getX();
y += infoButton.getY() + (startButton.height * 0.9);
if(infoClicked){
Color tmp = g2d.getColor();
g2d.setColor(CLICKED_BUTTON_COLOR);
g2d.draw(infoButton);
g2d.setColor(CLICKED_TEXT);
g2d.drawString(INFO_TEXT,x,y);
g2d.setColor(tmp);
}
else{
g2d.draw(infoButton);
g2d.drawString(INFO_TEXT,x,y);
}
}
private void drawInfoMenu(Graphics2D g2d){
FontRenderContext frc = g2d.getFontRenderContext();
Rectangle2D infoRec = infoFont.getStringBounds(INFO_TEXT,frc);
Color prev = g2d.getColor();
Stroke tmp = g2d.getStroke();
g2d.setStroke(borderStoke_noDashes);
g2d.setColor(DASH_BORDER_COLOR);
g2d.draw(infoFace);
g2d.setStroke(borderStoke);
g2d.setColor(BORDER_COLOR);
g2d.draw(infoFace);
g2d.fillRect(0,0,infoFace.width,infoFace.height);
g2d.setStroke(tmp);
g2d.setColor(prev);
g2d.setColor(TEXT_COLOR);
int sX,sY;
sY = (int)(infoFace.getHeight() / 15);
sX = (int)(infoFace.getWidth() - infoRec.getWidth()) / 2;
sY += (int) infoRec.getHeight() * 1.1;//add 10% of String height between the two strings
g2d.setFont(infoFont);
g2d.drawString(INFO_TEXT,sX,sY);
TextLayout layout = new TextLayout(howtoPlay, howtoPlayFont, frc);
String[] outputs = howtoPlay.split("\n");
for(int i=0; i<outputs.length; i++) {
g2d.setFont(howtoPlayFont);
g2d.drawString(outputs[i], 40, (int) (80 + i * layout.getBounds().getHeight() + 0.5));
}
backButton.setLocation(getWidth()/3,getHeight()-50);
int x = (int)(backButton.getWidth() - infoRec.getWidth()) / 2;
int y = (int)(backButton.getHeight() - infoRec.getHeight()) / 2;
x += backButton.x+11;
y += backButton.y + (layout.getBounds().getHeight() * 1.35);
backButton.setLocation(getWidth()/3,getHeight()-50);
if(backClicked){
Color tmp1 = g2d.getColor();
g2d.setColor(CLICKED_BUTTON_COLOR);
g2d.draw(backButton);
g2d.setColor(CLICKED_TEXT);
g2d.drawString(backText,x,y);
g2d.setColor(tmp1);
infoClicked = false;
repaint();
}
else{
g2d.draw(backButton);
g2d.drawString(backText,x,y);
}
}
@Override
public void mouseClicked(MouseEvent mouseEvent) {
Point p = mouseEvent.getPoint();
if(startButton.contains(p)){
owner.enableGameBoard();
}
else if(infoButton.contains(p)){
infoClicked = true;
}
else if(backButton.contains(p)){
infoClicked = false;
}
repaint();
}
@Override
public void mousePressed(MouseEvent mouseEvent) {
Point p = mouseEvent.getPoint();
if(startButton.contains(p)){
startClicked = true;
repaint(startButton.x,startButton.y,startButton.width+1,startButton.height+1);
}
else if(infoButton.contains(p)){
infoClicked = true;
}
else if(backButton.contains(p)){
infoClicked = false;
}
repaint();
}
@Override
public void mouseReleased(MouseEvent mouseEvent) {
if(startClicked){
startClicked = false;
repaint(startButton.x,startButton.y,startButton.width+1,startButton.height+1);
}
else if(infoClicked){
infoClicked = false;
}
else if(backClicked){
infoClicked = true;
}
repaint();
}
@Override
public void mouseEntered(MouseEvent mouseEvent) {
}
@Override
public void mouseExited(MouseEvent mouseEvent) {
}
@Override
public void mouseDragged(MouseEvent mouseEvent) {
}
@Override
public void mouseMoved(MouseEvent mouseEvent) {
Point p = mouseEvent.getPoint();
if(startButton.contains(p) || infoButton.contains(p) || backButton.contains(p)) {
this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
else {
this.setCursor(Cursor.getDefaultCursor());
}
}
}
Here are the images of both windows
main menu
info menu, pressing anywhere = back to home menu, pressing roughly in the middle = start game or back to main menu too
A: First read, Performing Custom Painting and Painting in AWT and Swing to get a better understanding how painting in Swing works and how you're suppose to work with it.
But I already have ...
public void paint(Graphics g){
drawMenu((Graphics2D)g);
}
would suggest otherwise. Seriously, go read those links so you understand all the issues that the above decision is going to create for you.
You're operating in a OO language, you need to take advantage of that and decouple your code and focus on the "single responsibility" principle.
I'm kind of tired of talking about it, so you can do some reading:
*
*https://softwareengineering.stackexchange.com/questions/244476/what-is-decoupling-and-what-development-areas-can-it-apply-to
*Cohesion and Decoupling, what do they represent?
*Single Responsibility Principle
*Single Responsibility Principle in Java with Examples
*SOLID Design Principles Explained: The Single Responsibility Principle
These are basic concepts you really need to understand as they will make your live SOOO much easier and can be applied to just about any language.
As an example, from your code...
public HomeMenu(GameFrame owner,Dimension area){
//...
this.setPreferredSize(area);
There is no good reason (other than laziness (IMHO)) that any caller should be telling a component what size it should be, that's not their responsibility. It's the responsibility of the component to tell the parent container how big it would like to be and for the parent component to figure out how it's going to achieve that (or ignore it as the case may be).
The "basic" problem you're having is a simple one. Your "God" class is simply trying to do too much (ie it's taken on too much responsibility). Now we "could" add a dozen or more flags into the code to compensate for this, which is just going to increase the coupling and complexity, making it harder to understand and maintain, or we can take a step back, break it down into individual areas of responsibility and build the solution around those, for example...
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Stroke;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.add(new HomePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class HomePane extends JPanel {
public HomePane() {
setLayout(new BorderLayout());
navigateToMenu();
}
@Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
protected void navigateToMenu() {
removeAll();
HomeMenuPane pane = new HomeMenuPane(new HomeMenuPane.NavigationListener() {
@Override
public void navigateToInfo(HomeMenuPane source) {
HomePane.this.navigateToInfo();
}
@Override
public void navigateToStartGame(HomeMenuPane source) {
startGame();
}
});
add(pane);
revalidate();
repaint();
}
protected void navigateToInfo() {
removeAll();
HowToPlayPane pane = new HowToPlayPane(new HowToPlayPane.NavigationListener() {
@Override
public void navigateBack(HowToPlayPane source) {
navigateToMenu();
}
});
add(pane);
revalidate();
repaint();
}
protected void startGame() {
removeAll();
add(new JLabel("This is pretty awesome, isn't it!", JLabel.CENTER));
revalidate();
repaint();
}
}
public abstract class AbstractBaseMenuPane extends JPanel {
protected static final Color BORDER_COLOR = new Color(200, 8, 21); //Venetian Red
protected static final Color DASH_BORDER_COLOR = new Color(255, 216, 0);//school bus yellow
protected static final Color TEXT_COLOR = new Color(255, 255, 255);//white
protected static final Color CLICKED_BUTTON_COLOR = Color.ORANGE.darker();
protected static final Color CLICKED_TEXT = Color.ORANGE.darker();
protected static final int BORDER_SIZE = 5;
protected static final float[] DASHES = {12, 6};
private Rectangle border;
private BasicStroke borderStoke;
private BasicStroke borderStoke_noDashes;
private BufferedImage backgroundImage;
public AbstractBaseMenuPane() {
borderStoke = new BasicStroke(BORDER_SIZE, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, DASHES, 0);
borderStoke_noDashes = new BasicStroke(BORDER_SIZE, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
border = new Rectangle(new Point(0, 0), getPreferredSize());
// You are now responsible for filling the background
setOpaque(false);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
BufferedImage backgroundImage = getBackgroundImage();
if (backgroundImage != null) {
g2d.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), this);
}
Color prev = g2d.getColor();
Stroke tmp = g2d.getStroke();
g2d.setStroke(borderStoke_noDashes);
g2d.setColor(DASH_BORDER_COLOR);
g2d.draw(border);
g2d.setStroke(borderStoke);
g2d.setColor(BORDER_COLOR);
g2d.draw(border);
g2d.dispose();
}
public void setBackgroundImage(BufferedImage backgroundImage) {
this.backgroundImage = backgroundImage;
repaint();
}
public BufferedImage getBackgroundImage() {
return backgroundImage;
}
}
public class HomeMenuPane extends AbstractBaseMenuPane {
public static interface NavigationListener {
public void navigateToInfo(HomeMenuPane source);
public void navigateToStartGame(HomeMenuPane source);
}
private static final String GAME_TITLE = "BRICK DESTROY";
private static final String START_TEXT = "START";
private static final String INFO_TEXT = "INFO";
private Rectangle startButton;
private Rectangle infoButton;
private Font gameTitleFont;
private Font buttonFont;
// Don't do this, this just sucks (for so many reasons)
// Use ImageIO.read instead and save yourself a load of frustration
//private Image img = Toolkit.getDefaultToolkit().createImage("1.jpeg");
private Point lastClickPoint;
private NavigationListener navigationListener;
public HomeMenuPane(NavigationListener navigationListener) {
this.navigationListener = navigationListener;
try {
setBackgroundImage(ImageIO.read(getClass().getResource("/images/BrickWall.jpg")));
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
this.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent mouseEvent) {
Point p = mouseEvent.getPoint();
lastClickPoint = p;
if (startButton.contains(p)) {
peformStartGameAction();
} else if (infoButton.contains(p)) {
performInfoAction();
}
repaint();
}
@Override
public void mouseReleased(MouseEvent mouseEvent) {
lastClickPoint = null;
repaint();
}
});
this.addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseMoved(MouseEvent mouseEvent) {
Point p = mouseEvent.getPoint();
if (startButton.contains(p) || infoButton.contains(p)) {
setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
} else {
setCursor(Cursor.getDefaultCursor());
}
}
});
Dimension area = getPreferredSize();
Dimension btnDim = new Dimension(area.width / 3, area.height / 12);
startButton = new Rectangle(btnDim);
infoButton = new Rectangle(btnDim);
gameTitleFont = new Font("Calibri", Font.BOLD, 28);
buttonFont = new Font("Calibri", Font.BOLD, startButton.height - 2);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
Color prevColor = g2d.getColor();
Font prevFont = g2d.getFont();
//methods calls
drawText(g2d);
drawButton(g2d);
//end of methods calls
g2d.setFont(prevFont);
g2d.setColor(prevColor);
g2d.dispose();
}
private void drawText(Graphics2D g2d) {
g2d.setColor(TEXT_COLOR);
FontRenderContext frc = g2d.getFontRenderContext();
Rectangle2D gameTitleRect = gameTitleFont.getStringBounds(GAME_TITLE, frc);
int sX, sY;
sY = (int) (getHeight() / 4);
sX = (int) (getWidth() - gameTitleRect.getWidth()) / 2;
sY += (int) gameTitleRect.getHeight() * 1.1;//add 10% of String height between the two strings
g2d.setFont(gameTitleFont);
g2d.drawString(GAME_TITLE, sX, sY);
}
private void drawButton(Graphics2D g2d) {
FontRenderContext frc = g2d.getFontRenderContext();
Rectangle2D txtRect = buttonFont.getStringBounds(START_TEXT, frc);
Rectangle2D mTxtRect = buttonFont.getStringBounds(INFO_TEXT, frc);
g2d.setFont(buttonFont);
int x = (getWidth() - startButton.width) / 2;
int y = (int) ((getHeight() - startButton.height) * 0.5);
startButton.setLocation(x, y);
x = (int) (startButton.getWidth() - txtRect.getWidth()) / 2;
y = (int) (startButton.getHeight() - txtRect.getHeight()) / 2;
x += startButton.x;
y += startButton.y + (startButton.height * 0.9);
if (lastClickPoint != null && startButton.contains(lastClickPoint)) {
Color tmp = g2d.getColor();
g2d.setColor(CLICKED_BUTTON_COLOR);
g2d.draw(startButton);
g2d.setColor(CLICKED_TEXT);
g2d.drawString(START_TEXT, x, y);
g2d.setColor(tmp);
} else {
g2d.draw(startButton);
g2d.drawString(START_TEXT, x, y);
}
x = startButton.x;
y = startButton.y;
y *= 1.3;
infoButton.setLocation(x, y);
x = (int) (infoButton.getWidth() - mTxtRect.getWidth()) / 2;
y = (int) (infoButton.getHeight() - mTxtRect.getHeight()) / 2;
x += infoButton.getX();
y += infoButton.getY() + (startButton.height * 0.9);
if (lastClickPoint != null && infoButton.contains(lastClickPoint)) {
Color tmp = g2d.getColor();
g2d.setColor(CLICKED_BUTTON_COLOR);
g2d.draw(infoButton);
g2d.setColor(CLICKED_TEXT);
g2d.drawString(INFO_TEXT, x, y);
g2d.setColor(tmp);
} else {
g2d.draw(infoButton);
g2d.drawString(INFO_TEXT, x, y);
}
}
protected void peformStartGameAction() {
navigationListener.navigateToStartGame(this);
}
protected void performInfoAction() {
navigationListener.navigateToInfo(this);
}
}
public class HowToPlayPane extends AbstractBaseMenuPane {
public static interface NavigationListener {
public void navigateBack(HowToPlayPane source);
}
private static final String HOW_TO_PLAY_TEXT = """
1- Click Start\n
2- Choose the mode\n
3- Each mode has 3 levels\n
4- To play/pause press space, use 'A' and 'D' to move\n
5- To open pause menu press 'ESC'\n
6- To open DebugPanel press 'ALT-SHIFT-F1'""";
private static final String BACK_TEXT = "BACK";
private static final String INFO_TEXT = "INFO";
private Rectangle backButton;
private boolean backClicked = false;
private Font infoFont;
private Font howtoPlayFont;
private NavigationListener navigationListener;
public HowToPlayPane(NavigationListener navigationListener) {
this.navigationListener = navigationListener;
this.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent mouseEvent) {
Point p = mouseEvent.getPoint();
if (backButton.contains(p)) {
backClicked = true;
repaint();
performBackAction();
}
}
@Override
public void mouseReleased(MouseEvent e) {
backClicked = false;
}
});
this.addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseMoved(MouseEvent mouseEvent) {
Point p = mouseEvent.getPoint();
if (backButton.contains(p)) {
setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
} else {
setCursor(Cursor.getDefaultCursor());
}
}
});
Dimension btnDim = new Dimension(getPreferredSize().width / 3, getPreferredSize().height / 12);
backButton = new Rectangle(btnDim);
infoFont = new Font("Calibri", Font.BOLD, 24);
howtoPlayFont = new Font("Calibri", Font.PLAIN, 14);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(BORDER_COLOR);
g2d.fillRect(0, 0, getWidth(), getHeight());
FontRenderContext frc = g2d.getFontRenderContext();
Rectangle2D infoRec = infoFont.getStringBounds(INFO_TEXT, frc);
//
// Color prev = g2d.getColor();
//
// Stroke tmp = g2d.getStroke();
//
// g2d.setStroke(borderStoke_noDashes);
// g2d.setColor(DASH_BORDER_COLOR);
// g2d.draw(infoFace);
//
// g2d.setStroke(borderStoke);
// g2d.setColor(BORDER_COLOR);
// g2d.draw(infoFace);
//
// g2d.fillRect(0, 0, infoFace.width, infoFace.height);
//
// g2d.setStroke(tmp);
//
// g2d.setColor(prev);
//
g2d.setColor(TEXT_COLOR);
int sX, sY;
sY = (int) (getHeight() / 15);
sX = (int) (getWidth() - infoRec.getWidth()) / 2;
sY += (int) infoRec.getHeight() * 1.1;//add 10% of String height between the two strings
g2d.setFont(infoFont);
g2d.drawString(INFO_TEXT, sX, sY);
TextLayout layout = new TextLayout(HOW_TO_PLAY_TEXT, howtoPlayFont, frc);
String[] outputs = HOW_TO_PLAY_TEXT.split("\n");
for (int i = 0; i < outputs.length; i++) {
g2d.setFont(howtoPlayFont);
g2d.drawString(outputs[i], 40, (int) (80 + i * layout.getBounds().getHeight() + 0.5));
}
backButton.setLocation(getWidth() / 3, getHeight() - 50);
int x = (int) (backButton.getWidth() - infoRec.getWidth()) / 2;
int y = (int) (backButton.getHeight() - infoRec.getHeight()) / 2;
x += backButton.x + 11;
y += backButton.y + (layout.getBounds().getHeight() * 1.35);
backButton.setLocation(getWidth() / 3, getHeight() - 50);
if (backClicked) {
Color tmp1 = g2d.getColor();
g2d.setColor(CLICKED_BUTTON_COLOR);
g2d.draw(backButton);
g2d.setColor(CLICKED_TEXT);
g2d.drawString(BACK_TEXT, x, y);
g2d.setColor(tmp1);
repaint();
} else {
g2d.draw(backButton);
g2d.drawString(BACK_TEXT, x, y);
}
g2d.dispose();
}
protected void performBackAction() {
navigationListener.navigateBack(this);
}
}
}
Now, this example makes use of components to present different views (it even has a nice abstract implementation to allow for code re-use ), but it occurs to me, that, if you "really" wanted to, you could have a series of "painter" classes, which could be used to delegate the painting of the current state to, and mouse clicks/movements could be delegated to, meaning you could have a single component, which would simple delegate the painting (via the paintComponent method) to which ever painter is active.
And, wouldn't you know it, they have a design principle for that to, the Delegation Pattern
The above example also makes use of the observer pattern, so you might want to have a look into that as well
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70162935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: android: how to hide bottom buttons on dialog fullscreen I'm trying to hide navigation buttons when a dialog is shown fullscreen.
I've manage to do it following this example: Android fullscreen dialog
however, whenever i touch a button they appear again.
is there any way to hide them properly?
thanks
A: The following snippet hides the navigation bar and status bar:
window.decorView.apply {
// Hide both the navigation bar and the status bar.
// SYSTEM_UI_FLAG_FULLSCREEN is only available on Android 4.1 and higher, but as
// a general rule, you should design your app to hide the status bar whenever you
// hide the navigation bar.
systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN
}
From https://developer.android.com/training/system-ui/navigation
Nonetheless for your case you need two things to happen.
*
*First, set windowFullScreen to true to allow the dialog to paint every pixel in the screen. (i.e. Use any FullScreen theme).
*Then, on you dialog, set the systemUiVisibility to View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION.
This will stop the navigationBar from ever showing until you reset the flags or dismiss the dialog.
The complete snippet:
class SomeActivity {
fun showDialog() {
FullScrenDialog()
.apply {
setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_NoTitleBar_Fullscreen)
}
.show(supportFragmentManager, "TAG")
}
}
class FullScrenDialog : DialogFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
dialog.window?.decorView?.systemUiVisibility = View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
return inflater.inflate(R.layout.dialog, container)
}
}
A: Please try below code for dialog:
final Dialog dialog = new Dialog(this);
dialog.setCancelable(false);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.getWindow().setGravity(Gravity.CENTER);
dialog.setContentView(R.layout.dialog_logout);
Window window = dialog.getWindow();
window.setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN;
window.getDecorView().setSystemUiVisibility(uiOptions);
dialog.show();
Output is:
I hope it works for you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59050705",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I use array using "row index" in python? I made code in python
There's so many arrays, what I want to do is
extract value of arrays and add it to array_matrix in row
and make a label too
and every circle row = row + 1
This is some part of my code,
I know the form of
array_matrix[row,0:3] = array1(u) and label_matrix(row,:) =[1 0]
isn't correct.
Please let me know what to change.
row = 0
array_matrix = []
for n in range(0,64,8):
array1.append(dct_temp[0,1])
array2.append(dct_temp[1,0])
array3.append(dct_temp[0,2])
array4.append(dct_temp[1,1])
u = (index-1,index+1,1) # index = index of max value of array
array_matrix[row,0:3] = array1(u)
array_matrix[row,4:7] = array2(u)
array_matrix[row,8:11] = array3(u)
array_matrix[row,12:15] = array4(u)
label_matrix(row,:) =[0 1]
row = row + 1
A: You could use a dict
dict = {"labelA",arrayVal}
list1 = [1, 2, 3, 4, 5]
list2 = [123, 234, 456]
d = {'a': [], 'b': []}
d['a'].append(list1)
d['a'].append(list2)
print d['a']
For your array you can use a notation like
array[FROM INDEX ROW:TOINDEX ROW, :]
The : means take all cols
FROM INDEX ROW:TOINDEX ROW means take all values from the FROM INDEX upto the TOINDEX.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47278540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: perl threading problem I'm writing a multithreaded website uptime checker in perl, and here is the basic code so far (includes only threading part):
#!/usr/bin/perl
use LWP::UserAgent;
use Getopt::Std;
use threads;
use threads::shared;
my $maxthreads :shared = 50;
my $threads :shared = 0;
print "Website Uptime Checker\n";
my $infilename = $ARGV[0];
chomp($infilename);
open(INFILE, $infilename);
my $outfilename = $ARGV[1];
chomp($outfilename);
open(OUTFILE, ">" . $outfilename);
OUTFILE->autoflush(1);
while ($site = <INFILE>)
{
chomp($site);
while (1)
{
if ($threads < $maxthreads)
{
$threads++;
my $thr = threads->create(\&check_site, $site);
$thr->detach();
last;
}
else
{
sleep(1);
}
}
}
while ($threads > 0)
{
sleep(1);
}
sub check_site
{
$server = $_[0];
print "$server\n";
$threads--;
}
It gives an error after a while:
Can't call method "detach" on an undefined value at C:\perl\webchecker.pl line 28, line 245.
What causes this error? I know it is at detach, but what am I doing wrong in my code? Windows shows lots of free memory, so it should not be the computer running out of memory, this error occurs even if I set $maxthreads as low as 10 or possibly even lower.
A: The specific issue is that thread->create is failing to create a thread and so it is returning undef. You should check the value of thr before calling detach if you want your code to be more robust.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3034048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to implement email for your apps in xcode? I tried to implement 'mail composer' (sample code from dev) to my apps. They are a lot of hard coded in the sample code. For example: sent to recipient - [email protected]. I want to leave it blank like @"", however it automatically prefix comma in front of the email address. I also have other concern, based on apple DEV readme.txt, launchMailAppOnDevice will be triggered if displayComposerSheet is failed. Should I replace all hardcoded in launchMailAppOnDevice and how to do it?
Please advise.
-(IBAction)showPicker:(id)sender
{
// This sample can run on devices running iPhone OS 2.0 or later
// The MFMailComposeViewController class is only available in iPhone OS 3.0 or later.
// So, we must verify the existence of the above class and provide a workaround for devices running
// earlier versions of the iPhone OS.
// We display an email composition interface if MFMailComposeViewController exists and the device can send emails.
// We launch the Mail application on the device, otherwise.
Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
if (mailClass != nil)
{
// We must always check whether the current device is configured for sending emails
if ([mailClass canSendMail])
{
[self displayComposerSheet];
}
else
{
[self launchMailAppOnDevice];
}
}
else
{
[self launchMailAppOnDevice];
}
}
// Displays an email composition interface inside the application. Populates all the Mail fields.
-(void)displayComposerSheet
{
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:@"Visit my new apps in app store!"];
// Set up recipients
NSArray *toRecipients = [NSArray arrayWithObject:@"[email protected]"];
[picker setToRecipients:toRecipients];
//Replace the email body with the content from my textview
[picker setMessageBody:TextView.text isHTML:NO];
[self presentModalViewController:picker animated:YES];
[picker release];
}
// Launches the Mail application on the device.
-(void)launchMailAppOnDevice
{
NSString *recipients = @"mailto:[email protected][email protected],[email protected]&subject=Hello from California!";
NSString *body = @"&body=It is raining in sunny California!";
NSString *email = [NSString stringWithFormat:@"%@%@", recipients, body];
email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}
A: Did you implement the mail class in your .h files
A: Replace your hard coded values in
"launchMailAppOnDevice".. it works for mine
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6003948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Searching for file using ref number I am trying to write a program that when prompted the user enters a Ref number and the program searches for the file which contains this ref number within it. Few things first:
The files all end with a .dpt extension and look like this:
PX12RUJ
PX12RUR
PX12RUV
#PX12RUU
PX12WLJ
#PX12WLL
PX12WLK
PX12RUW
WN14YGV
WN14YGY
Once I have found the file I need to read its contents into an array ignoring all lines that start with a '#'.
EDIT: Code for search but output is blank, grep within linux returns correct file test.dpt
#!/usr/bin/python
import subprocess
a = subprocess.Popen(("grep -l PX12WLK /shares/MILKLINK/PPdir/*/*.dpt"),shell=True, stdout = subprocess.PIPE)
output = a.communicate()[0]
print output
EDIT 2: Sorted it in the end for anyone interested here's how:
#!/usr/bin/python
from subprocess import Popen, PIPE, call
s_REG=raw_input('Please enter Reg number: ')
a = Popen(["grep -l %s /shares/MILKLINK/PPdir/*/*.dpt" %s_REG],shell=True, stdout = PIPE)
FILE_DIR = a.communicate()[0]
FILE_DIR=FILE_DIR.rstrip('\n')
FILE=open("%s" %FILE_DIR , 'r')
# Read File into array
LINES = FILE.read().split('\n')
# Remove Blank Lines and whitespace
LINES = filter(None, LINES)
# Ignore any lines that have been commented out
LINES = filter(lambda x: not x.startswith('#'), LINES)
FILE.close()
# Call the CrossRef Processor for each Reg to make sure for no differences
for I in range(len(LINES)):
call(["/shares/optiload/prog/indref.sh", "%s" %LINES[I]])
A: #!/usr/bin/python
from subprocess import Popen, PIPE, call
s_REG=raw_input('Please enter Reg number: ')
a = Popen(["grep -l %s /shares/MILKLINK/PPdir/*/*.dpt" %s_REG],shell=True, stdout = PIPE)
FILE_DIR = a.communicate()[0]
FILE_DIR=FILE_DIR.rstrip('\n')
FILE=open("%s" %FILE_DIR , 'r')
# Read File into array
LINES = FILE.read().split('\n')
# Remove Blank Lines and whitespace
LINES = filter(None, LINES)
# Ignore any lines that have been commented out
LINES = filter(lambda x: not x.startswith('#'), LINES)
FILE.close()
# Call the CrossRef Processor for each Reg to make sure for no differences
for I in range(len(LINES)):
call(["/shares/optiload/prog/indref.sh", "%s" %LINES[I]])
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27374792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Refit upload file from Api to Api I am trying to upload an image from one Asp net core backend to an other via refit.
await _repository.UploadImageAsync(userId,
new StreamPart(file.OpenReadStream(), file.FileName, file.ContentType), extension);
The Api
[Put("/image/{userId}")]
Task<Guid> UploadImageAsync(Guid userId, StreamPart stream, string extension);
The receiving Controller
[HttpPut("image/{userId}")]
public async Task<IActionResult> UploadImageAsync([FromRoute] Guid userId, StreamPart stream, string extension)
{
return await RunAsync(async () =>
{
var id = await _userImageManager.UploadImageAsync(userId, stream.Value, extension);
return Ok(id);
});
}
As soon as I run this i get the following exception:
Newtonsoft.Json.JsonSerializationException: Error getting value from 'ReadTimeout' on 'Microsoft.AspNetCore.Http.ReferenceReadStream'.
---> System.InvalidOperationException: Timeouts are not supported on this stream.
at System.IO.Stream.get_ReadTimeout()
at lambda_method(Closure , Object )
at Newtonsoft.Json.Serialization.ExpressionValueProvider.GetValue(Object target)
--- End of inner exception stack trace ---
at Newtonsoft.Json.Serialization.ExpressionValueProvider.GetValue(Object target)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)
at Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
at Newtonsoft.Json.JsonConvert.SerializeObjectInternal(Object value, Type type, JsonSerializer jsonSerializer)
at Newtonsoft.Json.JsonConvert.SerializeObject(Object value, Type type, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.SerializeObject(Object value, JsonSerializerSettings settings)
at Refit.JsonContentSerializer.SerializeAsync[T](T item) in d:\a\1\s\Refit\JsonContentSerializer.cs:line 34
at Refit.RequestBuilderImplementation.<>c__DisplayClass17_0.<<BuildRequestFactoryForMethod>b__0>d.MoveNext() in d:\a\1\s\Refit\RequestBuilderImplementation.cs:line 546
--- End of stack trace from previous location where exception was thrown ---
at Refit.RequestBuilderImplementation.<>c__DisplayClass14_0`2.<<BuildCancellableTaskFuncForMethod>b__0>d.MoveNext() in d:\a\1\s\Refit\RequestBuilderImplementation.cs:line 243
I tried going the way described here but had no success. Is there anything I did wrong?
EDIT
Based on @TomO answer I edited my code, but I still get null for stream:
Api 1 (the sending part to Api 2):
public async Task<Guid> UploadImageAsync(Guid userId, IFormFile file)
{
...
var stream = file.OpenReadStream();
var streamPart = new StreamPart(stream, file.FileName, file.ContentType);
var response = await _repository.UploadImageAsync(userId,
streamPart, extension);
...
}
Api 2 (The receiver):
[HttpPost("image/{userId}")]
public async Task<IActionResult> UploadImageAsync([FromRoute] Guid userId, string description, IFormFile stream, string extension)
{
...
}
The Refit Api:
[Multipart]
[Post("/image/{userId}")]
Task<Guid> UploadImageAsync(Guid userId, [AliasAs("Description")] string description, [AliasAs("File")] StreamPart stream, string extension);
A: I think the documentation (and the solution linked in the question) give good guidance. But here's what I got to work, anyhow:
Receiving API endpoint:
[HttpPost]
[Route("{*filePath:regex(^.*\\.[[^\\\\/]]+[[A-Za-z0-9]]$)}")]
public async Task<IActionResult> AddFile([FromRoute] AddFileRequest request,
[FromForm] AddFileRequestDetails body,
CancellationToken cancellationToken)
And the corresponding refit client call:
[Multipart]
[Post("/{**filePath}")]
Task AddFile(string filePath, [AliasAs("Description")] string description, [AliasAs("File")] StreamPart filepart);
The important thing here is that ALL of the member properties of the Form body(not including file) have to be decorated with the "AliasAs" attribute.
Calling on the sending side:
System.IO.Stream FileStream = request.File.OpenReadStream();
StreamPart sp = new StreamPart(FileStream, request.FileName);
try
{
await _filesClient.AddFile(request.FilePath, request.Description, sp);
}
catch (ApiException ae)
{
...
throw new Exception("Refit FileClient API Exception", ae);
}
Hope this helps the next person...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60565664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ng-bind-html is not able to bind text and image url together I am trying to use some string and a image together in ng-bind-html tag in AngularJS but it is giving error so far what i did is
<div class="row">
<span data-ng-bind-html="question"></span>
</div>
If only string value is coming or only image url is coming then it works fine but when string + image url both are coming it does not display anything and it thrown error(404) can not find resource.
This value is coming from DB which will assign to question variable
"This is Instruction for below question" http://localhost:8080/OnlineExam/static/css/question_images/ tid_27-8-16_10AM_qno_25.png
A:
var app = angular.module("exApp",["ngSanitize"]);
app.controller('ctrl', function($scope, $sce){
$scope.image = $sce.trustAsHtml('<img src="http://i67.tinypic.com/s6rmeo.jpg" style="width:200px;height:200px">');
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-sanitize.min.js"></script>
<body ng-app="exApp">
<div ng-controller="ctrl">
<span ng-bind-html="image"></span>
</div>
</body>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44391255",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get process name in an injected dll? I have this basic internal dll:
#include "pch.h"
DWORD WINAPI HackThread(HMODULE hModule)
{
uintptr_t moduleBase = (uintptr_t)GetModuleHandle(L"Mainmodule123.exe");
AllocConsole();
FILE* f;
freopen_s(&f, "CONOUT$", "w", stdout);
std::cout << "Injected" << std::endl;
while (!GetAsyncKeyState(VK_END) & 1) {
Sleep(10)
}
fclose(f);
FreeConsole();
FreeLibraryAndExitThread(hModule, 0);
return 0;
}
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
{
CloseHandle(CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)HackThread, hModule, 0, nullptr));
}
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
I want to get a handle to the main module of the application, for example: GetModuleHandle(L"Mainmodule123.exe")
The problem, is that this application is changing the module numbers randomly.
The main module name is the same as the process name. So I need to detect the process name that I'm attached to.
How can I get the process name I'm attached to in an internal dll?
A: You can pass NULL for the lpModuleName parameter into GetModuleHandle:
If this parameter is NULL, GetModuleHandle returns a handle to the file used to create the calling process (.exe file).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72832953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to see if a .NET program is running Is it possible to determine if a Microsoft .NET program is running on a windows computer?
A: The following will return true if there is one or more processes running that have the supplied name.
public bool IsProcessRunning(string processName)
{
return Process.GetProcessesByName(processName).Length != 0;
}
A: If you are attempting to identify processes/applications that are explicit to .NET, you should look for a dependency/module within the process that is specific to the .NET framework.
Below I am using mscorlib, as it's the first that comes to mind, as my hint to identify that the process is dependent on the .NET framework. e.g.
var processes = Process.GetProcesses();
foreach (var process in processes)
{
try
{
foreach (var module in process.Modules)
{
if (module.ToString().Contains("mscorlib"))
{
Console.WriteLine(process);
break;
}
}
}
catch { // Access violations }
}
It's not bullet proof, as some processes cannot have their modules enumerated due to access restrictions, but if you run it, you'll see that it will pull back .NET dependent processes. Perhaps it will give you a good starting point to get you thinking in the right direction.
A: Check out CorPublishLibrary - a library that lets you interrogate all managed-code processes running on a machine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4471665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Make div appear only once after closing using useState and localstorage I have a div with a close button. Currently, what it does is when the user clicks the close button, the div disappears. But when the user refreshes the page, the div is still there. I'm thinking of using localstorage but I'm confused as to how it should be incorporated when I am using useState.
Here's my code.
const [isVisible, setIsVisible] = useState(true)
useEffect(() => {
let hideDiv = localStorage.getItem('hideDiv ')
if (!hideDiv ) {
setIsVisible(true)
localStorage.setItem('hideDiv ', 1)
}
}, [])
if (!isVisible) return null
<div className="absolute right-5 text-gray flex text-white">
<a href="#" onClick={() => setIsVisible(false)}>
x
</a>
... some text here ...
</div>
My current idea is useEffect and localstorage, but considering how I'm completely new to React, I'm not so sure how I go about this as I've only tried hiding and showing elements using localstorage in Vanilla javascript
A: useEffect with an empty dependency array will fire once when the component mounts. This is a good place to get that value from local storage and set it to the state. Then your close function can just set the local storage to true.
I made a sandbox for you here: https://codesandbox.io/s/crazy-davinci-io03f?file=/src/App.js
You should probably initialise your state to false too. This will avoid that flicker that you see.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69819364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Result does not return any data in FMDB I am using this tutorial to implement FMDB in my project. But my code does not return any value. here is the code for retrive value.
-(NSMutableArray *) getCustomers
{
NSMutableArray *customers = [[NSMutableArray alloc] init];
FMDatabase *db = [FMDatabase databaseWithPath:[Utility getDatabasePath]];
[db open];
FMResultSet *results = [db executeQuery:@"SELECT * FROM customers"];
NSLog(@"results %i,%@,%@",[results intForColumn:@"id"],[results stringForColumn:@"firstname"],[results stringForColumn:@"lastname"]);
while([results next])
{
Customer *customer = [[Customer alloc] init];
customer.customerId = [results intForColumn:@"id"];
customer.firstName = [results stringForColumn:@"firstname"];
customer.lastName = [results stringForColumn:@"lastname"];
[customers addObject:customer];
}
[db close];
return customers;
}
When i check for db than db exist at document directory here is log
CRUD[47363:f803] db /Users/pingdanehog/Library/Application Support/iPhone Simulator/5.1/Applications/D9F19E7D-A232-4C4A-8218-58BC136053A7/Documents/Customers.db
Here is my db
And it contain data
But my resulset value always be null please help this code have run before but when i create new db with same name for this project than it have stopped.
Here is the value of result.
results 0,(null),(null)
I have initialize my DB in appdelegate file
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
databaseName = @"Customers.db";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [documentPaths objectAtIndex:0];
databasePath = [documentDir stringByAppendingPathComponent:databaseName];
[self createAndCheckDatabase];
// Override point for customization after application launch.
self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
-(void) createAndCheckDatabase
{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
success = [fileManager fileExistsAtPath:databasePath];
if(success) return;
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}
A: What happens, if you place the line
NSLog(@"results %i,%@,%@",[results intForColumn:@"id"], ....
behind the [results next], e.g. inside the while loop?
The documentation of FMDB says:
"You must always invoke -[FMResultSet next] before attempting to access the values returned in a query, even if you're only expecting one"
A: Make sure you have initialized your db into AppDelegate or any of your file where you are using FMDB.
If yes & you have initialized it somewhere, then try to run this SQL "SELECT * FROM customers" . in database itself, in SQL tab. And check whether database contains the values or not.
Before that make sure you are running SQL in databse which resides into **Application Support**
Enjoy Programming!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15811813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to Hide Body but Keep Image displaying with JavaScript I have an HTML page that I want to hide everything in the body but still show just a single image on the page. Then, I want to hide that image that was showing and then re-enable the body.
I want to do this with JavaScript that I inject into the page. That is, when the page launches, I can run some JavaScript that I inject to do this. My JavaScript can inject the image. Then, I need to be able to inject some JavaScript later that will turn off the image and re-show the body tag.
I can easily turn the body tag to hidden, but then that also hides my img tag that I appended to the body and that defeats my purpose.
My page is something like this:
<html>
<body style="display:inline">
<p>...</p>
<body>
</html>
My code that has the hidden image problem is this.
document.getElementsByTagName("body")[0].style.display = "hidden";
console.log("about to create image");
n = document.createElement("img"); // create an image element
n.src =
"https://www.nasa.gov/sites/default/files/styles/full_width_feature/public/thumbnails/image/p5020056.jpg"; // relative path to the image
document.body.appendChild(n); // append the image to the body
A: Try this :
let newDiv = document.createElement("DIV");
newDiv.setAttribute("id", "hide");
document.body.appendChild(newDiv);
document.getElementById("hide").style.zIndex = "9";
document.getElementById("hide").style.width = "100%";
document.getElementById("hide").style.height = "100%";
document.getElementById("hide").style.backgroundImage = "url('https://www.nasa.gov/sites/default/files/styles/full_width_feature/public/thumbnails/image/p5020056.jpg')";
document.getElementById("hide").style.backgroundRepeat = "no-repeat";
document.getElementById("hide").style.backgroundSize = "cover";
document.getElementById("hide").style.top = "0";
document.getElementById("hide").style.position = "fixed";
document.body.style.margin = "0";
document.body.style.padding = "0";
<p>This is a text under the image and will not show up because the image is covering the whole area of the body !</p>
<p> I can even copy and paste this hundreds of times, but the image will still be on top of everything !</p>
<p>This is a text under the image and will not show up because the image is covering the whole area of the body !</p>
<p> I can even copy and paste this hundreds of times, but the image will still be on top of everything !</p>
<p>This is a text under the image and will not show up because the image is covering the whole area of the body !</p>
<p> I can even copy and paste this hundreds of times, but the image will still be on top of everything !</p>
<p>This is a text under the image and will not show up because the image is covering the whole area of the body !</p>
<p> I can even copy and paste this hundreds of times, but the image will still be on top of everything !</p>
<p>This is a text under the image and will not show up because the image is covering the whole area of the body !</p>
<p> I can even copy and paste this hundreds of times, but the image will still be on top of everything !</p>
<p>This is a text under the image and will not show up because the image is covering the whole area of the body !</p>
<p> I can even copy and paste this hundreds of times, but the image will still be on top of everything !</p>
<p>This is a text under the image and will not show up because the image is covering the whole area of the body !</p>
<p> I can even copy and paste this hundreds of times, but the image will still be on top of everything !</p>
<p>This is a text under the image and will not show up because the image is covering the whole area of the body !</p>
<p> I can even copy and paste this hundreds of times, but the image will still be on top of everything !</p>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56193236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unable to Open new browser after each scenario in Cucumber-Protractor I had automated all my scenarios using cucumber-protractor framework. All this scenarios run fine when executed individually i.e. closes the browser once scenario is complete but when ran together I am unable to open new browser window after each scenario. It just continues in same browser. Due to SSO login, I have to restart browser after each scenario.
I tried using maxSession, maxInstance in protractor but of no help. Though maxIntance opens new browser, it doesn't close old one and neither passes control to new one. I tried using getWindowHandler as well but that also didn't worked.
Any help is greatly appreciated as I am stuck on this for long time.
A: It seems juliemr answers your question:
tests are sharded by file, not by scenario, so you'll need to split the scenarios into separate files.
https://github.com/angular/protractor/issues/864#issuecomment-45571006
So you'll need to split the scenarios into separate feature files and, if desired, set maxInstances to however many you want to run at once. For example:
capabilities: {
'browserName': 'chrome',
'shardTestFiles': true,
'maxInstances': 10
}
A: Add a hook after each scenario to close the browser:
this.After(function(scenario, done) {
this.quit(done);
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34730078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Which member in PROCESS_MEMORY_COUNTERS structure gives the current used memory Following is the PROCESS_MEMORY_COUNTERS structure
typedef struct _PROCESS_MEMORY_COUNTERS {
DWORD cb;
DWORD PageFaultCount;
SIZE_T PeakWorkingSetSize;
SIZE_T WorkingSetSize;
SIZE_T QuotaPeakPagedPoolUsage;
SIZE_T QuotaPagedPoolUsage;
SIZE_T QuotaPeakNonPagedPoolUsage;
SIZE_T QuotaNonPagedPoolUsage;
SIZE_T PagefileUsage;
SIZE_T PeakPagefileUsage;
} PROCESS_MEMORY_COUNTERS, *PPROCESS_MEMORY_COUNTERS;
Which member of the structure gives the current used memory of the specific process?
A: The structure member
WorkingSetSize
gives the current used memory.
The working set is the amount of memory physically mapped to the
process context at a given time.
Ref.:Process Memory Usage Information.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20896469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Create another symbol in specific point in a line graph I would like to have another symbol in a specific point of line graphs where the x axis has value of 1. In my graph, all the points in the line have circle as a symbol, but I would like to have a triangle where the value of the x axis is 1.
So far, I found this post when it creates an X symbol, but when I use it on my code, it creates an X mark on top the circle while I want an entirely new symbol.
Here is the code:
library(ggplot2)
wd = "path/"
block.data = read.csv(paste0(wd, "block.data.csv"))
ggplot(data = block.data, aes(x = PSF, y = CC, group = 1)) +
geom_line() +
geom_point(size = 2) +
theme_bw() +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black")) +
scale_x_continuous(breaks = seq(0, 2, .2)) +
scale_y_continuous(breaks = seq(0.08, 23, .01))
And the dataset:
structure(list(PSF = c(0, 0.2, 0.4, 0.6, 0.8, 1, 1.2, 1.4, 1.6, 1.8, 2), CC = c(0.08278661, 0.1866827, 0.2051862, 0.218509, 0.2247673, 0.2268575, 0.2265966, 0.22522, 0.223409, 0.2213272, 0.2192285 )), class = "data.frame", row.names = c(NA, -11L))
A: One option would be to map a condition, i.e. PSF != 1 on the shape aes and set your desired shape using scale_shape_manual:
library(ggplot2)
ggplot(data = block.data, aes(x = PSF, y = CC, group = 1)) +
geom_line() +
geom_point(aes(shape = PSF != 1), size = 3) +
scale_shape_manual(values = c(17, 16)) +
theme_bw() +
theme(
panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black")
) +
scale_x_continuous(breaks = seq(0, 2, .2)) +
scale_y_continuous(breaks = seq(0.08, 23, .01)) +
guides(shape = "none")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75574669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why do I keep getting ArrayIndexOutOfBoundsException? I know that the ArrayIndexOutOfBoundsException means that you're trying to access something not defined in the array, and tried to look up solutions. All the solutions say that you need to use < rather than =<, but that's about it. I don't understand why my loop below keeps giving me ArrayIndexOutOfBoundsException erros.
for (int i=0; i < myMessage.length(); ){
eInteger = eNumbers[i];
myInteger = numbers[i];
System.out.println(eInteger + " " + myInteger);
character = myInteger - eInteger;
stringCharacter = Integer.toString(character);
//decryptedMessage = decryptedMessage + " " + stringCharacter;
System.out.println(character);
i++;
}
I've tried int i=0, int i = 1, myMessage.length() - 1. It shouldn't be attempting to give me something further than the array, but I don't know.
Full code:
public class Decrypt {
private String myMessage;
private String e = "2718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427427466391932003059921817413596629043572900334295260595630738132328627943490763233829880753195251019011573834187930702154089149934884167509244761460668082264800168477411853742345442437107539077744992069551702761838606261331384583000752044933826560297606737113200709328709127443747047230696977209310141692836819025515108657463772111252389784425056953696770785449969967946864454905987931636889230098793127736178215424999229576351482208269895193668033182528869398496465105820939239829488793320362509443117301238197068416140397019837679320683282376464804295311802328782509819455815301756717361332069811250996181881593041690351598888519345807273866738589422879228499892086805825749279610484198444363463244968487560233624827041978623209002160990235304369941849146314093431738143640546253152096183690888707016768396424378140592714563549061303107208510383750510115747704171898610687396965521267154688957035035402123407849819334321068170121005627880235193033224745015853904730419957777093503660416997329725088687696640355570716226844716256079882651787134195124665201030592123667719432527867539855894489697096409754591856956380236370162112047742722836489613422516445078182442352948636372141740238893441247963574370263755294448337";
private String stringCharacter;
private int character;
private int myInteger;
private int eInteger;
private String decryptedMessage = "";
public Decrypt(String myMessage){
this.myMessage = myMessage;
}
public String Decryption(){
String[] splitMessage = myMessage.split(" ");
int[] numbers = Arrays.stream(splitMessage)
.mapToInt(Integer::parseInt).toArray();
String[] eMessage = e.split("");
int[] eNumbers = Arrays.stream(eMessage)
.mapToInt(Integer::parseInt).toArray();
for (int i=0; i < myMessage.length(); ){
eInteger = eNumbers[i];
myInteger = numbers[i];
System.out.println(eInteger + " " + myInteger);
character = myInteger - eInteger;
stringCharacter = Integer.toString(character);
//decryptedMessage = decryptedMessage + " " + stringCharacter;
System.out.println(character);
i++;
}
return stringCharacter;
}
public String toString(){
return "Message: " + Decryption();
}
}
When I run my program (the extra code is in a driver) I get the following:
Welcome to this cryptographic program! Would you like to encrypt or decrypt a message?
Please enter 1 to encrypt, and 2 to decrypt.
2
Thank you! Please type the message you would like to encrypt or decrypt.
22 12 20 28
2 22
Exception in thread "main" 20
7 12
5
1 20
19
8 28
20
java.lang.ArrayIndexOutOfBoundsException: 4
at Program4.Decrypt.Decryption(Decrypt.java:30)
at Program4.Decrypt.toString(Decrypt.java:42)
at java.lang.String.valueOf(Unknown Source)
at java.io.PrintStream.println(Unknown Source)
at Program4.Driver.main(Driver.java:28)
A: The problem is that myMessage.length() is the number of characters in myMessage, whereas numbers.size is the number of integers represented in myMessage.
In your example run, myMessage is "22 12 20 28", which has 11 characters so you are iterating from 0 to 10; but numbers is an array of just four numbers (0 through 3), so numbers[i] will raise this exception for any i greater than 3.
If I'm understanding correctly what you are trying to do, you just need to change this:
for (int i=0; i < myMessage.length(); ){
to this:
for (int i=0; i < numbers.size; ){
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28401964",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Display rss xml index in html I am adding an RSS feed to my website. I created the RSS.xml index file and next I want to display its contents in a nicely formatted way in a webpage.
Using PHP, I can do this:
$index = file_get_contents ($path . 'RSS.xml');
echo $index;
But all that does is dump the contents as a long stream of text with the tags removed.
I know that treating RSS.xml as a link, like this:
<a href="../blogs/RSS.xml">
<img src="../blogs/feed-icon-16.gif">Blog Index
</a>
causes my browser to parse and display it in a reasonable way when the user clicks on the link. However I want to embed it directly in the web page and not make the user go through another click.
What is the proper way to do what I want?
A: Use the following code:
include_once('Simple/autoloader.php');
$feed = new SimplePie();
$feed->set_feed_url($url);
$feed->enable_cache(false);
$feed->set_output_encoding('utf-8');
$feed->init();
$i=0;
$items = $feed->get_items();
foreach ($items as $item) {
$i++;
/*You are getting title,description,date of your rss by the following code*/
$title = $item->get_title();
$url = $item->get_permalink();
$desc = $item->get_description();
$date = $item->get_date();
}
Download the Simple folder data from : https://github.com/jewelhuq/Online-News-Grabber/tree/master/worldnews/Simple
Hope it will work for you. There $url mean your rss feed url. If you works then response.
A: Turns out, it's simple by using the PHP xml parer function:
$xml = simplexml_load_file ($path . 'RSS.xml');
$channel = $xml->channel;
$channel_title = $channel->title;
$channel_description = $channel->description;
echo "<h1>$channel_title</h1>";
echo "<h2>$channel_description</h2>";
foreach ($channel->item as $item)
{
$title = $item->title;
$link = $item->link;
$descr = $item->description;
echo "<h3><a href='$link'>$title</a></h3>";
echo "<p>$descr</p>";
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32750723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to set a default row for a query that returns no rows? I need to know how to return a default row if no rows exist in a table. What would be the best way to do this? I'm only returning a single column from this particular table to get its value.
Edit: This would be SQL Server.
A: One approach for Oracle:
SELECT val
FROM myTable
UNION ALL
SELECT 'DEFAULT'
FROM dual
WHERE NOT EXISTS (SELECT * FROM myTable)
Or alternatively in Oracle:
SELECT NVL(MIN(val), 'DEFAULT')
FROM myTable
Or alternatively in SqlServer:
SELECT ISNULL(MIN(val), 'DEFAULT')
FROM myTable
These use the fact that MIN() returns NULL when there are no rows.
A: How about this:
SELECT DEF.Rate, ACTUAL.Rate, COALESCE(ACTUAL.Rate, DEF.Rate) AS UseThisRate
FROM
(SELECT 0) DEF (Rate) -- This is your default rate
LEFT JOIN (
select rate
from d_payment_index
--WHERE 1=2 -- Uncomment this line to simulate a missing value
--...HERE IF YOUR ACTUAL WHERE CLAUSE. Removed for testing purposes...
--where fy = 2007
-- and payment_year = 2008
-- and program_id = 18
) ACTUAL (Rate) ON 1=1
Results
Valid Rate Exists
Rate Rate UseThisRate
----------- ----------- -----------
0 1 1
Default Rate Used
Rate Rate UseThisRate
----------- ----------- -----------
0 NULL 0
Test DDL
CREATE TABLE d_payment_index (rate int NOT NULL)
INSERT INTO d_payment_index VALUES (1)
A: This snippet uses Common Table Expressions to reduce redundant code and to improve readability. It is a variation of John Baughman's answer.
The syntax is for SQL Server.
WITH products AS (
SELECT prod_name,
price
FROM Products_Table
WHERE prod_name LIKE '%foo%'
),
defaults AS (
SELECT '-' AS prod_name,
0 AS price
)
SELECT * FROM products
UNION ALL
SELECT * FROM defaults
WHERE NOT EXISTS ( SELECT * FROM products );
A: *SQL solution
Suppose you have a review table which has primary key "id".
SELECT * FROM review WHERE id = 1555
UNION ALL
SELECT * FROM review WHERE NOT EXISTS ( SELECT * FROM review where id = 1555 ) AND id = 1
if table doesn't have review with 1555 id then this query will provide a review of id 1.
A: I figured it out, and it should also work for other systems too. It's a variation of WW's answer.
select rate
from d_payment_index
where fy = 2007
and payment_year = 2008
and program_id = 18
union
select 0 as rate
from d_payment_index
where not exists( select rate
from d_payment_index
where fy = 2007
and payment_year = 2008
and program_id = 18 )
A: One table scan method using a left join from defaults to actuals:
CREATE TABLE [stackoverflow-285666] (k int, val varchar(255))
INSERT INTO [stackoverflow-285666]
VALUES (1, '1-1')
INSERT INTO [stackoverflow-285666]
VALUES (1, '1-2')
INSERT INTO [stackoverflow-285666]
VALUES (1, '1-3')
INSERT INTO [stackoverflow-285666]
VALUES (2, '2-1')
INSERT INTO [stackoverflow-285666]
VALUES (2, '2-2')
DECLARE @k AS int
SET @k = 0
WHILE @k < 3
BEGIN
SELECT @k AS k
,COALESCE(ActualValue, DefaultValue) AS [Value]
FROM (
SELECT 'DefaultValue' AS DefaultValue
) AS Defaults
LEFT JOIN (
SELECT val AS ActualValue
FROM [stackoverflow-285666]
WHERE k = @k
) AS [Values]
ON 1 = 1
SET @k = @k + 1
END
DROP TABLE [stackoverflow-285666]
Gives output:
k Value
----------- ------------
0 DefaultValue
k Value
----------- ------------
1 1-1
1 1-2
1 1-3
k Value
----------- ------------
2 2-1
2 2-2
A: Assuming there is a table config with unique index on config_code column:
CONFIG_CODE PARAM1 PARAM2
--------------- -------- --------
default_config def 000
config1 abc 123
config2 def 456
This query returns line for config1 values, because it exists in the table:
SELECT *
FROM (SELECT *
FROM config
WHERE config_code = 'config1'
OR config_code = 'default_config'
ORDER BY CASE config_code WHEN 'default_config' THEN 999 ELSE 1 END)
WHERE rownum = 1;
CONFIG_CODE PARAM1 PARAM2
--------------- -------- --------
config1 abc 123
This one returns default record as config3 doesn't exist in the table:
SELECT *
FROM (SELECT *
FROM config
WHERE config_code = 'config3'
OR config_code = 'default_config'
ORDER BY CASE config_code WHEN 'default_config' THEN 999 ELSE 1 END)
WHERE rownum = 1;
CONFIG_CODE PARAM1 PARAM2
--------------- -------- --------
default_config def 000
In comparison with other solutions this one queries table config only once.
A: If your base query is expected to return only one row, then you could use this trick:
select NVL( MIN(rate), 0 ) AS rate
from d_payment_index
where fy = 2007
and payment_year = 2008
and program_id = 18
(Oracle code, not sure if NVL is the right function for SQL Server.)
A: This would be eliminate the select query from running twice and be better for performance:
Declare @rate int
select
@rate = rate
from
d_payment_index
where
fy = 2007
and payment_year = 2008
and program_id = 18
IF @@rowcount = 0
Set @rate = 0
Select @rate 'rate'
A: Do you want to return a full row? Does the default row need to have default values or can it be an empty row? Do you want the default row to have the same column structure as the table in question?
Depending on your requirements, you might do something like this:
1) run the query and put results in a temp table (or table variable)
2) check to see if the temp table has results
3) if not, return an empty row by performing a select statement similar to this (in SQL Server):
select '' as columnA, '' as columnB, '' as columnC from #tempTable
Where columnA, columnB and columnC are your actual column names.
A: Insert your default values into a table variable, then update this tableVar's single row with a match from your actual table. If a row is found, tableVar will be updated; if not, the default value remains. Return the table variable.
---=== The table & its data
CREATE TABLE dbo.Rates (
PkId int,
name varchar(10),
rate decimal(10,2)
)
INSERT INTO dbo.Rates(PkId, name, rate) VALUES (1, 'Schedule 1', 0.1)
INSERT INTO dbo.Rates(PkId, name, rate) VALUES (2, 'Schedule 2', 0.2)
Here's the solution:
---=== The solution
CREATE PROCEDURE dbo.GetRate
@PkId int
AS
BEGIN
DECLARE @tempTable TABLE (
PkId int,
name varchar(10),
rate decimal(10,2)
)
--- [1] Insert default values into @tempTable. PkId=0 is dummy value
INSERT INTO @tempTable(PkId, name, rate) VALUES (0, 'DEFAULT', 0.00)
--- [2] Update the single row in @tempTable with the actual value.
--- This only happens if a match is found
UPDATE @tempTable
SET t.PkId=x.PkId, t.name=x.name, t.rate = x.rate
FROM @tempTable t INNER JOIN dbo.Rates x
ON t.PkId = 0
WHERE x.PkId = @PkId
SELECT * FROM @tempTable
END
Test the code:
EXEC dbo.GetRate @PkId=1 --- returns values for PkId=1
EXEC dbo.GetRate @PkId=12314 --- returns default values
A: This is what I used for getting a default value if no values are present.
SELECT IF (
(SELECT COUNT(*) FROM tbs.replication_status) > 0,
(SELECT rs.last_replication_end_date FROM tbs.replication_status AS rs
WHERE rs.last_replication_start_date IS NOT NULL
AND rs.last_replication_end_date IS NOT NULL
AND rs.table = '%s' ORDER BY id DESC LIMIT 1),
(SELECT CAST(UNIX_TIMESTAMP (CURRENT_TIMESTAMP(6)) AS UNSIGNED))
) AS ts;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/285666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "52"
}
|
Q: Extracting HTML input string into Python I'm currently trying to grab a string that a user would put in an HTML form, and set that equal to a variable in a python program after the 'search' button has been clicked. I'm using flask to run the html code just on localhost. How would I go about implementing this?
The code I have for the search bar so far is below.
<div class="input-group pl-2">
<input type="text" class="form-control" placeholder="Enter a string...">
<span class="input-group-btn pr-2">
<button class="btn btn-success" type="submit">
<span></span>Search
</button>
</span>
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59147862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: pass url from one js page to another and extract exact value how can i pass this url="https://www.google.com/finance?q=tcs&ei=I7dtWaHxOJCuuATHoZaoCA" from store.js page and getting exact stock price of tcs on my another app.js page using chatbot and nodejs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45186839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Application.Match vs Find I want to write a macro that will get the last item in column A and check if it exists anywhere in columns B to D. However, the following code never finds a match and returns "Doesn't exist":
Sub MatchInRange()
Dim LastItem As Range
Set LastItem = Range("A1").End(xlDown)
If Not IsError(Application.Match(LastItem, "B:D", 0)) Then
MsgBox "Exists in range"
Else
MsgBox "Doesn't exist"
End If
End Sub
But it works when rewritten using Find:
Sub FindInRange()
Dim LastItem As Range
Set LastItem = Range("A1").End(xlDown)
If Not Range("B:D").Find(LastItem) Is Nothing Then
MsgBox "Exists in range"
Else
MsgBox "Doesn't exist"
End If
End Sub
Can anyone tell me what am I doing wrong with the first code?
A: Match works on 1 row or column. You are using 3 - B,C and D. Rewrite the first formula like this:
Sub TestMe()
Debug.Print WorksheetFunction.match("TestValue", Range("B:B"), 0)
End Sub
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45882858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: NSURLConnection JSON doesn't post data I'm creating a login Page in my iPhone app and I use Json to call a PHP page to connect to a MySql database.
I have the connection with the PHP page but my program doesn't post anything.
- (IBAction)login:(id)sender{
//Alloc dictionary
jsonDictionaryLogin = [[NSDictionary alloc] initWithObjectsAndKeys: securityCode, @"hash_app", loginTextField.text, @"app_email", passwordTextField.text, @"app_password", nil];
NSError *jsonError = nil;
jsonDataLogin = [NSJSONSerialization dataWithJSONObject:jsonDictionaryLogin
options:kNilOptions error:&jsonError];
if(!jsonError) {
NSString *serJSON = [[NSString alloc] initWithData:jsonDataLogin encoding:NSUTF8StringEncoding];
NSLog(@"\n\nSerialized JSON: %@", serJSON);
} else {
NSLog(@"JSON Encoding Failed: %@", [jsonError localizedDescription]);
}
NSURL *url = [NSURL URLWithString:@"http://www.mywebsite.com/mypage.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:[NSString stringWithFormat:@"%d", [jsonDataLogin length]] forHTTPHeaderField:@"content-Length"];
[request setHTTPBody:jsonDataLogin];
NSLog(@"jsonData: %@",jsonDataLogin);
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:true];
[connection start];
}
After, in my delegate method:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData{
NSLog(@"String sent from server %@",[[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding]);
}
My PHP code:
<?
$hash = $_POST['hash_app'];
echo json_encode(array("TEST" => "swrao")); //RETURN swrao
echo json_encode($hash); //RETURN null
if($hash == "string_sended")
{
echo json_encode(array("TEST" => "YOU ARE IN")); //NO RETURN
}
?>
The String from the NSLog give some message that i have written in PHP page, but the PHP page doesn't not receive the data sended.
Some idea?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15053186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Google Translator API "Too Large URL" I have recently started working on Translator API and I am getting the ERROR Too Large URL when my input text exceeds 1300 characters.
I am using the below code
string apiKey = "My Key";
string sourceLanguage = "en";
string targetLanguage = "de";
string googleUrl;
string textToTranslate =
while (textToTranslate.Length < 1300)
{
textToTranslate = textToTranslate + " hello world ";
}
googleUrl = "https://www.googleapis.com/language/translate/v2?key=" + apiKey + "&q=" + textToTranslate + "&source=" + sourceLanguage + "&target=" + targetLanguage;
WebRequest request = WebRequest.Create(googleUrl);
// Set the Method property of the request to POST^H^H^H^HGET.
request.Method = "GET"; // <-- ** You're putting textToTranslate into the query string so there's no need to use POST. **
//// Create POST data and convert it to a byte array.
//string postData = textToTranslate;
//byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// ** Commenting out the bit that writes the post data to the request stream **
//// Set the ContentLength property of the WebRequest.
//request.ContentLength = byteArray.Length;
//// Get the request stream.
//Stream dataStream = request.GetRequestStream();
//// Write the data to the request stream.
//dataStream.Write(byteArray, 0, byteArray.Length);
//// Close the Stream object.
//dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
Console.WriteLine(i);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
Can You please suggest me that what kind of changes i can do in my code, so that the input text limit can be increased unto 40k - 50k per request.
A: At some point someone has changed your code from making a POST request to making a GET.
GET puts all the data into the URL instead of putting it in the request body. URLs have a length limit. Go back to using POST and this problem will go away. Refer to the documentation for your HTTP client library to find out how to do this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19995625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Spring Boot throws exception when int field in mongodb model has null value in the database I have a situation when a user does not enter data for certain field I pass null as value for that int field to signify that no value was entered by the user like
{user: 'John',
age: null}
but when I read such document in my Spring Boot application, when it encounters above document, throws
Caused by: java.lang.IllegalArgumentException: Parameter age must not be null!
Is null allowed value in mongodb or Spring Boot is doing something wrong?
I tried to:
@Data
@Document
public class User {
final private String user;
@org.springframework.lang.Nullable
final private int age;
}
But it makes no difference. How to solve this problem other than not storing null ( because null is already populated in another node/mongoose application (which gladly stores and reads null values without any issue) using the same mongodb database?
A: Replace int with Integer since int is a primitive type which won't accept null values. Integer is a wrapper object that accepts null values.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49656855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the best way to update all clients when Flask database changes without polling? Currently I have a Flask server that runs a small web frontend as well as a command line interface to that same server. The basic idea looks like this:
<Top section: allows file upload>
* list of files from database
<Second section: allows file manipulation/ upload>
* list of files from database
<Third section: Not files, but still allows for database changes>
* list of things made from database
Now this works well from the front end, but currently if the CLI or another client makes a change to the database, it doesn't update other clients. I have it somewhat working with JS polling and rewriting the list of files every 10s, but that seems both inefficient and also would look very messy if I had to do it for every section. I saw websockets mentioned in various forums, but I've never used them and am unsure if it would be a pain to add. I'm not trying to rewrite the whole thing for a single feature.
Final takeaway: How to update all clients better than polling/ how to do polling efficiently?
A: Yes you are correct. You need sockets. There are bunch of articles over the internet but I would like to give a summary and try to explain why sockets will be the best fit to your requirements.
Sockets are way of achieving two way communication between client and server without the need of polling.
There is a package called Flask-SocketIO
Flask-SocketIO gives Flask applications access to low latency
bi-directional communications between the clients and the server.
Then for the scenario where you would like to send changes to all the connected client when one client does some work to your database or something similar, you will need to use broadcasting. When a message is sent with the broadcast option enabled, all clients connected to the namespace receive it, including the sender. Here you can find details of the broadcasting using Flask-SocketIO.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45486960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is this C++11 regex error me or the compiler? OK, this isn't the original program I had this problem in, but I duplicated it in a much smaller one. Very simple problem.
main.cpp:
#include <iostream>
#include <regex>
using namespace std;
int main()
{
regex r1("S");
printf("S works.\n");
regex r2(".");
printf(". works.\n");
regex r3(".+");
printf(".+ works.\n");
regex r4("[0-9]");
printf("[0-9] works.\n");
return 0;
}
Compiled successfully with this command, no error messages:
$ g++ -std=c++0x main.cpp
The last line of g++ -v, by the way, is:
gcc version 4.6.1 (Ubuntu/Linaro 4.6.1-9ubuntu3)
And the result when I try to run it:
$ ./a.out
S works.
. works.
.+ works.
terminate called after throwing an instance of 'std::regex_error'
what(): regex_error
Aborted
It happens the same way if I change r4 to \\s, \\w, or [a-z]. Is this a problem with the compiler? I might be able to believe that C++11's regex engine has different ways of saying "whitespace" or "word character," but square brackets not working is a stretch. Is it something that's been fixed in 4.6.2?
EDIT:
Joachim Pileborg has supplied a partial solution, using an extra regex_constants parameter to enable a syntax that supports square brackets, but neither basic, extended, awk, nor ECMAScript seem to support backslash-escaped terms like \\s, \\w, or \\t.
EDIT 2:
Using raw strings (R"(\w)" instead of "\\w") doesn't seem to work either.
A: Regex support improved between gcc 4.8.2 and 4.9.2. For example, the regex =[A-Z]{3} was failing for me with:
Regex error
After upgrading to gcc 4.9.2, it works as expected.
A: Update: <regex> is now implemented and released in GCC 4.9.0
Old answer:
ECMAScript syntax accepts [0-9], \s, \w, etc, see ECMA-262 (15.10). Here's an example with boost::regex that also uses the ECMAScript syntax by default:
#include <boost/regex.hpp>
int main(int argc, char* argv[]) {
using namespace boost;
regex e("[0-9]");
return argc > 1 ? !regex_match(argv[1], e) : 2;
}
It works:
$ g++ -std=c++0x *.cc -lboost_regex && ./a.out 1
According to the C++11 standard (28.8.2) basic_regex() uses regex_constants::ECMAScript flag by default so it must understand this syntax.
Is this C++11 regex error me or the compiler?
gcc-4.6.1 doesn't support c++11 regular expressions (28.13).
A: The error is because creating a regex by default uses ECMAScript syntax for the expression, which doesn't support brackets. You should declare the expression with the basic or extended flag:
std::regex r4("[0-9]", std::regex_constants::basic);
Edit Seems like libstdc++ (part of GCC, and the library that handles all C++ stuff) doesn't fully implement regular expressions yet. In their status document they say that Modified ECMAScript regular expression grammar is not implemented yet.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8060025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "58"
}
|
Q: Using Win32, GetModuleBaseName() and GetModuleFileNameEx() fail with GetLastError() = 6 when using valid handle First some simple code snippet:
m_hProcessHandle = ::OpenProcess((PROCESS_QUERY_INFORMATION | PROCESS_CREATE_THREAD | PROCESS_DUP_HANDLE | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_VM_OPERATION), FALSE, m_dwProcessIdentifier);
if (NULL != m_hProcessHandle)
{
if (FALSE != ::OpenProcessToken(m_hProcessHandle, (TOKEN_QUERY | TOKEN_IMPERSONATE | TOKEN_DUPLICATE), &m_hImpersonizationToken))
{
wchar_t wszFullExecutableFileName[MAX_PATH];
if (0 == ::GetModuleBaseName(m_hProcessHandle, NULL, wszFullExecutableFileName, (sizeof(wszFullExecutableFileName)/sizeof(wchar_t))))
{
__DebugMessage(L"GetModuleBaseName() failed with GetLastError() = %d", ::GetLastError());
}
else
{
if (0 == ::GetModuleFileNameEx(m_hProcessHandle, NULL, wszFullExecutableFileName, (sizeof(wszFullExecutableFileName)/sizeof(wchar_t))))
{
__DebugMessage(L"GetModuleFileNameEx() failed with GetLastError() = %d", ::GetLastError());
}
else
{
m_strFullFileName = wszFullExecutableFileName;
}
}
}
}
The OpenProcess() returns a valid handle as does the OpenProcessToken(), but when I call the subsequent GetModuleBaseName() and GetModuleFileNameEx() functions, I get GetLastError() = 6 (The handle is invalid). I am running that code as admin on Windows 7. What gives?
cheers,
GumbyTheBorg
A: You must run this program as administrator in order for it to work correctly. I just tested it working and GetLastError() = 0 after each line, which means there were no problems.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10502706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: HelloAndroid.java not created automatically - Hello World Android App in Eclipse I've finally installed the Android SDK/Eclipse and set everything up correctly (I thought), but when I create a new Android project it is not automatically creating the necessary files (HelloAndroid.java is missing).
I just wanted to do the simple HelloAndroid example to verify that everything was properly set up, and obviously I can add the file myself, but my settings are all defaults and I don't understand why this file would not be created for me when every tutorial assumes it is. In fact I cannot find any posts from others about this issue, either. The HelloAndroidActivity.java file is created, however.
Any ideas why this file is not being created for me? Did I start a new project the wrong way? I am using Eclipse on OSX 10.7.3.
A: It's HellowWorld.java or HelloWorldActivity.java depends on what you choose at this step. Whatever the name is, as long as the it extends Activity Class you should be OK.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10745129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Django fixtures for model from imported application (like django-allauth) I know that is possible to create fixtures file like initial_data.json for my own model. I want to create similar file for tables which are created and used by imported django-allauth application.
I tried:
[
{
"model":"allauth.socialaccount.models.SocialApp",
"pk":1,
"fields":{
"id":"1",
"provider":"facebook",
"name":"facebook",
"client_id":"0011223344556677",
"key":"",
"secret":"012345678901234567890123456"
}
}
]
However it's ends up with error:
python manage.py syncdb
Creating tables ...
Installing custom SQL ...
Installing indexes ...
DeserializationError: Problem installing fixture 'initial_data.json':
Invalid model identifier: 'allauth.socialaccount.models.SocialApp'
A: I found here that table from model django.contrib.sites.models.Site can be populate using
[
{
"model": "sites.site",
"pk": 1,
"fields": {
"domain": "myproject.mydomain.com",
"name": "My Project"
}
}
]
So model allauth.socialaccount.models.SocialApp probably can by populated by:
[
{
"model":"socialaccount.socialapp",
"pk":1,
"fields":{
"id":"1",
"provider":"facebook",
"name":"facebook",
"client_id":"0011223344556677",
"key":"",
"secret":"012345678901234567890123456"
}
}
]
A: Full fixture example, tested with django-allauth 0.19 and Django 1.8:
[
{
"model": "sites.site",
"pk": 1,
"fields": {
"domain": "localhost",
"name": "localhost"
}
},
{
"model":"socialaccount.socialapp",
"pk":1,
"fields":{
"id":"1",
"provider":"facebook",
"name":"facebook",
"client_id":"0011223344556677",
"secret":"012345678901234567890123456",
"key":""
}
},
{
"model":"socialaccount.socialapp_sites",
"pk":1,
"fields":{
"id":1,
"socialapp_id":1,
"site_id":1
}
}
]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18020791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: HTML5 Input tag : what if max,min,step do not fit with each other Let's say you had a job to provide the user with a <input> as this:
<input type="number" min="1" max="11" step="3" value="1"></input>
the result would be increased as this sequence : 1,4,7,10,(13).
you can never see "13" in the box because this number exceeds the maximum value it allows("11"). The max value you can get in this box is 10.
But what if the maximum number you want to show to the user is 11, as specified in your code ?
the expected sequence is like this : 1,4,7,10,11
How to make it ?
Thanks.
EDIT :
Here's a demonstration for the question.
A: The step attribute respects the max, but also restricts the input. If you need more flexibility, try this:
<input list="numbers">
<datalist id="numbers">
<option value="1">
<option value="4">
<option value="7">
<option value="10">
<option value="11">
</datalist>
On second thought, that's not great - I would just use the good old-fashioned select tag:
<select>
<option>1<option>
<option>4<option>
<option>7<option>
<option>10<option>
<option>11<option>
</select>
to get closer to your example. If your data set is contrived to demonstrate a point, these alternatives can be generated programmatically jsut as easy as the one in your example.
A: This is simply not possible using straight HTML5.
There's no HTML5 number feature that increments by 3s and switch to 1s near the last number. HTML rarely deviates from its established rules, no matter what our needs are. And step has pretty strict rules with no similar HTML5 alternatives. You will have to use Javascript or a <select> dropdown.
Easy Imperfect Solution
You can use some Javascript to make this happen. This example uses jQuery in a ready event:
$('input').change(function(){
var $input = $(this), val = $input.val();
if (val == 13) {
$input.attr("step","1");
$input.val(11);
} else if (val == 10) {
$input.attr("step","3");
} else if (val == 12) {
$input.val(11);
}
});
Demo: http://jsfiddle.net/fpm21ej2/1/
There is a flash of the incorrect number "13" right before it changes to "11". I don't know of an event that would intercept this faster though, making this solution imperfect.
Harder Better Solution
Create a custom text field to mimick this incrementing behavior, but using your special number sequence. That means take a number box, add in some up/down buttons (possibly with sprite images), use Javascript to bind them to events that increment this as expected, and validate against the user entering invalid numbers (use the HTML5 pattern attribute).
That will probably take some work, and it needs a bit more time than most of us can volunteer here at StackOverflow. But this should be possible.
Easy Better Solution
Use a <select> dropdown.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25903654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Css loop animation I have a problem with the animation, where the words should iterate 'n' number of times
The above mentioned code has 9 different words which has a fade in and out animation one after the other, but this animation is only once . What i need is the loop iterates again and again with the same animation , as the last word ends the first should be loaded.
Here is the html/css code:
h1.main,p.demos {
-webkit-animation-delay: 18s;
-moz-animation-delay: 18s;
-ms-animation-delay: 18s;
animation-delay: 18s;
}
.sp-container {
position: relative;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
z-index: 0;
background: -webkit-radial-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.3) 35%, rgba(0, 0, 0, 0.7));
background: -moz-radial-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.3) 35%, rgba(0, 0, 0, 0.7));
background: -ms-radial-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.3) 35%, rgba(0, 0, 0, 0.7));
background: radial-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.3) 35%, rgba(0, 0, 0, 0.7));
}
.sp-content {
position: absolute;
width: 100%;
height: 100%;
left: 0px;
top: 0px;
z-index: 1000;
}
.sp-container h2 {
position: absolute;
top: 50%;
line-height: 100px;
height: 90px;
margin-top: -50px;
font-size: 90px;
width: 100%;
text-align: center;
color: transparent;
-webkit-animation: blurFadeInOut 3s ease-in backwards;
-moz-animation: blurFadeInOut 3s ease-in backwards;
-ms-animation: blurFadeInOut 3s ease-in backwards;
animation: blurFadeInOut 3s ease-in backwards;
}
.sp-container h2.frame-6 {
-webkit-animation-delay:0s;
-moz-animation-delay: 0s;
-ms-animation-delay: 0s;
animation-delay: 0s;
}
.sp-container h2.frame-1 {
-webkit-animation-delay: 3s;
-moz-animation-delay: 3s;
-ms-animation-delay: 3s;
animation-delay: 3s;
}
.sp-container h2.frame-2 {
-webkit-animation-delay: 6s;
-moz-animation-delay: 6s;
-ms-animation-delay: 6s;
animation-delay: 6s;
}
.sp-container h2.frame-3 {
-webkit-animation-delay: 9s;
-moz-animation-delay: 9s;
-ms-animation-delay: 9s;
animation-delay: 9s;
}
.sp-container h2.frame-4 {
font-size: 200px;
-webkit-animation-delay: 12s;
-moz-animation-delay: 12s;
-ms-animation-delay: 12s;
animation-delay: 12s;
}
.sp-container h2.frame-7 {
font-size: 200px;
-webkit-animation-delay: 15s;
-moz-animation-delay: 15s;
-ms-animation-delay: 15s;
animation-delay: 15s;
}
.sp-container h2.frame-8 {
font-size: 200px;
-webkit-animation-delay: 18s;
-moz-animation-delay: 18s;
-ms-animation-delay: 18s;
animation-delay: 18s;
}
.sp-container h2.frame-9 {
font-size: 200px;
-webkit-animation-delay: 21s;
-moz-animation-delay: 21s;
-ms-animation-delay: 21s;
animation-delay: 21s;
}
.sp-container h2.frame-5 {
font-size: 200px;
-webkit-animation-delay: 24s;
-moz-animation-delay: 24s;
-ms-animation-delay: 24s;
animation-delay: 24s;
}
/* .sp-container h2.frame-5 span {
-webkit-animation: blurFadeIn 3s ease-in 12s backwards;
-moz-animation: blurFadeIn 1s ease-in 12s backwards;
-ms-animation: blurFadeIn 3s ease-in 12s backwards;
animation: blurFadeIn 3s ease-in 12s backwards;
color: transparent;
text-shadow: 0px 0px 1px #fff;
} */
.sp-container h2.frame-5 span:nth-child(2) {
-webkit-animation-delay: 13s;
-moz-animation-delay: 13s;
-ms-animation-delay: 13s;
animation-delay: 13s;
}
.sp-container h2.frame-5 span:nth-child(3) {
-webkit-animation-delay: 14s;
-moz-animation-delay: 14s;
-ms-animation-delay: 14s;
animation-delay: 14s;
}
.sp-globe {
position: absolute;
width: 282px;
height: 273px;
left: 50%;
top: 50%;
margin: -137px 0 0 -141px;
background: transparent url(http://web-sonick.zz.mu/images/sl/globe.png) no-repeat top left;
-webkit-animation: fadeInBack 3.6s linear 14s backwards;
-moz-animation: fadeInBack 3.6s linear 14s backwards;
-ms-animation: fadeInBack 3.6s linear 14s backwards;
animation: fadeInBack 3.6s linear 14s backwards;
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=30)";
filter: alpha(opacity=30);
opacity: 0.3;
-webkit-transform: scale(5);
-moz-transform: scale(5);
-o-transform: scale(5);
-ms-transform: scale(5);
transform: scale(5);
}
.sp-circle-link {
position: absolute;
left: 50%;
bottom: 100px;
margin-left: -50px;
text-align: center;
line-height: 100px;
width: 100px;
height: 100px;
background: #fff;
color: #3f1616;
font-size: 25px;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
border-radius: 50%;
-webkit-animation: fadeInRotate 1s linear 16s backwards;
-moz-animation: fadeInRotate 1s linear 16s backwards;
-ms-animation: fadeInRotate 1s linear 16s backwards;
animation: fadeInRotate 1s linear 16s backwards;
-webkit-transform: scale(1) rotate(0deg);
-moz-transform: scale(1) rotate(0deg);
-o-transform: scale(1) rotate(0deg);
-ms-transform: scale(1) rotate(0deg);
transform: scale(1) rotate(0deg);
}
.sp-circle-link:hover {
background: #85373b;
color: #fff;
}
/**/
@-webkit-keyframes blurFadeInOut{
0%{
opacity: 0;
text-shadow: 0px 0px 40px #fff;
-webkit-transform: scale(1.3);
}
20%,75%{
opacity: 1;
text-shadow: 0px 0px 1px #fff;
-webkit-transform: scale(1);
}
100%{
opacity: 0;
text-shadow: 0px 0px 50px #fff;
-webkit-transform: scale(0);
}
}
@-webkit-keyframes blurFadeIn{
0%{
opacity: 0;
text-shadow: 0px 0px 40px #fff;
-webkit-transform: scale(1.3);
}
50%{
opacity: 0.5;
text-shadow: 0px 0px 10px #fff;
-webkit-transform: scale(1.1);
}
100%{
opacity: 1;
text-shadow: 0px 0px 1px #fff;
-webkit-transform: scale(1);
}
}
@-webkit-keyframes fadeInBack{
0%{
opacity: 0;
-webkit-transform: scale(0);
}
50%{
opacity: 0.4;
-webkit-transform: scale(2);
}
100%{
opacity: 0.2;
-webkit-transform: scale(5);
}
}
@-webkit-keyframes fadeInRotate{
0%{
opacity: 0;
-webkit-transform: scale(0) rotate(360deg);
}
100%{
opacity: 1;
-webkit-transform: scale(1) rotate(0deg);
}
}
/**/
@-moz-keyframes blurFadeInOut{
0%{
opacity: 0;
text-shadow: 0px 0px 40px #fff;
-moz-transform: scale(1.3);
}
20%,75%{
opacity: 1;
text-shadow: 0px 0px 1px #fff;
-moz-transform: scale(1);
}
100%{
opacity: 0;
text-shadow: 0px 0px 50px #fff;
-moz-transform: scale(0);
}
}
@-moz-keyframes blurFadeIn{
0%{
opacity: 0;
text-shadow: 0px 0px 40px #fff;
-moz-transform: scale(1.3);
}
100%{
opacity: 1;
text-shadow: 0px 0px 1px #fff;
-moz-transform: scale(1);
}
}
@-moz-keyframes fadeInBack{
0%{
opacity: 0;
-moz-transform: scale(0);
}
50%{
opacity: 0.4;
-moz-transform: scale(2);
}
100%{
opacity: 0.2;
-moz-transform: scale(5);
}
}
@-moz-keyframes fadeInRotate{
0%{
opacity: 0;
-moz-transform: scale(0) rotate(360deg);
}
100%{
opacity: 1;
-moz-transform: scale(1) rotate(0deg);
}
}
/**/
@keyframes blurFadeInOut{
0%{
opacity: 0;
text-shadow: 0px 0px 40px #fff;
transform: scale(1.3);
}
20%,75%{
opacity: 1;
text-shadow: 0px 0px 1px #fff;
transform: scale(1);
}
100%{
opacity: 0;
text-shadow: 0px 0px 50px #fff;
transform: scale(0);
}
}
@keyframes blurFadeIn{
0%{
opacity: 0;
text-shadow: 0px 0px 40px #fff;
transform: scale(1.3);
}
50%{
opacity: 0.5;
text-shadow: 0px 0px 10px #fff;
transform: scale(1.1);
}
100%{
opacity: 1;
text-shadow: 0px 0px 1px #fff;
transform: scale(1);
}
}
@keyframes fadeInBack{
0%{
opacity: 0;
transform: scale(0);
}
50%{
opacity: 0.4;
transform: scale(2);
}
100%{
opacity: 0.2;
transform: scale(5);
}
}
@keyframes fadeInRotate{
0%{
opacity: 0;
transform: scale(0) rotate(360deg);
}
100%{
opacity: 1;
transform: scale(1) rotate(0deg);
}
}
<div class="container">
<div class="header">
<div class="clr"></div>
</div>
<div class="sp-container">
<div class="sp-content">
<div class="sp-globe"></div>
<h2 style="font-size:75px;font-family:bold;" class="frame-6"><span>WE </span> <span>STAND </span> <span>FOR</span></h2>
<h2 style="font-size:68px;" class="frame-1">INNOVATION</h2>
<h2 style="font-size:68px;" class="frame-2">QUALITY</h2>
<h2 style="font-size:68px;" class="frame-3">RELIABILITY</h2>
<h2 style="font-size:68px;" class="frame-4">SAFETY</h2>
<h2 style="font-size:68px;" class="frame-7">VALUES</h2>
<h2 style="font-size:68px;" class="frame-8">HARMONY</h2>
<h2 style="font-size:68px;" class="frame-9">UNITY</h2>
<h2 style="font-size:75px;font-family:bold;" class="frame-5"><span>CUSTOMER</span> </h2>
</div>
</div>
</div>
A: I don't really understand your code, but what you can do is to create an animation for each element and define the same duration for each element of the animation (the total animation time).
After that, you just have to handle "what is displayed when" using %
In my example, I will handle 4 elements, so 25% of the total time for each one (and +/-5% for fadeIn fadeOut)
.el-1, .el-2, .el-3, .el-4 {
position: absolute;
width: 100px;
height: 100px;
animation-duration: 10s; /* Total time */
animation-iteration-count: infinite;
animation-delay: 0; /* by default */
}
.el-1 {
animation-name: example-1;
background: red;
}
.el-2 {
animation-name: example-2;
background: green;
}
.el-3 {
animation-name: example-3;
background: blue;
}
.el-4 {
animation-name: example-4;
background: yellow;
}
@keyframes example-1 {
0% {opacity: 0;}
5% {opacity: 1;}
20% {opacity: 1;}
30% {opacity: 0;}
100% {opacity: 0;}
}
@keyframes example-2 {
0% {opacity: 0;}
20% {opacity: 0;}
30% {opacity: 1;}
40% {opacity: 1;}
60% {opacity: 0;}
100% {opacity: 0;}
}
@keyframes example-3 {
0% {opacity: 0;}
40% {opacity: 0;}
60% {opacity: 1;}
70% {opacity: 1;}
80% {opacity: 0;}
100% {opacity: 0;}
}
@keyframes example-4 {
0% {opacity: 0;}
70% {opacity: 0;}
80% {opacity: 1;}
95% {opacity: 1;}
100% {opacity: 0;}
}
<div class="el-1">1</div>
<div class="el-2">2</div>
<div class="el-3">3</div>
<div class="el-4">4</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37882776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Neo4j Cypher query empty collect makes the entire result empty I have been facing wierd problem, I have tried to get data from the neo4j graph that I have built.Here is my query
MATCH (u1:User {user_id: 4})-[:FOLLOWS]->(u2:User)-[]->(r1:Rest{city_id: 1})
WITH COLLECT ({ REST: r1.res_id}) as rows
MATCH (u1:User {user_id: 4})-[rel]->(r2:Rest{city_id: 1})
WHERE NOT (u1:User {user_id: 4})-[rel : BEEN_THERE | ADD_REVIEW]->(r2:Rest{city_id: 1})
WITH rows + COLLECT ({ REST: r2.res_id}) AS allrows
UNWIND allrows as row
RETURN row.REST as RESTAURANT_ID, count(row.REST) as COUNT
ORDER BY COUNT desc
LIMIT 15;
However when the result of COLLECT ({ REST: r2.res_id}) are empty the entire result becomes empty. Also the query is unable to identify rows from 1st match and return undefined rows. Please let me know. Thanks!
A: If the pattern doesn't match any path, the result will be empty indeed.
You have to split the MATCH in 2 and make the second one OPTIONAL, or in your actual case, stop matching the same u1 node over and over again:
MATCH (u1:User {user_id: 4})
OPTIONAL MATCH (u1)-[:FOLLOWS]->(:User)-->(r1:Rest {city_id: 1})
WITH u1, collect({ REST: r1.res_id }) AS rows
OPTIONAL MATCH (u1)-->(r2:Rest {city_id: 1})
WHERE NOT (u1)-[:BEEN_THERE | ADD_REVIEW]->(r2)
WITH rows + collect({ REST: r2.res_id }) AS allrows
UNWIND allrows as row
RETURN row.REST AS RESTAURANT_ID, count(row.REST) AS COUNT
ORDER BY COUNT desc
LIMIT 15
I'm not sure about the first OPTIONAL MATCH in your case (you only mention the second collect as being a blocker), but if you want the aggregation of both patterns where each can be empty, here you go.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39613457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: FragmentTabPager not working at all I'm trying to implement FragmentTabPager Activity, but it doesn't run at all. Once I call the activity the app stops immediately. I've used tried multiple sources of code/tutorial including developers.android, but the same problem happens with all of them. And from what I understand, no one has faced the same problem(at least they haven't written about it). THis leads me to believe that I am making some stupid mistake. I've spent over 2 days on this. Heres the code for my fragmentTabPager activity:
package com.my.pack;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TabHost;
import android.widget.TabWidget;
import java.util.ArrayList;
public class FragmentTabsPager extends FragmentActivity {
TabHost mTabHost;
ViewPager mViewPager;
TabsAdapter mTabsAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabs_viewpager_layout);
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
mViewPager = (ViewPager) findViewById(R.id.pager);
// Create our tab adapter
mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
// add our tabs to the adapter
mTabsAdapter.addTab(mTabHost.newTabSpec("forex").setIndicator("Forex"),
Forex.class, null);
mTabsAdapter.addTab(mTabHost.newTabSpec("stocks")
.setIndicator("Stocks"), Stocks.class, null);
mTabsAdapter.addTab(
mTabHost.newTabSpec("commodities").setIndicator("Commodities"),
Commodities.class, null);
/*
* mTabsAdapter.addTab(mTabHost.newTabSpec("throttle").setIndicator(
* "Throttle"), LoaderThrottleSupport.ThrottledLoaderListFragment.class,
* null);
*/
if (savedInstanceState != null) {
// restore the last selected tab if we can
mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("tab", mTabHost.getCurrentTabTag());
}
public static class TabsAdapter extends FragmentPagerAdapter implements
TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
private final Context mContext;
private final TabHost mTabHost;
private final ViewPager mViewPager;
private final ArrayList mTabs = new ArrayList();
static final class TabInfo {
private final String tag;
private final Class clss;
private final Bundle args;
TabInfo(String _tag, Class _class, Bundle _args) {
tag = _tag;
clss = _class;
args = _args;
}
}
static class DummyTabFactory implements TabHost.TabContentFactory {
private final Context mContext;
public DummyTabFactory(Context context) {
mContext = context;
}
public View createTabContent(String tag) {
View v = new View(mContext);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
public TabsAdapter(FragmentActivity activity, TabHost tabHost,
ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mTabHost = tabHost;
mViewPager = pager;
mTabHost.setOnTabChangedListener(this);
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(TabHost.TabSpec tabSpec, Class clss, Bundle args) {
tabSpec.setContent(new DummyTabFactory(mContext));
String tag = tabSpec.getTag();
TabInfo info = new TabInfo(tag, clss, args);
mTabs.add(info);
mTabHost.addTab(tabSpec);
notifyDataSetChanged();
}
@Override
public int getCount() {
return mTabs.size();
}
@Override
public Fragment getItem(int position) {
TabInfo info = (TabInfo) mTabs.get(position);
// Create a new fragment if necessary.
return Fragment.instantiate(mContext, info.clss.getName(),
info.args);
}
public void onTabChanged(String tabId) {
// called when the user clicks on a tab.
int position = mTabHost.getCurrentTab();
mViewPager.setCurrentItem(position);
}
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
public void onPageSelected(int position) {
TabWidget widget = mTabHost.getTabWidget();
int oldFocusability = widget.getDescendantFocusability();
widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
mTabHost.setCurrentTab(position);
widget.setDescendantFocusability(oldFocusability);
}
public void onPageScrollStateChanged(int state) {
}
}
}
And my manifest looks like:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.my.pack"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".Main"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".FragmentTabsPager"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.FRAGMENTTABSPAGER" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".Stocks"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.STOCKS" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".Commodities"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.COMMODITIES" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".Forex"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.FOREX" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
The xml of tabs_viewpager_layout file:
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabWidget
android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:orientation="horizontal" />
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
And my main from which I wish to call my fragmentTab activity:
package com.my.pack;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Main extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myintent = new Intent(Main.this, FragmentTabsPager.class);
startActivity(myintent);
}
});
}
}
I know my 3 Forex, stock, etc. pager activites are running without a hitch. I checked by changing the intent in main to Forex.class and all 3 work fine. I also thought that the activity had to be a LAUNCHER activity and tried that only to fail. Thanks in advance. Any help would be GREATLY appreciated.
My logcat is..
04-08 19:05:24.839: D/AndroidRuntime(1332): Shutting down VM
04-08 19:05:24.839: W/dalvikvm(1332): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
04-08 19:05:24.869: E/AndroidRuntime(1332): FATAL EXCEPTION: main
04-08 19:05:24.869: E/AndroidRuntime(1332): java.lang.ClassCastException: com.my.pack.Forex
04-08 19:05:24.869: E/AndroidRuntime(1332): at android.support.v4.app.Fragment.instantiate(Fragment.java:384)
04-08 19:05:24.869: E/AndroidRuntime(1332): at com.my.pack.FragmentTabsPager$TabsAdapter.getItem(FragmentTabsPager.java:124)
04-08 19:05:24.869: E/AndroidRuntime(1332): at android.support.v4.app.FragmentPagerAdapter.instantiateItem(FragmentPagerAdapter.java:95)
04-08 19:05:24.869: E/AndroidRuntime(1332): at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:649)
04-08 19:05:24.869: E/AndroidRuntime(1332): at android.support.v4.view.ViewPager.populate(ViewPager.java:783)
04-08 19:05:24.869: E/AndroidRuntime(1332): at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1016)
04-08 19:05:24.869: E/AndroidRuntime(1332): at android.view.View.measure(View.java:8171)
04-08 19:05:24.869: E/AndroidRuntime(1332): at android.widget.LinearLayout.measureVertical(LinearLayout.java:526)
04-08 19:05:24.869: E/AndroidRuntime(1332): at android.widget.LinearLayout.onMeasure(LinearLayout.java:304)
04-08 19:05:24.869: E/AndroidRuntime(1332): at android.view.View.measure(View.java:8171)
04-08 19:05:24.869: E/AndroidRuntime(1332): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
04-08 19:05:24.869: E/AndroidRuntime(1332): at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
04-08 19:05:24.869: E/AndroidRuntime(1332): at android.view.View.measure(View.java:8171)
04-08 19:05:24.869: E/AndroidRuntime(1332): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
04-08 19:05:24.869: E/AndroidRuntime(1332): at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
04-08 19:05:24.869: E/AndroidRuntime(1332): at android.view.View.measure(View.java:8171)
04-08 19:05:24.869: E/AndroidRuntime(1332): at android.widget.LinearLayout.measureVertical(LinearLayout.java:526)
04-08 19:05:24.869: E/AndroidRuntime(1332): at android.widget.LinearLayout.onMeasure(LinearLayout.java:304)
04-08 19:05:24.869: E/AndroidRuntime(1332): at android.view.View.measure(View.java:8171)
04-08 19:05:24.869: E/AndroidRuntime(1332): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
04-08 19:05:24.869: E/AndroidRuntime(1332): at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
04-08 19:05:24.869: E/AndroidRuntime(1332): at android.view.View.measure(View.java:8171)
04-08 19:05:24.869: E/AndroidRuntime(1332): at android.view.ViewRoot.performTraversals(ViewRoot.java:801)
04-08 19:05:24.869: E/AndroidRuntime(1332): at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
04-08 19:05:24.869: E/AndroidRuntime(1332): at android.os.Handler.dispatchMessage(Handler.java:99)
04-08 19:05:24.869: E/AndroidRuntime(1332): at android.os.Looper.loop(Looper.java:123)
04-08 19:05:24.869: E/AndroidRuntime(1332): at android.app.ActivityThread.main(ActivityThread.java:4627)
04-08 19:05:24.869: E/AndroidRuntime(1332): at java.lang.reflect.Method.invokeNative(Native Method)
04-08 19:05:24.869: E/AndroidRuntime(1332): at java.lang.reflect.Method.invoke(Method.java:521)
04-08 19:05:24.869: E/AndroidRuntime(1332): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-08 19:05:24.869: E/AndroidRuntime(1332): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-08 19:05:24.869: E/AndroidRuntime(1332): at dalvik.system.NativeStart.main(Native Method)
04-08 19:05:27.898: I/Process(1332): Sending signal. PID: 1332 SIG: 9
A: Do you have duplicate android:id tags in any of those three activities? I've read that such a situation could cause an issue.
Ah, here's the link to where I read that: ClassCastException
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10062692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Inserting additional code into the onclick attribute of a submit button using jquery I'm having trouble trying to properly insert additional code into the onclick attribute of a submit button. I don't want to overwrite anything within the onclick but just add additional code. I have successfully inserted the code needed but when I look at the source code of the button it shows some additional functionality that shouldn't be there so i don't think I have it written out properly.
Here's the button:
<input id='TESTFrmSubmit' type='submit' value='Submit' name='submitButton' onclick='formSubmit(document.getElementById("TESTForm_1001")); return false;' />
The additional code I want to insert into the onclick attribute is:
'_gaq.push(['_trackEvent', 'Whitepaper Campaign', 'Submit Button','conceptshareexample.pdf'']);'
The jquery I have that inserts the additonal code into the onclick attribute is:
$(document).ready(function(){
$("#TESTFrmSubmit").attr ("onclick", function() {
return this.onclick + "'_gaq.push(['_trackEvent', 'Whitepaper Campaign', 'Submit Button','TESTexample.pdf'']);'";
});
});
The problem I'm having is that when i view the source code of the button, it contains
function onclick(event) within the onclick displaying it like so:
onclick="function onclick(event){ formSubmit(document.getElementById("TESTForm_1010")); return false; }_gaq.push(['_trackEvent', 'Whitepaper Campaign', 'Submit Button','TESTexample.pdf'']);"
I need it to display it like this without the function onclick(event):
onclick="{formSubmit(document.getElementById("TESTForm_1010")); return false; }_gaq.push(['_trackEvent', 'Whitepaper Campaign', 'Submit Button','TESTexample.pdf'']);"
Please help! this has been racking my brain...
A: Instead of setting .attr('onclick', you can bind into the event handler directly:
$('#mktFrmSubmit').click(function ()
{
doSomething();
alert('hi');
}
$('#mktFrmSubmit').click(function ()
{
alert('We can also bind to .click multiple times, and it adds events');
// Instead of just overwriting them
}
Now clicking #mktFrmSubmit will fire both those click handlers.
A: this.onclick
is returning the
function onclick(event) {...
To accomplish what you want, use this:
$(document).ready(function(){
$("#mktFrmSubmit").attr ("onclick", function() {
_gaq.push(['_trackEvent', 'Whitepaper Campaign', 'Submit Button','conceptshareexample.pdf']);
formSubmit(document.getElementById("TESTForm_1001")); return false;
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9224689",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JavaScript Double Select I have a problem with 3 Select Box's I have. The second and third should populate after select the first and second select box.
After select a value from Select Box 1, it populates Select Box 2.
After select a value from Select Box 2, it populates Select Box 3.
I have two problems with my code:
*
*It populates automatically the second select box based on first value, but doesn't populate the third select box
*After change it populates the select box, but If I change the first select box, it updates the second select box but the third isn't updated based on the values of the second select box. It only populates after I change the value in the second select box.
My Code:
<script type="text/javascript">
jQuery(document).ready(function() {
$("#category").change(function(){
getSubCat();//get sub category after change event
});
$("#subcategory").change(function(){
getSubSubCat(); //get sub category after change event
});
getSubCat();//get sub category after page load
getSubSubCat();
function getSubCat(){
var selectedCategory = $("#category option:selected").val();
$.ajax({
type: "POST",
url: "subcat.php",
data: { category : selectedCategory }
}).done(function(data){
$("#subcategory").html(data);
});
}
function getSubSubCat(){
var selectedSubCategory = $("#subcategory option:selected").val();
$.ajax({
type: "POST",
url: "subsubcat.php",
data: { subcategory : selectedSubCategory }
}).done(function(data){
$("#subsubcategory").html(data);
});
}
});
</script>
Can you help me please?
A: The .done() function of getSubCat() should call getSubSubCat().
function getSubCat(){
var selectedCategory = $("#category option:selected").val();
$.ajax({
type: "POST",
url: "subcat.php",
data: { category : selectedCategory }
}).done(function(data){
$("#subcategory").html(data);
getSubSubCat();
});
}
When you call getSubSubCat() during page load, getSubCat() hasn't finished yet (because AJAX is asynchronous), so none of its changes to the second menu have been made.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46854429",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Make the BODY DIV Fill the Available Area I'm working on a brand new website and I'm trying to just get the basic layout going. I am using the ASP.NET MVC 4 generated HTML and I would like to get the DIV named body to fill the available space after making room for the header and thus anchoring the footer to the bottom of the browser window. However, what I'm getting right now is three panels just stacked on top of each other.
I would like a solution that would work if the browser supported HTML5 and one if it didn't
Please note I've inlined comments in the CSS to try and explain what I've tried.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title - Title</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
@Styles.Render("~/Content/css")
</head>
<body>
<header>
<div class="content-wrapper">
<div class="float-left">
<p class="site-title">@Html.ActionLink("Title", "Index", "Home")</p>
</div>
</div>
</header>
<div id="body">
@RenderSection("featured", required: false)
<section class="content-wrapper main-content clear-fix">
@RenderBody()
</section>
</div>
<footer>
<div class="content-wrapper">
<div class="float-left">
<p>© @DateTime.Now.Year - ACME. All rights reserved.</p>
</div>
<div class="float-right">
<ul id="social">
<li><a href="http://facebook.com" class="facebook">Facebook</a></li>
<li><a href="http://twitter.com" class="twitter">Twitter</a></li>
</ul>
</div>
</div>
</footer>
@RenderSection("scripts", required: false)
</body>
</html>
CSS
body {
/* I'VE TRIED BOTH OF THE FOLLOWING TO SEE IF THE BODY ITSELF WOULD SPAN */
/* WITH NO OTHER CSS APPLIED TO THE body ELEMENT */
/*height: fill-available;*/
/*height: 100%*/
}
/* general layout
----------------------------------------------------------*/
.float-left {
float: left;
}
.float-right {
float: right;
}
.clear-fix:after {
content: ".";
clear: both;
display: block;
height: 0;
visibility: hidden;
}
/* main layout
----------------------------------------------------------*/
.content-wrapper {
margin: 0 auto;
max-width: 960px;
}
#body {
background-color: #efeeef;
clear: both;
padding-bottom: 35px;
/* I'VE TRIED BOTH OF THE FOLLOWING TO SEE IF I COULD GET THIS ELEMENT TO SPAN */
/* WITHOUT ANY OTHER CSS APPLIED TO THE body TAG */
/*height: fill-available;*/
/*height: 100%*/
}
.main-content {
/*background: url("../Images/accent.png") no-repeat;*/
padding-left: 10px;
padding-top: 30px;
}
.featured + .main-content {
/*background: url("../Images/heroAccent.png") no-repeat;*/
}
footer {
clear: both;
background-color: #e2e2e2;
font-size: .8em;
height: 100px;
}
/* site title
----------------------------------------------------------*/
.site-title {
color: #c8c8c8;
font-family: Rockwell, Consolas, "Courier New", Courier, monospace;
font-size: 2.3em;
margin: 20px 0;
}
.site-title a, .site-title a:hover, .site-title a:active {
background: none;
color: #c8c8c8;
outline: none;
text-decoration: none;
}
/* social
----------------------------------------------------------*/
ul#social li {
display: inline;
list-style: none;
}
ul#social li a {
color: #999;
text-decoration: none;
}
a.facebook, a.twitter {
display: block;
float: left;
height: 24px;
padding-left: 17px;
text-indent: -9999px;
width: 16px;
}
a.facebook {
background: url("../Images/facebook.png") no-repeat;
}
a.twitter {
background: url("../Images/twitter.png") no-repeat;
}
A: Just snap the header and footer at the bottom of the page using fixed positioning.
header, footer{ position:fixed; left:0; right:0; z-index:1; }
header{ top:0; }
footer{ bottom:0; }
Then you can give your body the background your div#body had before. The div gets no background and will expand as much as needed.
div#body{ background:none; }
body{ background:#eee; }
This will look like the div would fill the remaining space of the page. Finally give your header and footer a background so that you can't see the background of the body under it.
header, footer{ background:#fff; }
By the way I would suggest removing body margins. body{ margin:0; }
A: I believe it's a bit impossible to do that with just CSS. You can make a webpage with 100% height like this:
html{
height: 100%;
}
body{
height: 100%;
}
#body{
height: 100%;
}
And then for header, body and footer you can do like this:
header{
height: 100px;
left: 0;
position: absolute;
top: 0;
width: 100%;
background-color: #f00;
}
#body{
bottom: 100px;
left: 0;
position: absolute;
right: 0;
top: 100px;
background-color: #fff;
}
footer{
bottom: 0;
height: 100px;
left: 0;
position: absolute;
width: 100%;
background-color: #ff0;
}
It might work for a bit, but it'll break at some point. When you resize your browser, it'll be running out of room for your #body. If you want a better solution, you should use javascript. In your javascript, calculate how much space you have for your #body, then either adjust the height of header and footer. Or adjust the #body instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11909683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Passing a pointer for a dynamic runtime function I'm trying to write a generic utility function for a class that applies a function to each element of a vector with the only input argument being the value of that element. The idea being that I can use that to support scalar addition/multiplication as well as user-specified functions without duplicating too much code. It works fine for the user-specified functions, but I'm struggling with how the best implement it for scalar addition/multiplication.
The code below is a simplified version of what I'm playing around with. It works fine, but what I want to be able to do is have the "5" in the lambda expression be a variable passed in separately, but not necessarily passed into "apply_f". So keep apply_f only taking a vector an a function pointer. I'm aware of the captures field for lambda expressions, but I was having trouble passing a lambda function with a capture into another function. I'm also aware of something like std::bind, but couldn't get that to work either.
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
void apply_f(vector<double>& vec, double (*f)(double)) {
transform(vec.begin(), vec.end(), vec.begin(), f);
}
int main() {
vector<double> x {1, 2, 3};
auto f = [](double x){ return x + 5; };
apply_f(x, f);
cout << x[0] << endl;
cout << x[1] << endl;
cout << x[2] << endl;
}
A: Simply take a parameter with a unique type:
template <class F>
void apply_f(vector<double>& vec, F f) {
transform(vec.begin(), vec.end(), vec.begin(), f);
}
Not only it will work, but you will get way better performance since the compiler knows the actual type being passed.
A: Unfortunately, lambdas are not just pointers to functions (because they can have state, for instance). You can change your code to use a std::function<double(double) instead of a double(*)(double), and this can capture a lambda (you may need to pass std::cref(f) instead of just f).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52683634",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Peewee ArrayField error When I create my table based on a model without an ArrayField, I get no errors.
When I add:
images = ArrayField(CharField)
I get:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/site-packages/peewee.py", line 5037, in create_table
db.create_table(cls)
File "/usr/local/lib/python3.6/site-packages/peewee.py", line 3914, in create_table
return self.execute_sql(*qc.create_table(model_class, safe))
File "/usr/local/lib/python3.6/site-packages/peewee.py", line 3837, in execute_sql
self.commit()
File "/usr/local/lib/python3.6/site-packages/peewee.py", line 3656, in __exit__
reraise(new_type, new_type(*exc_args), traceback)
File "/usr/local/lib/python3.6/site-packages/peewee.py", line 135, in reraise
raise value.with_traceback(tb)
File "/usr/local/lib/python3.6/site-packages/peewee.py", line 3830, in execute_sql
cursor.execute(sql, params or ())
peewee.OperationalError: near "[]": syntax error
Can anyone point out why and provide a solution?
A: What database driver are you using? ArrayField requires postgresql.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47970063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: (python) solving transcendental equation i need to solve following equation:
0 = -1 / x**0.5) - 2 * log((alpha * x**0.5) + beta)
alpha and beta are given, i just need to iterate x until a certain extent.
I'm not a great python programmer, but like to implement this one.
How might this be possible?
Best regards
A: The smartest to do would be to implement a solve function like Stanislav recommended. You can't just iterate over values of x until the equation reaches 0 due to Floating Point Arithmetic. You would have to .floor or .ceil your value to avoid an infinity loop. An example of this would be something like:
x = 0
while True:
x += 0.1
print(x)
if x == 10:
break
Here you'd think that x eventually reaches 10 when it adds 0.1 to 9.9, but this will continue forever. Now, I don't know if your values are integers or floats, but what I'm getting at is: Don't iterate. Use already built solve libraries.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40489853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why do null columns behave differently with the count aggragate function? In oracle, we have a task to count the number of rows that have a specific null collumn.
I have the query:
select count(MY_COL) from My_Table where MY_COL is null;
this returns zero results.
Why does this return zero results and the query
select count(*) from My_Table where MY_COL is null;
return the correct results?
A: Both results are correct.
select count(col_name) counts the records where col_name is not null while select count(*) counts all records, regardless of any null values.
This is documented on Tahiti:
If you specify expr, then COUNT returns the number of rows where expr is not null. You can count either all rows, or only distinct values of expr.
If you specify the asterisk (*), then this function returns all rows, including duplicates and nulls.
COUNT never returns null.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18667381",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can't install python, pip related apps through Ansible I am using below ansible yml file to install python, pip, etc.
roles/python/main.yml:
---
- name: python
apt:
pkg: python
- name: python-pip
apt:
pkg: python-pip
- name: mongopy
pip:
pkg: mongopy
- name: mtools
pip:
pkg: mtools
when I run ansible-playbook on this script, I get below
PLAY [ec2] ***********************************************************************************************************************************************************************************************
TASK [Gathering Facts] ***********************************************************************************************************************************************************************************
ok: [xxxxx.ap-southeast-2.compute.amazonaws.com]
PLAY RECAP ***********************************************************************************************************************************************************************************************
xxxxxap-southeast-2.compute.amazonaws.com : ok=1 changed=0 unreachable=0 failed=0
there is no error on them but I checked these apps are not installed on the remote host. What wrong with my yml file? Is there any place I can check what the error is?
below is my playbook:
python.yml:
---
- hosts: ec2
remote_user: ubuntu
roles:
- python
below is the command I run:
ansible-playbook -i hosts python.yml
A: There are no tasks in your python role. Please have a look at the role structure.
If roles/x/tasks/main.yml exists, tasks listed therein will be added to the play
Tasks file (main.yml) should be placed in the tasks subdirectory of the role, not in the main role's directory.
And this has nothing to do with how you described the problem (installing Python or Pip). Even if you replaced the tasks with a single debug task which displays Hello world by default, it would not run.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45472916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SpringBoot project gradle build 'bootRepackage' task fails because it is unable to rename jar When running 'gradle clean build' on my spring boot project (version 1.3.6.RELEASE) on windows 10 (as administrator), the build fails on the 'bootRepackage' task on one of my modules with the following stacktrace
:myProjectModule:findMainClass
:myProjectModule:bootRepackage FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':myProjectModule:bootRepackage'.
> Unable to rename 'D:\dev\myProject\myProjectModule\build\libs\myProjectModule-0.0.8-SNAPSHOT.jar' to 'D:\dev\myProject\myProjectModule\build\libs\myProjectModule-0.0.8-SNAPSHOT.jar.original'
* Try:
Run with --info or --debug option to get more log output.
* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':myProjectModule:bootRepackage'.
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:66)
at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:203)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:185)
at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:66)
at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:50)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:25)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:110)
at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
at org.gradle.initialization.DefaultGradleLauncher$4.run(DefaultGradleLauncher.java:153)
at org.gradle.internal.Factories$1.create(Factories.java:22)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:91)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:53)
at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:150)
at org.gradle.initialization.DefaultGradleLauncher.access$200(DefaultGradleLauncher.java:32)
at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.java:98)
at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.java:92)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:91)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:63)
at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:92)
at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:83)
at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:99)
at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:48)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:30)
at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:81)
at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:46)
at org.gradle.launcher.exec.DaemonUsageSuggestingBuildActionExecuter.execute(DaemonUsageSuggestingBuildActionExecuter.java:51)
at org.gradle.launcher.exec.DaemonUsageSuggestingBuildActionExecuter.execute(DaemonUsageSuggestingBuildActionExecuter.java:28)
at org.gradle.launcher.cli.RunBuildAction.run(RunBuildAction.java:43)
at org.gradle.internal.Actions$RunnableActionAdapter.execute(Actions.java:173)
at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:239)
at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:212)
at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:35)
at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:24)
at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:33)
at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:22)
at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:205)
at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:169)
at org.gradle.launcher.Main.doAction(Main.java:33)
at org.gradle.launcher.bootstrap.EntryPoint.run(EntryPoint.java:45)
at org.gradle.launcher.bootstrap.ProcessBootstrap.runNoExit(ProcessBootstrap.java:55)
at org.gradle.launcher.bootstrap.ProcessBootstrap.run(ProcessBootstrap.java:36)
at org.gradle.launcher.GradleMain.main(GradleMain.java:23)
at org.gradle.wrapper.BootstrapMainStarter.start(BootstrapMainStarter.java:30)
at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:129)
at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)
Caused by: java.lang.IllegalStateException: Unable to rename 'D:\dev\myProject\myProjectModule\build\libs\myProjectModule-0.0.8-SNAPSHOT.jar' to 'D:\dev\myProject\myProjectModule\build\libs\myProjectModule-0.0.8-SNAPSHOT.jar.original'
at org.springframework.boot.loader.tools.Repackager.renameFile(Repackager.java:285)
at org.springframework.boot.loader.tools.Repackager.repackage(Repackager.java:138)
at org.springframework.boot.gradle.repackage.RepackageTask$RepackageAction.repackage(RepackageTask.java:226)
at org.springframework.boot.gradle.repackage.RepackageTask$RepackageAction.execute(RepackageTask.java:190)
at org.springframework.boot.gradle.repackage.RepackageTask$RepackageAction.execute(RepackageTask.java:165)
at org.gradle.internal.Actions$FilteredAction.execute(Actions.java:205)
at org.gradle.api.internal.DefaultDomainObjectCollection.all(DefaultDomainObjectCollection.java:110)
at org.gradle.api.internal.tasks.RealizableTaskCollection.all(RealizableTaskCollection.java:182)
at org.gradle.api.internal.DefaultDomainObjectCollection.withType(DefaultDomainObjectCollection.java:120)
at org.springframework.boot.gradle.repackage.RepackageTask.repackage(RepackageTask.java:140)
at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:75)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.doExecute(AnnotationProcessingTaskFactory.java:228)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:221)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:210)
at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:621)
at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:604)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61)
... 60 more
BUILD FAILED
Total time: 25.024 secs
Build works when executed on a linux os and mac, so it looks like a windows issue.
A: I faced the similar problem. The jar was locked because the server was running using that jar. Terminating the server worked.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40420018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why does setting focus in the OnNavigatedTo() event not set focus? I've got this code in a pages OnNavigatedTo() event:
if (string.IsNullOrWhiteSpace(textBoxGroupName.Text))
{
textBoxGroupName.Focus(FocusState.Programmatic);
}
...but textBoxGroupName does not have focus when the page displays. Why not?
A: OnNavigatedTo happens to early in the page lifetime for setting the focus to work. You should call your code in the Loaded event:
private void MainPage_OnLoaded(object sender, RoutedEventArgs e)
{
if (string.IsNullOrWhiteSpace(textBoxGroupName.Text))
{
textBoxGroupName.Focus(FocusState.Programmatic);
}
}
Of course you need to setup the handler in your .xaml file (I've omitted the other attributes in the Page element:
<Page
Loaded="MainPage_OnLoaded">
A: Only controls that are contained within the GroupBox control can be selected or receive focus. Seems like you are not using GroupBox correctly.
From MSDN
The complete GroupBox itself cannot be selected or receive focus. For more information about how this control responds to the Focus and Select methods, see the following Control members: CanFocus, CanSelect, Focused, ContainsFocus, Focus, Select.
Hint:
You maybe want to use the Controls property to access the child controls:
if (string.IsNullOrWhiteSpace(textBoxGroupName.Text))
{
var child_TextBox = textBoxGroupName.Controls["myTextBox"]
if(child_TextBox.CanFocus)
child_TextBox.Focus(FocusState.Programmatic);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14313447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to handle very very large amount of data in Android? I have a database containing 2 500 000 row of 13-digits numbers (and on end a little bit more - 4 000 000)
The user has to find if a 13-digits number exists in this database, all this on his android phone, without any internet connexion. So what do you suggest to deal with this?
I thought about using SQLITE on Android.
What do you suggest?
A: SQLite will be the best storage option for large data sets on the device. Ensure that where possible you use the correct SQLite query to get the data you need rather then using a general query and doing processing in your own code.
A: This is a bit too much to add in the comments, so I'll add it here.
4,000,000 rows of integers is not that much. Assuming that the integers will use the maximum size of a signed int (8 bytes), your database will be:
4000000 * 8 / 1024 / 1024 = ~30.5mb
That is large, but not game breaking.
Now that also assumes you will need a full 8 bytes per number. We know that we want to store 13 digits per entry, so a 6 byte integer column would suffice:
4000000 * 6 / 1024 / 1024 = ~23mb
A: Hi d3cima may be too late answer but it's help other's. Myself Realm is the best option.
Realm
Realm’s developer-friendly platform makes it easy to build reactive apps, realtime collaborative features, and offline-first experiences.
Advantage's:
*
*faster than SQLite (up to 10x speed up over raw SQLite for normal
operations)
*easy to use
*object conversion handled for you
*convenient for creating and storing data on the fly
I used my project it's more than 10 x then Sqlite.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36197067",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Open an iOS app from a shared link on a Facebook post We need users to open our app from a "...shared a link" on Facebook, or re-direct to the iOS app download page. Is there objective c code available to accomplish this? Thanks.
A: Since you asked for objective-C code, I assume you want to open either the appstore or the app on a certain URL. However, objective-c code is the least of the efforts here since it's mostly configurations that are at work for this.
To open an app you need to provide it a custom URL scheme:
http://iosdevelopertips.com/cocoa/launching-your-own-application-via-a-custom-url-scheme.html
To detect if that app is installed, you can try that URL:
https://developer.apple.com/library/ios/documentation/uikit/reference/UIApplication_Class/index.html#//apple_ref/occ/instm/UIApplication/canOpenURL:
And if not, you can navigate to the appstore instead via a different URL:
How can I link to my app in the App Store (iTunes)?
After you have done all that, the only actual code you need takes something of the form:
NSString *customURL = @"yourscheme://";
NSString *storeURL = @"itms://url_to_your_app";
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:customURL]])
{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:customURL]];
}
else
{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:storeURL]];
}
Opening the app via it's URL can be done from other apps and websites, but will be more difficult to choose whether or not to open the app or store from inside a browser.
A: Apple have documented the process for you. You can just implement it your way.
NSString *iTunesLink = @"https://itunes.apple.com/us/app/apple-store/id375380948?mt=8";
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink]]
You can refer to This document for more info
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26551343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Cannot update global state using Context.API Trying to use Context.API to create a global state and pass it to multiple components. The state will store a few properties including a TwilioToken, device type and a name. I have a component SignupForm that renders a button. When the button is clicked, this triggers a function handleSubmit that takes a username and passes the username as an argument to another function setupTwilio. This function sends the username to an end point that interacts with Twilio Programmable Voice API, sending back a TwilioToken and device type. I then want to update my global state with the Twilio Token and device type and then redirect the user to another page /rooms
Problem is I don't seem to be updating my global state at all, when I console.log(state.TwilioToken) in the component rendered after handleSubmit I get null
Here is my context provider:
const initialState = {
nickname: '',
selectedRoom: null,
rooms: [],
createdRoomTopic: '',
twilioToken: '',
device: null
};
const RoomContext = createContext(null);
export const RoomContextProvider = ({ children }) => {
const[state, setState] = useState(initialState);
return (
<RoomContext.Provider value={[state, setState]}>{children}</RoomContext.Provider>
)
};
export const useGlobalState = () => {
const value = useContext(RoomContext)
if(value === undefined) throw new Error('Please add RoomContextProvider');
return value;
}
My signupform
import { useGlobalState } from '../../context/RoomContextProvider';
...
//without useState() I get the error Uncaught TypeError: object null is not iterable (cannot read property Symbol(Symbol.iterator))
const [state, setState] = useState(useGlobalState());
...
const handleSubmit = e => {
e.preventDefault();
const nickname = user.username;
setupTwilio(nickname);
history.push('/rooms');
}
const setupTwilio = (nickname) => {
console.log('inside setupTwilio function', nickname)
fetch(`http://127.0.0.1:8000/voice_chat/token/${nickname}`)
.then(response => response.json())
.then(data => {
const twilioToken = data.token;
const device = new Device(twilioToken);
device.updateOptions(twilioToken, {
codecPreferences: ['opus', 'pcmu'],
fakeLocalDTMF: true,
maxAverageBitrate: 16000
});
device.on('error', (device) => {
console.log("error: ", device)
});
setState((state) => {
return {...state, device, twilioToken}
});
})
...
};
return (
<button className="button button-primary button-wide-mobile button-sm"
onClick={handleSubmit}> Start Coding
</button>
);
When I console.log my state in the component rendered I get null
import { useGlobalState } from '../../context/RoomContextProvider';
...
const [state, setState] = useState(useGlobalState());
console.log('global state token is', state.twilioToken)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72351491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Flash CS5.5 adds green background to bitmaps with alpha Recently, my Flash began to behave weirdly. I have imported PSD file, where were some layers with transparency. They imported successfully and are OK.
The problem is, when I want to edit them from library with PS. I always worked great, but now flash adds all pixels with alpha green background color (see picture below).
Left: Bitmap with alpha; Right: after clicking on "Edit with ..."
I went through all the settings I've found, but I can't find any solution. Did this happen to you too? Did you solve it?
Thank you for your answers.
EDIT: SOLUTION
I've resetted to the default settings. http://forums.adobe.com/thread/992810
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20188676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I get the string value of the name of a property in a dynamic type in Azure Log Analytics? I have a value of type dynamic, the JSON representation of which looks like:
{ "ReportName": { "Duration": 2347, "RowCount": 1167 } }
I would like to extract the string value "ReportName" from this, as I have many rows with a similar structure, but the name of the "root" property can differ for each one.
This seems like it should be easy, but I am struggling. I have arrived at this juncture by doing an mvexpand on a sub-property of a much larger JSON value/entity further up in my query, which has a variety of different property names inside it.
I have tried casting this to a string (using tostring()) and using jsonextract("$", value), plus several similar variants, but none of them seem to work (I get NULLs back).
Thanks!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48104812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Design practice for container class with multiple collections which reference each other I'm trying to design a class structure with the following:
*
*Container class which holds all the items.
*Item collection class which is inside the Container, where each Item has a unique ID and some other data, including a reference to an ItemStyle.
*ItemStyle collection class which is inside the Container, where each ItemStyle represents a common style of items and also the relationship to other styles.
Relationships can be "Attaches To" where a style has a list of other styles it can attach to, and "Attachments" which is the inverse of that. If a style can "Attach To" another style, then the other style should be able to produce the first style as one of its "Attachments".
The container manages the Items and the ItemStyles. I use unique IDs for everything because I want to be able to serialize to and from XML.
However I keep running into logical problems such as I am trying to deserialize an ItemStyle from XML, but of course it can't generate references to the item IDs that it reads since only the Container itself has access to the other items.
Another issue is I want these classes to be independent to the point where if I have a reference to an Item, I can invoke a list of compatible items such as calling "Item.Attachments" or "Item.AttachesTo". This of course all needs to be calculated by the Container since it is the only class to be able to access both the ItemStyles and the Item collections.
So I'm running into a solution where I am going to have to give each Item and ItemStyle a reference to the Container so they can perform their own lookups and determine their relationship with other items. This seems like bad encapsulation and bad OOP practice, but I can't think of any other way.
I'm trying to compare my code to how a ListView works as an example. A ListView has a ListViewItemCollection and ListViewItems. In user code when you can create a new ListViewItem and when you add it to a ListViewItemCollection, it automatically now has a reference to its parent ListView. When looking at the metadata it shows the ListView reference as only having a getter. Can I assume that it uses an internal set?
Should following the ListView model of owner/item relationship work with my classes?
A: Looking at a tight coupling between all classes involved, I don't think that having a reference to the parent (Container) would be a bad idea. There are many models that rely on having parent reference (typical reason could be to ensure a single parent but other reasons such as validations etc can be a cause) - one of the way to model is to have non-public constructor and construct objects via factory methods. Another way of modelling is to have public constructor but have internal setter to set the parent reference. Whenever child is added to the parent's collection object, the reference is set.
I would prefer the later approach. However, one of the thing that I would do is to avoid direct coupling with Container. Rather, I will introduce IContainer interface that will abstract look-ups needed in children and children (Item/ItemStyle) will know only about IContainer interface.
Yet another reasonable design would be to raise events from children when they want to do look-ups. These will be internal events that will be handled by container when the children are added to it.
Yet another approach would be to have a loose model. Essentially, Item can maintain its own ItemStyle references. Whenever needed, Container can build ItemStyle collection by implementing visitor pattern.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9781300",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is it possible to put different datatypes in the same List<> Is it possible to put different datatypes in the same List<> in C#?
myList.Add("Joe");
myList.Add(25);
A: Assuming you are using Java, yes. Everything is an Object in Java and Arrays take Objects. Good luck getting them back out though.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13746194",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I fix my image not being pasted correctly? I am trying to crop a image into a circulor form (which works) and then pasting it to a white backround.
from PIL import Image,ImageFont,ImageDraw, ImageOps, ImageFilter
from io import BytesIO
import numpy as np
pfp = Image.open(avatar)
# cropping to circle
img=pfp.convert("RGB")
npImage=np.array(img)
h,w=img.size
alpha = Image.new('L', img.size,0)
draw = ImageDraw.Draw(alpha)
draw.pieslice([0,0,h,w],0,360,fill=255)
npAlpha=np.array(alpha)
npImage=np.dstack((npImage,npAlpha))
Image.fromarray(npImage).save('result.png')
background = Image.open('white2.png')
background.paste(Image.open('result.png'), (200, 200, h, w))
background.save('combined.png')
Heres what the cropped image looks like(It looks like it has a white background but that's it's transparent):
Cropped Image
But then when I paste it to the white background it changes to a square:
Pasted Image
Here is the original image I am working with:
Image
A: What you're doing is setting the Alpha of any pixel outside that circle to 0, so when you render it, it's gone, but that pixel data is still there. That's not a problem, but it important to know.
Problem
Your "white2.png" image does not have an alpha channel. Even if it's a PNG file, you have to add an alpha channel using your image editing tool. You can print("BGN:", background.getbands()), to see the channels it has. You'll see it says 'R','G','B', but no 'A'.
Solution 1
Replace your paste line with:
background.paste(pfp, (200, 200), alpha)
Here, we use the loaded in avatar as is, and the third argument is a mask which PIL figures out how to use to mask the image before pasting.
Solution 2
Give your white background image an alpha channel.
MS Paint doesn't do this. You have to use something else.
For GIMP, you simply right-click on the layer and click Add Alpha-channel.
Oh, and something worth noting.
Documentation for Paste.
See alpha_composite() if you want to combine images with respect to their alpha channels.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70131857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to get the meta value of the ACF field (wordpress)? I need to get the meta value of the ACF field.
ACF field called 'submitdate' (format => Date Time picker : Y-m-d H:i:s) already has data '2021-06-11 17:23:36'
I tried the following code, but it only shows correct $post->ID, it doesn't show $submitdate.
No error in console.
Would you please let me know how to echo the value of the field?
Query I tried:
$args = array(
'post_type' => 'project',
'posts_per_page' => -1,
'author' => get_current_user_id(),
'name' => get_the_title()
);
$query = new WP_Query($args);
if ($query->have_posts()) {
global $post;
while ($query->have_posts()) {
$query->the_post();
$submitdate = get_post_meta($post->ID, 'submitdate', true);
echo $post->ID;
echo $submitdate;
}
}
I also tried, it shows current date and time, not the value in the field:
$submitdate = get_field("submitdate", $post->ID);
Thank you.
A: /* I had same issue before few days and resolved with below function */
/* please try this line of code */
$args = array(
'post_type' => 'project',
'posts_per_page' => -1,
'author' => get_current_user_id(),
'name' => get_the_title()
);
$query = new WP_Query($args);
if ($query->have_posts()) {
global $post;
while ($query->have_posts()) {
$query->the_post();
$submitdate = get_field('submitdate', $post->ID ); // if changed field name then update key in this query
echo $post->ID;
echo $submitdate;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67931845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How to take data from mongodb atlas and add to table on website? the plan is to create a table on a website (link below) that users can add or remove data (a new row) to.
I have set up a form above the table (with POST) that takes data input into the form and then adds that data to a collection in my mongodDB atlas cloud.
This is fine so far, the problem is I dont know how to code to get that data to go from the db and append to the table (with GET) adding a new row simultaneously.
eg. You add data to form and press submit.
*
*The data you submitted goes to database (set this up)
*At same time, data that was just submitted is taken from database and added to the table on the webpage (permanently until removed).
I can show you the page i created so you can see what Im trying to do.
https://epsl.herokuapp.com/transfer_list
I am using node, mongo, mongoose, express..to set it up.
thanks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67713220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What does module refer to in context of the 4 concepts of Webpack? The 4 concepts of webpack are Entry, Output, Loaders, and Plugins.
I have been looking through the documentation to get an understanding of how my React configuration works.
Entry and Output make sense. But why is loaders included under module.
In terms of the documentation modules are what webpack creates from files.
But in the code ( working ) it holds loaders.
I would have expected it to be a 3rd key.
Where is the documentation for Webpack-React? I did an advance Google Search but nothing relevant came up except a React Proxy Loader,
I am trying to understand this code and need a starting point. Other than the 4 primary concepts. I don't know how it works.
The form below does not even seem to be contained in more in depth documentation under loaders
module.exports = {
entry: `${SRC_DIR}/index.jsx`,
output: {
filename: 'bundle.js',
path: DIST_DIR
},
module: {
loaders: [
{
test: /\.jsx?/,
include: SRC_DIR,
loader: 'babel-loader',
query: {
plugins: ["transform-object-rest-spread", "transform-class-properties"],
presets: ['react', 'es2015']
}
}
]
}
};
A: So one answer to your question is that you're not necessarily looking for documentation for Webpack and React, but Babel (or similar transpiler) and React. Babel-loader (which is the loader you're using above) transpiles React's JSX format into javascript the browser can read via Webpack. Here's the babel-loader documentation.
Here are a few other resources that may help:
1) Setup React.js with Npm, Babel 6 and Webpack in under 1 hour
2) Setup a React Environment Using webpack and Babel
3) React JSX transform
4) And if it is of interest to you: React without JSX
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48064823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to get Names of Background Running Apps I'm making an app in which i need to show the names of apps running in background. I did R&D on it and came to know that we can know only about Apple's apps like Photos , Camera etc. But I couldn't know how. Please help me if you know how to get JUST NAMES OF BACKGROUND RUNNING APPS
For Background running processes I have used following Method
- (NSArray *)runningProcesses {
int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0};
size_t miblen = 4;
size_t size;
int st = sysctl(mib, miblen, NULL, &size, NULL, 0);
struct kinfo_proc * process = NULL;
struct kinfo_proc * newprocess = NULL;
do {
size += size / 10;
newprocess = realloc(process, size);
if (!newprocess){
if (process){
free(process);
}
return nil;
}
process = newprocess;
st = sysctl(mib, miblen, process, &size, NULL, 0);
} while (st == -1 && errno == ENOMEM);
if (st == 0){
if (size % sizeof(struct kinfo_proc) == 0){
int nprocess = size / sizeof(struct kinfo_proc);
if (nprocess){
NSMutableArray * array = [[NSMutableArray alloc] init];
for (int i = nprocess - 1; i >= 0; i--){
NSString * processID = [[NSString alloc] initWithFormat:@"%d", process[i].kp_proc.p_pid];
NSString * processName = [[NSString alloc] initWithFormat:@"%s", process[i].kp_proc.p_comm];
NSDictionary * dict = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects:processID, processName, nil]
forKeys:[NSArray arrayWithObjects:@"ProcessID", @"ProcessName", nil]];
[processID release];
[processName release];
[array addObject:dict];
[dict release];
}
free(process);
return [array autorelease];
}
}
}
return nil;
}
If you think its impossible then kindly have a look to this app http://itunes.apple.com/us/app/sys-activity-manager-for-memory/id447374159?mt=8 . I have also got a solution but its not a proper way (I've mentioned in the last comment below this question).
Thanks.
A: I think in ios it not posible to get which apps are running in background, because in ios the which one is foreground this one the active running apps and other which one you are getting these all are background appps.
so, excluding your application name others are background apps.
A: I don't think it's ment to be possible, but others like you have been very involved in the same topic and come up with some workarounds. Read this blogpost for more info: http://www.amitay.us/blog/files/how_to_detect_installed_ios_apps.php
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9919070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Struggling with gesture dragging I am trying to implement dragging in my Android app. I am following the Android documentation sample listed here. Here is the code:
// The current viewport. This rectangle represents the currently visible
// chart domain and range.
private RectF mCurrentViewport =
new RectF(AXIS_X_MIN, AXIS_Y_MIN, AXIS_X_MAX, AXIS_Y_MAX);
// The current destination rectangle (in pixel coordinates) into which the
// chart data should be drawn.
private Rect mContentRect;
private final GestureDetector.SimpleOnGestureListener mGestureListener
= new GestureDetector.SimpleOnGestureListener() {
...
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
// Scrolling uses math based on the viewport (as opposed to math using pixels).
// Pixel offset is the offset in screen pixels, while viewport offset is the
// offset within the current viewport.
float viewportOffsetX = distanceX * mCurrentViewport.width()
/ mContentRect.width();
float viewportOffsetY = -distanceY * mCurrentViewport.height()
/ mContentRect.height();
...
// Updates the viewport, refreshes the display.
setViewportBottomLeft(
mCurrentViewport.left + viewportOffsetX,
mCurrentViewport.bottom + viewportOffsetY);
...
return true;
}
After the onScroll method executes, how do I update my View? Only the mCurrentViewport variable is updated in the sample.
A: There is quite some code going into using those Android tutorials that is not mentioned there. I suggest using the import sample from menu from Android Studio. This one is possibly what you need to play with:
https://github.com/googlesamples/android-BasicGestureDetect/
I have embedded that Android Tutorial code below in BasicGestureDetectFragment.java if you use the guthyb code above. In "moveLog" method you can do whathever you like with the dx values. I have also put a code under this that shows you how to creat an app dragging a picture. Just add "ic_launcher.png" to image folder under res folder so that you can have an image and move it. I suggest coding with Corona SDK that is a lot simpler than Android.
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.basicgesturedetect;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MotionEventCompat;
import android.view.GestureDetector;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import com.example.android.common.logger.Log;
import com.example.android.common.logger.LogFragment;
import static android.view.MotionEvent.INVALID_POINTER_ID;
public class BasicGestureDetectFragment extends Fragment{
private int mActivePointerId = INVALID_POINTER_ID;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
View gestureView = getActivity().findViewById(R.id.sample_output);
gestureView.setFocusable(true);
// BEGIN_INCLUDE(init_detector)
// First create the GestureListener that will include all our callbacks.
// Then create the GestureDetector, which takes that listener as an argument.
GestureDetector.SimpleOnGestureListener gestureListener = new GestureListener();
final GestureDetector gd = new GestureDetector(getActivity(), gestureListener);
/* For the view where gestures will occur, create an onTouchListener that sends
* all motion events to the gesture detector. When the gesture detector
* actually detects an event, it will use the callbacks you created in the
* SimpleOnGestureListener to alert your application.
*/
gestureView.setOnTouchListener(new View.OnTouchListener() {
float mLastTouchX;
float mLastTouchY;
float mPosX;
float mPosY;
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
gd.onTouchEvent(motionEvent);
//**********
final int action = MotionEventCompat.getActionMasked(motionEvent);
switch (action) {
case MotionEvent.ACTION_DOWN: {
final int pointerIndex = MotionEventCompat.getActionIndex(motionEvent);
final float x = MotionEventCompat.getX(motionEvent, pointerIndex);
final float y = MotionEventCompat.getY(motionEvent, pointerIndex);
// Remember where we started (for dragging)
mLastTouchX = x;
mLastTouchY = y;
// Save the ID of this pointer (for dragging)
mActivePointerId = MotionEventCompat.getPointerId(motionEvent, 0);
break;
}
case MotionEvent.ACTION_MOVE: {
// Find the index of the active pointer and fetch its position
final int pointerIndex =
MotionEventCompat.findPointerIndex(motionEvent, mActivePointerId);
final float x = MotionEventCompat.getX(motionEvent, pointerIndex);
final float y = MotionEventCompat.getY(motionEvent, pointerIndex);
// Calculate the distance moved
final float dx = x - mLastTouchX;
final float dy = y - mLastTouchY;
mPosX += dx;
mPosY += dy;
moveLog(dx);
//invalidate();
// Remember this touch position for the next move event
mLastTouchX = x;
mLastTouchY = y;
break;
}
case MotionEvent.ACTION_UP: {
mActivePointerId = INVALID_POINTER_ID;
break;
}
case MotionEvent.ACTION_CANCEL: {
mActivePointerId = INVALID_POINTER_ID;
break;
}
case MotionEvent.ACTION_POINTER_UP: {
final int pointerIndex = MotionEventCompat.getActionIndex(motionEvent);
final int pointerId = MotionEventCompat.getPointerId(motionEvent, pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mLastTouchX = MotionEventCompat.getX(motionEvent, newPointerIndex);
mLastTouchY = MotionEventCompat.getY(motionEvent, newPointerIndex);
mActivePointerId = MotionEventCompat.getPointerId(motionEvent, newPointerIndex);
}
break;
}
}
//**********
return false;
}
});
// END_INCLUDE(init_detector)
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.sample_action) {
clearLog();
}
return true;
}
public void clearLog() {
LogFragment logFragment = ((LogFragment) getActivity().getSupportFragmentManager()
.findFragmentById(R.id.log_fragment));
logFragment.getLogView().setText("");
}
public void moveLog(float x) {
//do whatever you like
}
}
*
*Image Drag App
Just start a blank app under Android Studio:
1 - Change activity_main.xml to this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/image"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:contentDescription="@string/app_name"
android:src="@drawable/ic_launcher" />
</RelativeLayout>
and MainActivity.java to this.
(Leave the package name as your own: package com.jorc.move.myapplication;)
package com.jorc.move.myapplication;
import android.annotation.SuppressLint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private ViewGroup mainLayout;
private ImageView image;
private int xDelta;
private int yDelta;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainLayout = (RelativeLayout) findViewById(R.id.main);
image = (ImageView) findViewById(R.id.image);
image.setOnTouchListener(onTouchListener());
}
private View.OnTouchListener onTouchListener() {
return new View.OnTouchListener() {
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouch(View view, MotionEvent event) {
final int x = (int) event.getRawX();
final int y = (int) event.getRawY();
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams)
view.getLayoutParams();
xDelta = x - lParams.leftMargin;
yDelta = y - lParams.topMargin;
break;
case MotionEvent.ACTION_UP:
Toast.makeText(MainActivity.this,
"thanks for new location!", Toast.LENGTH_SHORT)
.show();
break;
case MotionEvent.ACTION_MOVE:
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view
.getLayoutParams();
layoutParams.leftMargin = x - xDelta;
layoutParams.topMargin = y - yDelta;
layoutParams.rightMargin = 0;
layoutParams.bottomMargin = 0;
view.setLayoutParams(layoutParams);
break;
}
mainLayout.invalidate();
return true;
}
};
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53968778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Dynamic HREF in XSLT using attribute not working as expected I'm newer to XSLTs and I'm struggling a bit with getting this one to format correctly. I want the output HTML to basically be rows that look like this:
1 : SO090040717 113657 XXX 56371444826
Where "SalesId" is a clickable URL that is formatted (in this example) as basically:
<a href="dynamics://TEST?DrillDown_0?tableid=40276&field=RecId&value=5637144826&company=XXX">SO090040717</a>
The error appears to be somewhere in the <a></a> text?
Sample XML:
<ELEMENT>
<RECORD>
<COUNTER>1</COUNTER>
<DRILLDOWNGROUP>TEST</DRILLDOWNGROUP>
<SalesId>SO090040717</SalesId>
<PurchOrderFormNum>113657</PurchOrderFormNum>
<dataAreaId>XXX</dataAreaId>
<RecId>5637144826</RecId>
<TableId>40276</TableId>
</RECORD>
</ELEMENT>
My, non-working, XSLT:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:template match="/">
<html>
<body>
<xsl:for-each select="ELEMENT">
<p>
<xsl:for-each select="RECORD">
<p>
<xsl:value-of select="COUNTER"/>
<xsl:text> : </xsl:text>
<a>
<xsl:attribute name="href">
<xsl:text>Dynamics://</xsl:text>
<xsl:value-of select="DrillDownGroup"/>
<xsl:text>?DrillDown_0?tableid=</xsl:text>
<xsl:value-of select="TableId"/>
<xsl:text>&field=RecId&value=</xsl:text>
<xsl:value-of select="RecId"/>
<xsl:text>&company=</xsl:text>
<xsl:value-of select="DataAreaId"/>
</xsl:attribute>
<xsl:value-of select="SALESID"/>
</a>
<xsl:text> </xsl:text>
<xsl:value-of select="PurchOrderFormNum"/>
<xsl:text> </xsl:text>
<xsl:value-of select="dataAreaId"/>
<xsl:text> </xsl:text>
<xsl:value-of select="RecId"/>
<br/>
<br/>
</p>
</xsl:for-each>
</p>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
A: A few things:
*
*Case matters so be sure the paths in your select attributes are the same as the source XML.
* The entity nbsp is not declared so use either a hex or decimal reference. You can create an entity declaration for nbsp if you want. In the example, I used the hex reference. Let me know if you want an example of the declaration for nbsp.
*You can't use literal & unless you're in a CDATA section. It's easier to use & instead. I used & in the example. If you want to use CDATA, do something like: <xsl:text><![CDATA[&company=]]></xsl:text>
XSLT 1.0
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:template match="/">
<html>
<body>
<xsl:for-each select="ELEMENT">
<p>
<xsl:for-each select="RECORD">
<p>
<xsl:value-of select="COUNTER"/>
<xsl:text> : </xsl:text>
<a>
<xsl:attribute name="href">
<xsl:text>dynamics://</xsl:text>
<xsl:value-of select="DRILLDOWNGROUP"/>
<xsl:text>?DrillDown_0?tableid=</xsl:text>
<xsl:value-of select="TableId"/>
<xsl:text>&field=RecId&value=</xsl:text>
<xsl:value-of select="RecId"/>
<xsl:text>&company=</xsl:text>
<xsl:value-of select="dataAreaId"/>
</xsl:attribute>
<xsl:value-of select="SalesId"/>
</a>
<xsl:text>   </xsl:text>
<xsl:value-of select="PurchOrderFormNum"/>
<xsl:text>   </xsl:text>
<xsl:value-of select="dataAreaId"/>
<xsl:text>   </xsl:text>
<xsl:value-of select="RecId"/>
<br/>
<br/>
</p>
</xsl:for-each>
</p>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Output
<html>
<body>
<p>
<p>1 : <a href="dynamics://TEST?DrillDown_0?tableid=40276&field=RecId&value=5637144826&company=XXX">SO090040717</a> 113657 XXX 5637144826<br><br></p>
</p>
</body>
</html>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21388430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Initialization of unique_ptr as a class member variable In C++, Is there a difference between using braces when initializing the unique_ptr and not using them in this code?
// MyClass.h
class MyClass()
{
public:
MyClass();
private:
std::unique_ptr<TT> tt{};
}
// MyClass.cpp
MyClass() {
}
Do I even need to initialize the unique_ptr?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62543543",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Import external js script into Angular app I was trying to implement this widget to my Angular app. For the second part I was able to create a custom js file in my assets folder, create a .d.ts file for it and successfully imported the function in my component.
But for the first part:
<script async src="https://telegram.org/js/telegram-widget.js?5" data-telegram-login="samplebot" data-size="large" data-onauth="onTelegramAuth(user)" data-request-access="write"></script>
If I do it with plain HTML and js, it will fetch from the website and generate a login button. Yet I tried simply pasting it into my component's HTML, it does not get rendered. As it is not a function nor a variable, I am not sure how can I place it into a specific div in the component.
Please help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53186015",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Youtube Player fragments inside ViewPager I really need help with this situation. I can't manage to properly create YouTube fragments for each PagerView fragment.
Use case:
~ Let's say I have a PagerView with x fragments, and I want on each of it(in a part of it actually) to be able to play a different video using YouTube API.
This is my YoutubeFragment class which creates an instance of the player
public class YoutubeFragment extends Fragment {
private RelativeLayout layoutAbove;
YouTubePlayer mPlayer;
private static final String TAG = "YoutubeFragment";
private static final String API_KEY = DateUtils.getDeveloperKey();
// YouTube video ID
private static String VIDEO_ID;
private MyPlaybackEventListener myPlaybackEventListener = new MyPlaybackEventListener();
public void setVideoID(String id){
VIDEO_ID = id;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.youtube_layout, container, false);
YouTubePlayerSupportFragment youTubePlayerFragment = YouTubePlayerSupportFragment.newInstance();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.youtube_layout, youTubePlayerFragment).commit();
youTubePlayerFragment.initialize(API_KEY, new OnInitializedListener() {
@Override
public void onInitializationSuccess(Provider provider, final YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
mPlayer = player;
mPlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
mPlayer.setPlaybackEventListener(myPlaybackEventListener);
mPlayer.cueVideo(VIDEO_ID);
}
}
@Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult error) {
// YouTube error
String errorMessage = error.toString();
Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_LONG).show();
Log.d("errorMessage:", errorMessage);
}
});
return rootView;
}
}
And I use this in my adapter for the PagerView, replacing a view
if (images.size() == 0) {
images.addAll(eventData.getVideos());
youtubeFragment = new YoutubeFragment();
if (views.getViewPager(R.id.vp_images) != null)
views.getViewPager(R.id.vp_images).setVisibility(View.GONE);
youtubeFragment.setVideoID(eventData.getYoutube_id());
android.support.v4.app.FragmentManager fragmentManager = ((FragmentActivity) context).getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(views.getFrameLayoutid(R.id.youtube_layout), youtubeFragment)
//.addToBackStack(null) // added to backstack of supportFragmentManager
.commit();
}
I have to mention that I create the PagerView based on a list with items. I manage to create an instance of the video fragment, but only on the clicked item, but even like this, the video is not being played more than 1 sec. I was careful with padding & other views that might be over the player.
Also, on the next page (that is loaded by the PagerView) I can't event see the YouTube fragment.
Here is the XML file of PagerView fragment(at least the important snippet of it)
<RelativeLayout
android:id="@+id/relativeProblematicLayout"
android:contentDescription="@string/contentDescription"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:id="@+id/youtube_layout"
android:layout_width="match_parent"
android:layout_height="@dimen/event_image_height"
android:visibility="visible" />
</LinearLayout>
<android.support.v4.view.ViewPager
android:id="@+id/vp_images"
android:layout_width="match_parent"
android:layout_height="@dimen/event_image_height"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
</android.support.v4.view.ViewPager>
<RelativeLayout
android:visibility="gone"
android:id="@+id/viewPagerIndicator"
android:layout_width="match_parent"
android:layout_height="20dp"
android:layout_marginTop="@dimen/standard_1_dp"
android:layout_marginBottom="@dimen/standard_10_dp"
android:layout_alignParentBottom="true"
android:gravity="center">
<LinearLayout
android:id="@+id/viewPagerCountDots"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:gravity="center"
android:orientation="horizontal" />
</RelativeLayout>
</RelativeLayout>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46542349",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Jump to function definition How can I jump to a function definition using Vim? For example with Visual Assist, I can type Alt+g under a function and it opens a context menu listing the files with definitions.
How can I do something like this in vim?
A: To second Paul's response: yes, ctags (especially exuberant-ctags (http://ctags.sourceforge.net/)) is great. I have also added this to my vimrc, so I can use one tags file for an entire project:
set tags=tags;/
A: Use gd or gD while placing the cursor on any variable in your program.
*
*gd will take you to the local declaration.
*gD will take you to the global declaration.
more navigation options can be found in here.
Use cscope for cross referencing large project such as the linux kernel.
A: TL;DR:
You can do this using internal VIM functionality but a modern (and much easier) way is to use COC for intellisense-like completion and one or more language servers (LS) for jump-to-definition (and way way more). For even more functionality (but it's not needed for jump-to-definition) you can install one or more debuggers and get a full blown IDE experience.
Best second is to use native VIM's functionality called define-search but it was invented for C preprocessor's #define directive and for most other languages requires extra configuration, for some isn't possible at all (also you miss on other IDE features). Finally, a fallback to that is ctags.
Quick-start:
*
*install vim-plug to manage your VIM plug-ins
*add COC and (optionally) Vimspector at the top of ~/.vimrc:
call plug#begin()
Plug 'neoclide/coc.nvim', {'branch': 'release'}
Plug 'puremourning/vimspector'
call plug#end()
" key mappings example
nmap <silent> gd <Plug>(coc-definition)
nmap <silent> gD <Plug>(coc-implementation)
nmap <silent> gr <Plug>(coc-references)
" there's way more, see `:help coc-key-mappings@en'
*call :source $MYVIMRC | PlugInstall to reload VIM config and download plug-ins
*restart vim and call :CocInstall coc-marketplace to get easy access to COC extensions
*call :CocList marketplace and search for language servers, e.g.:
*
*type python to find coc-jedi,
*type php to find coc-phpls, etc.
*(optionally) see :h VimspectorInstall to install additional debuggers, e.g.:
*
*:VimspectorInstall debugpy,
*:VimspectorInstall vscode-php-debug, etc.
Full story:
Language server (LS) is a separate standalone application (one for each programming language) that runs in the background and analyses your whole project in real time exposing extra capabilities to your editor (any editor, not only vim). You get things like:
*
*namespace aware tag completion
*jump to definition
*jump to next / previous error
*find all references to an object
*find all interface implementations
*rename across a whole project
*documentation on hover
*snippets, code actions, formatting, linting and more...
Communication with language servers takes place via Language Server Protocol (LSP). Both nvim and vim8 (or higher) support LSP through plug-ins, the most popular being Conquer of Completion (COC).
List of actively developed language servers and their capabilities is available on Lang Server website. Not all of those are provided by COC extensions. If you want to use one of those you can either write a COC extension yourself or install LS manually and use the combo of following VIM plug-ins as alternative to COC:
*
*LanguageClient - handles LSP
*deoplete - triggers completion as you type
Communication with debuggers takes place via Debug Adapter Protocol (DAP). The most popular DAP plug-in for VIM is Vimspector.
Language Server Protocol (LSP) was created by Microsoft for Visual Studio Code and released as an open source project with a permissive MIT license (standardized by collaboration with Red Hat and Codenvy). Later on Microsoft released Debug Adapter Protocol (DAP) as well. Any language supported by VSCode is supported in VIM.
I personally recommend using COC + language servers provided by COC extensions + ALE for extra linting (but with LSP support disabled to avoid conflicts with COC) + Vimspector + debuggers provided by Vimspector (called "gadgets") + following VIM plug-ins:
call plug#begin()
Plug 'neoclide/coc.nvim'
Plug 'dense-analysis/ale'
Plug 'puremourning/vimspector'
Plug 'scrooloose/nerdtree'
Plug 'scrooloose/nerdcommenter'
Plug 'sheerun/vim-polyglot'
Plug 'yggdroot/indentline'
Plug 'tpope/vim-surround'
Plug 'kana/vim-textobj-user'
\| Plug 'glts/vim-textobj-comment'
Plug 'janko/vim-test'
Plug 'vim-scripts/vcscommand.vim'
Plug 'mhinz/vim-signify'
call plug#end()
You can google each to see what they do.
Native VIM jump to definition:
If you really don't want to use Language Server and still want a somewhat decent jump to definition with native VIM you should get familiar with :ij and :dj which stand for include-jump and definition-jump. These VIM commands let you jump to any file that's included by your project or jump to any defined symbol that's in any of the included files. For that to work, however, VIM has to know how lines that include files or define symbols look like in any given language. You can set it up per language in ~/.vim/ftplugin/$file_type.vim with set include=$regex and set define=$regex patterns as described in :h include-search, although, coming up with those patterns is a bit of an art and sometimes not possible at all, e.g. for languages where symbol definition or file import can span over multiple lines (e.g. Golang). If that's your case the usual fallback is ctags as described in other answers.
A: Use ctags. Generate a tags file, and tell vim where it is using the :tags command. Then you can just jump to the function definition using Ctrl-]
There are more tags tricks and tips in this question.
A: If everything is contained in one file, there's the command gd (as in 'goto definition'), which will take you to the first occurrence in the file of the word under the cursor, which is often the definition.
A: As Paul Tomblin mentioned you have to use ctags.
You could also consider using plugins to select appropriate one or to preview the definition of the function under cursor.
Without plugins you will have a headache trying to select one of the hundreds overloaded 'doAction' methods as built in ctags support doesn't take in account the context - just a name.
Also you can use cscope and its 'find global symbol' function. But your vim have to be compiled with +cscope support which isn't default one option of build.
If you know that the function is defined in the current file, you can use 'gD' keystrokes in a normal mode to jump to definition of the symbol under cursor.
Here is the most downloaded plugin for navigation
http://www.vim.org/scripts/script.php?script_id=273
Here is one I've written to select context while jump to tag
http://www.vim.org/scripts/script.php?script_id=2507
A: Another common technique is to place the function name in the first column. This allows the definition to be found with a simple search.
int
main(int argc, char *argv[])
{
...
}
The above function could then be found with /^main inside the file or with :grep -r '^main' *.c in a directory. As long as code is properly indented the only time the identifier will occur at the beginning of a line is at the function definition.
Of course, if you aren't using ctags from this point on you should be ashamed of yourself! However, I find this coding standard a helpful addition as well.
A: 1- install exuberant ctags. If you're using osx, this article shows a little trick:
http://www.runtime-era.com/2012/05/exuberant-ctags-in-osx-107.html
2- If you only wish to include the ctags for the files in your directory only, run this command in your directory:
ctags -R
This will create a "tags" file for you.
3- If you're using Ruby and wish to include the ctags for your gems (this has been really helpful for me with RubyMotion and local gems that I have developed), do the following:
ctags --exclude=.git --exclude='*.log' -R * `bundle show --paths`
credit: https://coderwall.com/p/lv1qww
(Note that I omitted the -e option which generates tags for emacs instead of vim)
4- Add the following line to your ~/.vimrc
set autochdir
set tags+=./tags;
(Why the semi colon: http://vim.wikia.com/wiki/Single_tags_file_for_a_source_tree )
5- Go to the word you'd like to follow and hit ctrl + ] ; if you'd like to go back, use ctrl+o (source: https://stackoverflow.com/a/53929/226255)
A: g* does a decent job without ctags being set up.
That is, type g,* (or just * - see below) to search for the word under the cursor (in this case, the function name). Then press n to go to the next (or Shift-n for previous) occurrence.
It doesn't jump directly to the definition, given that this command just searches for the word under the cursor, but if you don't want to deal with setting up ctags at the moment, you can at least save yourself from having to re-type the function name to search for its definition.
--Edit--
Although I've been using g* for a long time, I've recently discovered two shortcuts for these shortcuts!
(a) * will jump to the next occurrence of the word under the cursor. (No need to type the g, the 'goto' command in vi).
(b) # goes to the previous occurrence, in similar fashion.
N and n still work, but '#' is often very useful to start the search initially in the reverse direction, for example, when looking for the declaration of a variable under the cursor.
A: Install cscope. It works very much like ctags but more powerful. To go to definition, instead of Ctrl + ], do Ctrl + \ + g. Of course you may use both concurrently. But with a big project (say Linux kernel), cscope is miles ahead.
A: After generating ctags, you can also use the following in vim:
:tag <f_name>
Above will take you to function definition.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/635770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "308"
}
|
Q: .htaccess redirect url with controller name for MVC application i am trying to build a mvc like application and i cant figure out the right .htaccess i need.
I want something like:
RewriteRule ^(.*)/(.*)/(.*)$ $1.php?action=$2&n=$3 [L]
so i can access the file that contains the proper controller and two get variables from the url. The code above doesnt work, i have been around this for 2 days now and i cant find anything like what i need anywhere.What happens there is that the 3 variables are required at the url in order to work, and thats not what i want. Sugestions?
A: Most frameworks use a Front-Controller instead of mod_rewrite. This controller splits apart the URL and routes accordingly.
While not the only solution, this is more flexible. Consider when you have the URL plugin/controller/view/id or controller/view/param1/param2.
If you want to adopt the Front-Controller architecture, I'd recommend using FallbackResource to keep your htaccess file trim.
FallbackResource /front-controller.php
From there it should be fairly straightforward to split apart the url with functions like parse_url().
A: use this:
RewriteRule ^([^\./]*)$ index.php?route=$1 [L,NC,QSA]
then
$route = explode('/', $_GET['route']);
$id = array_pop();
$controller = array_shift($route);
$method = implode('_', $route);
$controller = new $controller;
$controller->$method();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11532235",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: springMVC+mybatis+mysql can't insert blob I use the mybatis and springMVC,and the database is the MySql,I know the configuration of the SpringMVC and mybatis are right ,but when I want to write a demo of the blob ,it does't work,this is the code.
FileMapper.java
public interface FileMapper {
//插入文件
int insert(ContractFile file);
//读取文件
ContractFile selectByFileName(String fileName);
}
FileMapper.xml
<insert id="insert" parameterType="com.beebank.test.model.ContractFile">
insert into t_base_file
(fileId, fileName, fileContent)
values
(#{fileId,jdbcType=INTEGER},
#{fileName,jdbcType=VARCHAR},
#{fileContent,jdbcType=BLOB})
</insert>
ContractFile.java
public class ContractFile {
private Integer fileId;
private String fileName;
private byte[] fileContent;
// getter() and setter()...
}
TestFile.java(the main code)
String fileName = input.nextLine();
File file = new File(fileUrl + fileName);
FileInputStream fis = new FileInputStream(file);
byte[] fileContent = new byte[(int)file.length()];
fis.read(fileContent);
ContractFile contractFile=new ContractFile();
contractFile.setFileId(1);
contractFile.setFileName(fileName);
contractFile.setFileContent(fileContent);
mapper.insert(contractFile);
fis.close();
This is my first time to ask and my English is not good, so Hope we learn from each other。
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37114269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Checking for missing values in CSV I have a CSV file that counts the data in a timestamp every 15 min.
I need tried to figure out how to see, if there is missing any of the 15 min in the file. But i cant get the code to work 100%.
hope you can help!
First i geathered the data from csv and set it in timestamp. The format is yyyy-mm-dd-hh:mm.
lst = list()
with open("CHFJPY15.csv", "r") as f:
f_r = f.read()
sline = f_r.split()
for line in sline:
parts = line.split(',')
date = parts[0]
time = parts[1]
closeingtime = parts[5]
timestamp = date + ' ' + time + ' ' + closeingtime
lst.append(timestamp)
print(lst, "liste")
(All credits to BillBell for the code below)
Here try creating a consistently formatted list of data items.
from datetime import timedelta
interval = timedelta(minutes=15)
from datetime import datetime
current_time = datetime(2015,12,9,19,30)
data = []
omits = [3,5,9,11,17]
for i in range(20):
current_time += interval
if i in omits:
continue
data.append(current_time.strftime('%y.%m.%d.%H:%M')+' 123.456')
Now I read through the dates subtracting each from it predecessor. I set the first 'predecessor', which I call previous to now because that's bound to differ from the other dates.
I split each datum from the list into two, ignoring the second piece. Using strptime I turn strings into dates. Dates can be subtracted and the differences compared.
previous = datetime.now().strftime('%y.%m.%d.%H:%M')
first = True
for d in data:
date_part, other = d.split(' ')
if datetime.strptime(date_part, '%y.%m.%d.%H:%M') - datetime.strptime(previous, '%y.%m.%d.%H:%M') != interval:
if not first:
'unacceptable gap prior to ', date_part
else:
first = False
previous = date_part
Hope you can see the problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45661376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: shader storage block length returns zero or less I am getting zero or less when I try to get the length of an indeterminate-length array in a shader storage block.
Setting up the storage:
geometryBuffer = ByteBuffer.allocateDirect(12* 4)
.order(ByteOrder.nativeOrder());
geometryBuffer.putFloat(1f);
geometryBuffer.putFloat(0.25f);
geometryBuffer.putFloat(0.5f);
geometryBuffer.putFloat(0.75f);
geometryBuffer.putFloat(1.1f);
geometryBuffer.putFloat(0.35f);
geometryBuffer.putFloat(0.6f);
geometryBuffer.putFloat(0.85f);
geometryBuffer.putFloat(1.2f);
geometryBuffer.putFloat(0.45f);
geometryBuffer.putFloat(0.7f);
geometryBuffer.putFloat(0.95f);
geometryBuffer.flip();
geometryBufferId = GL15.glGenBuffers();
GL15.glBindBuffer(GL43.GL_SHADER_STORAGE_BUFFER, geometryBufferId);
System.out.println("bb" + GL11.glGetError());
GL15.glBufferData(GL43.GL_SHADER_STORAGE_BUFFER, geometryBuffer, GL15.GL_STATIC_DRAW);
System.out.println("bd" + GL11.glGetError());
GL30.glBindBufferRange(GL43.GL_SHADER_STORAGE_BUFFER, 0, geometryBufferId, 0, 36);
System.out.println("br" + GL11.glGetError());
GL15.glBindBuffer(GL43.GL_SHADER_STORAGE_BUFFER, 0);
The frag shader:
#version 430
out vec4 outColour;
layout(std430, binding=0) buffer Geometry {
vec4 a;
vec4 myVec[];
} ;
void main() {
// if (myVec[0].y == 0.35) {
if (myVec.length() == -1) {
outColour = vec4 (1,0,0,1);
} else {
outColour = vec4(0,0,1,1);
}
}
I expect length to be 2 but the length returned in this example is -1. I can retrieve the values in the array as the test if (myVec[0].y == 0.35) also returns red.
According to https://www.opengl.org/wiki/Interface_Block_(GLSL) and the GLSL spec v4.5 section 4.1.9, the size is calculated at runtime from the size of the buffer or range, minus all the sized components in the block and then divided by the size of an individual array entry. What I seem to be getting is zero minus the number of vec4 units before the indeterminate storage in the block.
An alternative would be to pass a uniform with the array size, but why doesn't length() return the correct value? I'm running on a GTX660M
A: I cant claim the credit for this as it was provided by someone on a GL forum, but to close this question out, the answer is that referencing myVec.length() is not enough, you have to actually reference the array so this works :
if (myVec.length() == 2 && myVec[0].y == 0.35) {
...
Without actually referencing an array entry in the shader, the compiler presumably optimizes it out, thus returning a length of zero at runtime.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38681103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: __attribute__((OS_main)) results in strange behaviour in AVR I don't know how to precisely described the error I am seeing. If I set up my port register in main() everything works as intended. However if I try to do it in a function, the program halts.
main.c:
__attribute__((OS_main)) int main(void);
int main(void) {
DDRD = 0xF0;
PORTD = 0xF0;
led( LED_GREEN, true );
while( true );
}
This turns on the green LED. However if I move the port setup to a seperate function nothing happens, like so:
__attribute__((OS_main)) int main(void);
int main(void) {
hwInit();
led( LED_GREEN, true );
while( true );
}
The culprit seems to be the attribute line because if I comment it out the second example works as expected. My problem is understanding why, since as I understand it the OS_main attribute should only tell the compiler that it should not store any registers upon entry or exit to the function. Is this not correct?
A: The following was compiled with avr-gcc 4.8.0 under ArchLinux. The distribution should be irrelevant to the situation, compiler and compiler version however, may produce different outputs. The code:
#include <avr/io.h>
#define LED_GREEN PD7
#define led(p, s) { if(s) PORTD |= _BV(p); \
else PORTD &= _BV(p); }
__attribute__((OS_main)) int main(void);
__attribute__((noinline)) void hwInit(void);
void hwInit(void){
DDRD = 0xF0;
}
int main(void){
hwInit();
led(LED_GREEN, 1);
while(1);
}
Generates:
000000a4 <hwInit>:
a4: 80 ef ldi r24, 0xF0 ; 240
a6: 8a b9 out 0x0a, r24 ; 10
a8: 08 95 ret
000000aa <main>:
aa: 0e 94 52 00 call 0xa4 ; 0xa4 <hwInit>
ae: 5f 9a sbi 0x0b, 7 ; 11
b0: ff cf rjmp .-2 ; 0xb0 <main+0x6>
when compiled with
avr-gcc -Wall -Os -fpack-struct -fshort-enums -std=gnu99 -funsigned-char -funsigned-bitfields -mmcu=atmega168 -DF_CPU=1000000UL -MMD -MP -MF"core.d" -MT"core.d" -c -o "core.o" "../core.c" and linked accordingly.
Commenting __attribute__((OS_main)) int main(void); from the above sources has no effect on the generated assembly. Curiously, however, removing the noinline directive from hwInit() has the effect of the compiler inlining the function into main, as expected, but the function itself still exists as part of the final binary, even when compiled with -Os.
This leads me to believe that your compiler version/arguments to the compiler are generating some assembly which is not correct. If possible, can you post the disassembly for the relevant areas for further examination?
Edited late to add two contributions, second of which resolves the problem at hand:
Hanno Binder states: "In order to remove those 'unused' functions from the binary you would also need -ffunction-sections -Wl,--gc-sections."
Asker adds [paraphrased]: "I followed a tutorial which neglected to mention the avr-objcopy step to create the hex file. I assumed that compiling and linking the project for the correct target was sufficient (which it for some reason was for basic functionality). After having added an avr-objcopy step to generate the file everything works."
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16103979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Performance: list all keys from hdf5 file with pandas Is it normal that that it takes so long to obtain all present keys in a hdf5 file?
Code Sample:
start = time.time()
store = pd.HDFStore(filepath)
print(time.time() - start)
0.0
start = time.time()
a = store.keys()
print(time.time() - start)
23.874846696853638
len(a)
80
start = time.time()
store.select(key="/data/table1") # the next table would be /data/table2
print(time.time() - start)
0.062399864196777344
All keys are 'tables' (i.e. not fixed).
There are about 80 keys present in the file.
The entire size of the .h5 file is 348 MB. Each table has approx. the same size (after loading to a pandas.DataFrame) of 2.6 MB.
pandas v.0.20.1
tables v.3.2.2.
I am wondering if the key hierarchy is an issue: all in data/table[X] instead of directly into table[X]?
A: I have the same issue. It appears the cause is related to the way tables checks every single node value to create a list of keys. I've raised this to pandas dev.
If you want to check whether a key is in the store then
store.__contains__(key)
will do the job and is much faster.
https://github.com/pandas-dev/pandas/issues/17593
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44737892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Iterating Properties I've been doing some research on iterating properties, and have come up with a basic solution that seems to work, but doesn't quite do what I'm looking for. I'm calling a WebService method which returns an PeopleSoft object with a large amount of properties. Each one of these properties returns some obscure type of object that would take too much time to typecast individually. My code works and it iterates the properties, but it doesn't display the values. Here is the auto generated code visual studio makes for one of the properties.
public SETIDTypeShape5 SETID {
get {
return this.sETIDField;
}
set {
this.sETIDField = value;
}
}
I'm guessing that the SETIDTypeShape5 doesn't have a proper ToString() method, because when it gets printed, all it shows is SETIDTypeShape5. I know it has a Value property associated with it, but is there any way to access that value? This is the code I have so far, and what some of the output looks like.
Type getType = idResponseTypeShape.GetType();
foreach (PropertyInfo info in getType.GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
String name = info.Name;
object value = info.GetValue(idResponseTypeShape, null);
Debug.WriteLine("{0} = {1}", name, value);
}
SETID = VendorMod.edu.clcillinois.fs3.SETIDTypeShape5
VENDOR_ID = VendorMod.edu.clcillinois.fs3.VENDOR_IDTypeShape5
VENDOR_NAME_SHORT = VendorMod.edu.clcillinois.fs3.VENDOR_NAME_SHORTTypeShape3
VNDR_NAME_SHRT_USR = VendorMod.edu.clcillinois.fs3.VNDR_NAME_SHRT_USRTypeShape1
VNDR_NAME_SEQ_NUM = VendorMod.edu.clcillinois.fs3.VNDR_NAME_SEQ_NUMTypeShape1
NAME1 = VendorMod.edu.clcillinois.fs3.NAME1TypeShape3
NAME2 = VendorMod.edu.clcillinois.fs3.NAME2TypeShape1
VENDOR_STATUS = VendorMod.edu.clcillinois.fs3.VENDOR_STATUSTypeShape1
I'm not sure if I'm explaining it thoroughly, but I'm basically looking for a way to get the Value of each one of those TypeShapes, without manually casting each one to the correct object explicitly. Is this even possible?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12391405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to set a specific function to every widget while using loops in tkinter from Python 3? I'm exploring tkinter from Python 3 and I have a problem with using loops to create widgets containing functions. I have this code:
from tkinter import *
def test(no, button_name, event=None):
def callback():
print(button_name)
return callback
root = Tk()
list_of_buttons = 'Button 1, Button 2, Button 3, Button 4, Button 5'.split(', ')
for no, i in enumerate(list_of_buttons):
list_of_buttons[no] = Button(root, text=i, command=test(no=no, button_name=i))
list_of_buttons[no].grid(row=no, column=0)
root.mainloop()
This code Works good, and the result is when you press each button, it prints its's own name. But, I think buttons are ugly, even with ttk, so I am planning to make some customized screen, with labels and images instead of buttons. Then I tried to change the Button widget to a Label, in this way:
list_of_buttons[no] = Label(root, text=i)
list_of_buttons[no].bind('<Button-1>', test(no=no, button_name=i))
Then an error appears:
TypeError: callback() takes 0 positional arguments but 1 was given
I tired to fixed using lambda but when i use it, when I press the label it just doesn't work:
list_of_buttons[no].bind('<Button-1>', lambda event: test(no=no, button_name=i))
I also tried calling the callback function like this:
return callback()
But this only print 'Button 5'. Is there any way to do the same with the labels that needs event bindings?
A: Modify your callback def to:
def callback(event=None):
print(button_name)
This is because the callback that tkinter calls is actually the callback function, not the test function. Test function does not need event=None.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47115243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Laravel eloquent is very slow when joining two models There is a model Invoice which equals to a purchase basket and model InvoiceItem which stores items inside a specific invoice. The model invoice has status field, if its value is 2999 and someone has verified it, it is successful. I need to get invoice items which are sold. Here is codes:
class Invoice extends Model
{
protected $fillable = [];
protected $table = 'payment_invoices';
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
public function scopeSuccessful($query)
{
return $query->where('status', 2999)->where('verified_at', '<>', null);
}
}
and
class InvoiceItem extends Model
{
protected $fillable = [];
protected $table = 'payment_invoice_items';
public function invoice()
{
return $this->belongsTo(Invoice::class, 'invoice_id');
}
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
public function vendor()
{
return $this->belongsTo(Vendor::class, 'vendor_id');
}
public function scopeNotDeleted($query)
{
return $query->where('deleted_at', null);
}
public function scopeSold($query)
{
return $query->notDeleted()->whereHas('invoice', function ($q) {
$q->successful();
});
}
}
The following statement
InvoiceItem::sold()->take(10)->get()
returns 10 sold items but it is very slow. it takes about 4 seconds to retrieve the information while the query
select *
from laravel.payment_invoice_items pii
join laravel.payment_invoices pi
on pi.id = pii.invoice_id
and pii.deleted_at isnull
and pi.status=2999
and pi.verified_at notnull
limit 10
takes about 800 milliseconds. Eloquent is very inefficient. Is there any solution to use the eloquent and get the same efficiency here?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65069447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to remove StartMenu shortcut using C# How can I remove a shortcut folder from Startmenu in Windows using C#, I know how to do that using this code:
private void RemoveShortCutFolder(string folder)
{
folder = folder.Replace("\" ", "");
folder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu), folder);
try
{
if (System.IO.Directory.Exists(folder))
{
System.IO.Directory.Delete(folder, true);
}
else
{
}
}
catch (Exception)
{
}
}
But the problem that I need to remove one shortcut folder in ALL USERS folder, not the current logged user. Environment.SpecialFolder.StartMenu gives me the current user not all users folder.
Any idea,
Thanks,
A: If you don't mind a little Win32, you can use SHGetSpecialFolderPath.
[DllImport("shell32.dll")]
static extern bool SHGetSpecialFolderPath(IntPtr hwndOwner, StringBuilder lpszPath, CSIDL nFolder, bool fCreate);
enum CSIDL
{
COMMON_STARTMENU = 0x0016,
COMMON_PROGRAMS = 0x0017
}
static void Main(string[] args)
{
StringBuilder allUsersStartMenu = new StringBuilder(255);
SHGetSpecialFolderPath(IntPtr.Zero, allUsersStartMenu, CSIDL.COMMON_PROGRAMS, false);
Console.WriteLine("All Users' Start Menu is in {0}", allUsersStartMenu.ToString());
}
A: Use Environment.SpecialFolder.CommonStartMenu instead of StartMenu.
A: Thanks guys, I found the answer:
private void RemoveShortCutFolder(string folder)
{
folder = folder.Replace("\" ", "");
folder = Path.Combine(Path.Combine(Path.Combine(Environment.GetEnvironmentVariable("ALLUSERSPROFILE"), "Start Menu"), "Programs"), folder);
try
{
if (System.IO.Directory.Exists(folder))
{
System.IO.Directory.Delete(folder, true);
}
else
{
}
}
catch (Exception)
{
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/650746",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Qt Reources - Add and Read JSON file I need a JSON file to save some info about my app and read it sometimes. And because my app runs in Ubuntu and Windows, I added it to Qt Resources...
To access the JSON file I tried:
QFile file(":/files/files/my_settings.json");
qDebug() << "settings file: " << endl << file.readAll();
A: First you need to call QFile::open() before calling readAll().
Second point, you can not write to file in Qt Resources.
If you want a cross platform way to save settings and such for your software take a look at QStandardPaths::writableLocation() and QSettings.
Note that QSettings won't handle JSON out of the box, but it will handle all the read/write to file for you (and the file format and location for you if you took car of setting QCoreApplication::applicationName and QCoreApplication::organizationName).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41502389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Defining self-referential structs in a C header file (.h)? I'm trying to create a struct used in two .c source files to make a simple linked list structure. I thought it would save time to create a struct in the header file, however, I get a 'parse error before *' error.
This is the code I'm using:
/*
* Structures.h
*
* Created on: Dec 17, 2011
* Author: timgreene
*/
#ifndef STRUCTURES_H_
#define STRUCTURES_H_
typedef struct list_struct {
int data;
struct list_struct* next;
struct list_struct* prev;
} list;
#endif /* STRUCTURES_H_ */
Edit: I did originally omit a detail that is, I'm actually compiling with xcc from the XMOS toolchain. I still don't understand that there would be a difference in .h file syntax.
Could it be a compilation flag I'm using?
Here's the console printout:
xcc -O0 -g -Wall -c -MMD -MP -MF"filter.d" -MT"filter.d filter.o " -target=XC-1A -o filter.o "../filter.xc"
In file included from ../filter.xc:15:
Structures.h:13: error: parse error before '*' token
Structures.h:14: error: parse error before '*' token
Structures.h:15: error: parse error before '}' token
A: Looking around in some of the XMOS documentation, it seems the problem is that XC is not C, it's just a C-like language. From the "XC Programming Guide":
XC provides many of the same capabilities as C, the main omission being support
for pointers.
...which explains why it doesn't accept the next and prev pointers in your structure.
Apparently xcc lets you mix C and XC sources, though, so if you were to limit your use of the structure to C code it should work. From the "XCC Command-Line Manual", it appears that anything with a .xc extension (as in the command line you used above) is treated as XC, rather than C, source code by default. This can be overridden by placing the option -xc before the C sources on the command line and -x afterward (or just rename the files with a .c extension).
If you must use XC rather than C, you may need to find another way of doing things (arrays, maybe?).
A: Try using a forward declaration of struct list_struct:
struct list_struct;
typedef struct list_struct {
int data;
struct list_struct* next;
struct list_struct* prev;
} list;
Perhaps your compiler doesn't recognize the identifier in the middle of its own definition, I'm not sure what the standards say about that (if anything).
For those that don't already know, this is also the way to deal with circular dependencies in struct definitions:
struct a;
struct b;
struct a {
int x;
struct b *y;
};
struct b {
int x;
struct a *y;
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8549077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: What is the DataGrid MappingName for a non DataTable DataSource? I am able to Bind my DataGrid in .NET 3.5 CF to a List() but I am unable to format the columns by specifying their width. Below is the code that looks like it should work but does not. I am pretty sure that I am not setting the MappingName correctly as all tutorials tell you to set it to the name of your DataTable but I am not binding to a DataTable so I am not quiet sure what to do.
grdBatch.DataSource = InventoryItems;
DataGridTableStyle tableStyle = new DataGridTableStyle();
tableStyle.MappingName = InventoryItems.ToString();
DataGridTextBoxColumn tbcName = new DataGridTextBoxColumn();
tbcName.Width = 400;
tbcName.MappingName = "SERIAL_ID";
tbcName.HeaderText = "SERIAL_ID";
tableStyle.GridColumnStyles.Add(tbcName);
grdBatch.TableStyles.Clear();
grdBatch.TableStyles.Add(tableStyle);
grdBatch is a DataGrid and InventoryItems is a List of POCOS(Plain old C# Objects).
A: Change:
tableStyle.MappingName = InventoryItems.ToString();
to
tableStyle.MappingName = InventoryItems.GetType().Name;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/859464",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: debugging a rails controller making too many queries I have a rails application that about 3 years old, and I'm having a problem with my pages making too many queries. Every page that loads has several lines that look like this:
ReqTdsLink Columns (1.0ms) SHOW FIELDS FROM `req_tds_links`
what sort of method call would cause this output in the log? I can't find any before filters, or anything else in the application controller that could be causing this, but I have yet to check all the views (which are astronomical in number) I'd like to have something specific to look for before i start manually scanning each file for something that might cause this.
thanks,
-C
A: Are you running in development or production mode?
SHOW FIELDS FROM foo is done by your model, as you noted, so it knows which accessor methods to generate.
In development mode, this is done every request so you don't need to reload your webserver so often, but in production mode this information should be cached, even if you're running a three year old version of Rails.
A: This is called by ActiveRecord reading the attributes of a model from your database. It won't happen multiple times in production, but in development mode, Rails queries the table each time to pick up on any changes that may have occurred.
A: If you have this kind of problem again and need to track down how a query is being called I would suggest the Query Trace plugin: http://github.com/ntalbott/query_trace/tree/master. It adds a stack trace to the log for every SQL query. Very handy.
A: This line actually comes from calling the model, i had an array in the application controller that looked like [Model1, Model2, Model3] and I changed it to look like ['Model1','Model2', 'Model3'] and that fixed all the extra calls.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/808553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: PHP file read not working On a server I have the file some.php. I try to read the contents using file_get_content and fread. Both these don't read my content.
If I try some other URL like yahoo.com, these functions are reading the contents. Why does this happen?
$my_conetn = file_get_contents("http://example.com");
echo $my_conetn;
The above snippet is not working.
$handle = fopen($filename, "r");
$contents = fread($handle, 20);
echo $contents;
fclose($handle);
Also the above snippet is not working.
How to check my server? Is there any file read operation locked or not?
edit: I am not sure, but it is only my server file that can't be read. I can read the other server links. So I contact my hosting provider, then I get back to you guys/gals.
A: When using file functions to access remote files (paths starting with http:// and similar protocols) it only works if the php.ini setting allow_url_fopen is enabled.
Additionally, you have no influence on the request sent. Using CURL is suggested when dealing with remote files.
If it's a local file, ensure that you have access to the file - you can check that with is_readable($filename) - and that it's within your open_basedir restriction if one is set (usually to your document root in shared hosting environments).
Additionally, enable errors when debugging problems:
ini_set('display_errors', 'on');
error_reporting(E_ALL);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2848185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to rewrite CSS Grid declaration w/ grid areas for IE11 I have a handy Container component that defines a grid that wraps all children within the middle column, which serves as a max-width container. This component has the option of specifying the child item to break that max-width container and start at the first column and end at the last column.
See this blog post for further explanation: https://cloudfour.com/thinks/breaking-out-with-css-grid-layout/
See this Codepen for example:
https://codepen.io/tylersticka/full/wdmymG/
I was confident that'd the old IE 10 and IE 11 spec would have properties to cover the newer spec's properties but I haven't had any luck with in when testing in IE 11. What syntax am I missing or do I need to modify to replicate grid-areas in IE 11?
.grid-container {
display: -ms-grid;
display: grid;
-ms-grid-columns: [full-start] minmax(0, 1fr) [main-start] minmax(0, 1120px) [main-end] minmax(0, 1fr)
[full-end];
grid-template-columns:
[full-start] minmax(0, 1fr) [main-start] minmax(0, 1120px) [main-end] minmax(0, 1fr) [full-end];
> * {
grid-column: main;
padding: 0 16px;
}
}
.full-width {
grid-column: full;
}
Sources:
https://css-tricks.com/css-grid-in-ie-debunking-common-ie-grid-misconceptions/
https://css-tricks.com/css-grid-in-ie-css-grid-and-the-new-autoprefixer/
https://autoprefixer.github.io/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52504649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: React Router v4 Group of Router I want to create a Route Group to validate each route with the first Component. But it may not be possible. Because React read just the first group, I also tried it with React.Fragment, but the same thing happens
I created a Group of Routes:
import React from 'react';
import {Route} from 'react-router-dom';
import _ from 'lodash';
export const PathGroup = (pathGroup, sadas) => {
const Template = pathGroup.template;
return (
{ _.map(pathGroup.children, (pathRoute, key) => {
const { component, path, exact, ...another } = pathRoute.props;
return (
<Route
exact
path={path}
key={key}
render={ (route) => <Template
component={component}
route={route}
{...another}
/>}
/>
)
}) }
);
};
export const Path = (path) => {
return <React.Fragment/>
};
To print the routes by group in this way:
render() {
const user = this.props.user;
if (!user.verified) { return(<div>Loading...</div>); }
return (
<BrowserRouter>
<Switch>
<PathGroup template={PublicLayout} >
<Path exact path='/contact' component={Contact} user={user}/>
<Path exact path='/' component={Home} user={user} />
</PathGroup>
<PathGroup template={PrivateLayout} verify={this.props.user.logged} redirectFalse="/projects" >
<Path exact path='/profile' component={Profile} user={user} />
<Path exact path='/posts' component={Posts} user={user} />
<Path exact path='/posts/:idPost' component={Post} user={user} />
</PathGroup>
<PathGroup template={Login} verify={this.props.user.logged} redirectTrue="/projects" >
<Path exact path='/login' component={Login} />
</PathGroup>
<Route component={ NotFound } />
</Switch>
</BrowserRouter>
);
}
But when I run the app it shows just the first group
Also I tried with React.Fragment, but happens the same.
A: I don't know if this is the answer you want, but if you want to have a fallback page for each base route, the easiest way is to use nested switch.
import React, { Component } from "react";
import { render } from "react-dom";
import { Route, Switch, BrowserRouter } from "react-router-dom";
const Home = props => (
<div>
<Switch>
<Route path={props.match.url + "/1"} exact render={() => <h1>Home 1</h1>} />
<Route path={props.match.url + "/2"} exact render={() => <h1>Home 2</h1>} />
<Route render={() => <h1>Home 404</h1>} />
</Switch>
</div>
);
const Post = props => (
<div>
<Switch>
<Route path={props.match.url + "/1"} exact render={() => <h1>Post 1</h1>} />
<Route path={props.match.url + "/2"} exact render={() => <h1>Post 2</h1>} />
<Route render={() => <h1>Post 404</h1>} />
</Switch>
</div>
);
class App extends Component {
render() {
return (
<BrowserRouter>
<div>
<Switch>
<Route path="/home" component={Home} />
<Route path="/post" component={Post} />
<Route render={() => <h1>404</h1>} />
</Switch>
</div>
</BrowserRouter>
);
}
}
*
*The authentication can be done in each root route component, and then redirect to login page.
*Query parameter also can be used, so the same route can handle multiple ids.
Eg: <Route path={this.props.match.url + '/:id'} exact component={Post} /> and then, in Post component, using const { id } = this.props.match.params to get the id.
There is the CodeSandbox demo.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49267910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java - Sorting a 2D Array by Row Sum Trying to write a method that swaps the rows of a 2D array in order of increasing row sum.
For example, if I have the following 2d array:
int [][] array = {4,5,6},{3,4,5},{2,3,4};
I would want it to output an array as so:
{2 3 4}, {3 4 5}, {4 5 6}
Methodology:
a.) take the sums of each row and make a 1D array of the sums
b.) do a bubble sort on rowSum array
c.) swap the rows of the original array based on the bubble sort swaps made
d.) then print the newly row sorted array.
Here's my code so far:
public void sortedArrayByRowTot() {
int [][] tempArray2 = new int [salaryArray.length [salaryArray[0].length];
for (int i = 0; i < tempArray2.length; i++) {
for (int j = 0; j < tempArray2[i].length; j++) {
tempArray2[i][j] = salaryArray[i][j];
}
}
int [] rowSums = new int [tempArray2.length];
int sum = 0;
for (int i = 0; i < tempArray2.length; i++) {
for (int j = 0; j < tempArray2[i].length; j++) {
sum += tempArray2[i][j];
}
rowSums[i] = sum;
sum = 0;
}
int temp;
int i = -1;
for(int j = rowSums.length; j > 0; j--){
boolean isSwap = false;
for (i = 1; i < j; i++) {
if(rowSums[i-1] > rowSums[i]) {
temp = rowSums[i-1];
rowSums[i-1] = rowSums[i];
rowSums[i] = temp;
isSwap = true;
}
}
if(!isSwap){
break;
}
}
for (int k = 0; k < tempArray2.length; k++) {
temp = tempArray2[i-1][k];
tempArray2[i-1][k] = tempArray2[i][k];
tempArray2[i][k] = temp;
}
for (int b = 0; b < tempArray2.length; b++) {
for (int c = 0; c < tempArray2[b].length; c++) {
System.out.print(tempArray2[b][c] + " ");
}
}
}
}
Not sure if I am doing part c of my methodology correctly?
It keeps saying "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2"
A: As @shmosel said, you can do it like this:
public static void sortedArrayByRowTot() {
int [][] array = {{4,5,6},{3,4,5},{2,3,4}};
Arrays.sort(array, Comparator.comparingInt(a -> IntStream.of(a).sum()));
}
A: I was able to solve my question. Thanks.
public void sortedArrayByRowTot() {
//Creates tempArray2 to copy salaryArray into
int [][] tempArray2 = new int [salaryArray.length][salaryArray[0].length];
//Copies salaryArray into tempArray2
for (int i = 0; i < salaryArray.length; i++) {
for (int j = 0; j < salaryArray[i].length; j++) {
tempArray2[i][j] = salaryArray[i][j];
}
}
//Creates rowSum array to store sum of each row
int [] rowSums = new int [tempArray2.length];
for (int i = 0; i < tempArray2.length; i++) {
for (int j = 0; j < tempArray2[0].length; j++) {
rowSums[i] += tempArray2[i][j];
}
}
//Modified Bubble Sort of rowSum array (highest to lowest values)
int temp;
int i = 0;
for(int j = rowSums.length; j > 0; j--){
boolean isSwap = false;
for (i = 1; i < j; i++) {
if(rowSums[i-1] < rowSums[i]) {
temp = rowSums[i-1];
rowSums[i-1] = rowSums[i];
rowSums[i] = temp;
isSwap = true;
//swaps rows in corresponding tempArray2
int [] temp2 = tempArray2[i-1];
tempArray2[i-1] = tempArray2[i];
tempArray2[i] = temp2;
}
}
if(!isSwap){
break;
}
}
//Prints sorted array
System.out.println("Sorted array: ");
for (i = 0; i < tempArray2.length; i++) {
for (int j = 0; j < tempArray2[i].length; j++) {
System.out.print("$"+ tempArray2[i][j] + " ");
}
System.out.println();
}
}
A: You may try this way. That I have solved.
public class Solution{
public static void sortedArrayByRowTot() {
int [][] salaryArray = { {4,5,6},{3,4,5},{2,3,4} };
int [][] tempArray2 = new int [salaryArray.length][salaryArray[0].length];
for (int i = 0; i < salaryArray.length; i++) {
for (int j = 0; j < salaryArray[i].length; j++) {
tempArray2[i][j] = salaryArray[i][j];
}
}
// Buble Sort to store rowSums
int [] rowSums = new int [tempArray2.length];
for (int i = 0; i < tempArray2.length; i++) {
for (int j = 0; j < tempArray2[0].length; j++) {
rowSums[i] += tempArray2[i][j];
}
}
//Buble Sort by Rows Sum (Lowest Value to Highest)
int temp;
int i = 0;
for(int j = rowSums.length; j > 0; j--){
boolean isSwap = false;
for (i = 1; i < j; i++) {
if(rowSums[i-1] > rowSums[i]) {
temp = rowSums[i-1];
rowSums[i-1] = rowSums[i];
rowSums[i] = temp;
isSwap = true;
//swaps rows in corresponding tempArray2
int [] temp2 = tempArray2[i-1];
tempArray2[i-1] = tempArray2[i];
tempArray2[i] = temp2;
}
}
if(!isSwap){
break;
}
}
/** No Need.
for (int k = 0; k < tempArray2.length; k++) {
temp = tempArray2[i-1][k];
tempArray2[i-1][k] = tempArray2[i][k];
tempArray2[i][k] = temp;
}
*/
for (int b = 0; b < tempArray2.length; b++) {
for (int c = 0; c < tempArray2[b].length; c++) {
System.out.print(tempArray2[b][c] + " ");
}
}
}
public static void main(String[] args) {
sortedArrayByRowTot();
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44993028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Writing a P2P chat application in Python Is it possible to write a peer-to-peer chat application in Python?
I am thinking of this from a hobbyist project point-of-view. Can two machines connect to each other directly without involving a server? I have always wondered this, but never actually seen it implemented anywhere so I am thinking there must be a catch somewhere.
PS: I intend to learn Twisted, so if that is involved, it would be an added advantage!
A: Yes. You can do this pretty easily with Twisted. Just have one of the peers act like a server and the other one act like a client. In fact, the twisted tutorial will get you most of the way there.
The only problem you're likely to run into is firewalls. Most people run their home machines behind SNAT routers, which make it tougher to connect directly to them from outside. You can get around it with port forwarding though.
A: Yes, each computer (as long as their on the same network) can establish a server instance with inbound and outbound POST/GET.
A: I think i am way too late in putting my two bits here, i accidentally stumbled upon here as i was also searching on similar lines. I think you can do this fairly easily using just sockets only, however as mentioned above one of the machines would have to act like a server, to whome the other will connect.
I am not familiar with twisted, but i did achieved this using just sockets. But yes even i am curious to know how would you achieve peer2peer chat communication if there are multiple clients connected to a server. Creating a chat room kind of app is easy but i am having hard time in thinking how to handle peer to peer connections.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4269287",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: symfony2 doctrine multiple update / transaction I'm working on a Symfony2 project with doctrine and have some problems with a SQL update. I have a database table where all entries have a position attribute, since the order is important and changeable by the customer. Finally, I decided to save the position as simple integer values, without any implemented logic, and update any affected rows.
So, I wrote this function
public function swapCookingStepAction($recipeId, $posBefore, $posAfter) {
$em = $this->getDoctrine()->getManager();
$swappedEntry = $em->getRepository('BarraFrontBundle:CookingStep')->findOneBy(array('recipe'=>$recipeId, 'position'=>$posBefore));
$swappedEntry->setPosition($posAfter);
if ($posBefore < $posAfter)
$steps = $em->getRepository('BarraFrontBundle:CookingStep')->decreaseBetweenPos($recipeId, $posBefore+1, $posAfter);
else
$steps = $em->getRepository('BarraFrontBundle:CookingStep')->increaseBetweenPos($recipeId, $posAfter, $posBefore-1);
$em->flush();
return new Response("ok?");
}
and this repository with doctrine
class CookingStepRepository extends EntityRepository {
public function increaseBetweenPos($recipeId, $posBefore, $posAfter)
{
$query = $this->createQueryBuilder('c')
->update()
->set('c.position', 'c.position +1')
->where('c.recipe = :recipeId')
->andWhere('c.position BETWEEN :posBefore AND :posAfter')
->setParameter('posBefore', $posBefore)
->setParameter('posAfter', $posAfter)
->setParameter('recipeId', $recipeId)
->getQuery();
return $query->getResult();
}
public function decreaseBetweenPos($recipeId, $posBefore, $posAfter)
{
$query = $this->createQueryBuilder('c')
->update()
->set('c.position', 'c.position -1')
->where('c.recipe = :recipeId')
->andWhere('c.position BETWEEN :posBefore AND :posAfter')
->setParameter('posBefore', $posBefore)
->setParameter('posAfter', $posAfter)
->setParameter('recipeId', $recipeId)
->getQuery();
return $query->getResult();
}}
The queries are build as wished but unfortunately I get this primary key error
An exception occurred while executing 'UPDATE CookingStep SET position = position - 1 WHERE recipe = ? AND (position BETWEEN ? AND ?)' with params ["6", 2, "2"]:
Integrity constraint violation: 1062 Duplicate entry '1-6' for key 'PRIMARY'
for params (6, 1, 2). I tried to work with a transaction but this didn't change anything.
Could you help me, guys?
UPDATE
Just added a 4th parameter at the repository function and could remove the 2nd function.
If I change the primary key for tests, the code & update works very well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26348104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to show first page of the route without page number on Next JS I've been trying to create a blog page which contains pagination with numbers.
My pages folder is like below :
src
-pages
--blog
---[id].tsx
I am able to render all static pages with getStaticPaths function Next provides.
The issue is I would like to show first page as /blog instead of /blog/1.
How can I push the route /blog when there is /blog/1 content?
A: There could be (1) client side routing and (2) server side routing
create new page blog/index.tsx
src
-pages
--blog
---[id].tsx
---index.tsx
and redirect to /blog/1 in index.tsx(client side routing)
import { useEffect } from 'react'
import { useRouter } from 'next/router'
export default function Blog() {
useEffect(() => {
router.push('/blog/1')
}, [])
return <p>Redirecting...</p>
}
server side route
import { useEffect } from 'react'
import { useRouter } from 'next/router'
export default function Blog() {
useEffect(() => {
router.push('/blog/1')
}, [])
return <p>Redirecting...</p>
}
export const getServerSideProps = ({ req, res }) => {
res.writeHead(302, { Location: "/blog/1" });
res.end();
return {
props: {}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65264228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Prevent text keyboard input on Android/chrome mobile [web] I have a textarea with keyDown listener
<textarea onKeyDown={handleKeyDown}></textarea>
And the handleKeyDown function:
const handleKeyDown = event => event.preventDefault()
When I typing from windows PC, Chrome Version 90.0.4430.212 (Official Build) (64-bit) everything works perfect: text is not appearing in textarea.
When I typing from mac, chrome 90 everything works perfect too.
But when I grab my Android Phone (Samsung, Android 11), open Mobile Chrome (90.0.4430.210) and start typing, text IS appearing in textarea. And the worst thing is that the only mention about this bug I found is this question, which will be referenced by bots when marking my question as duplicate. There is no answer: maxlength attribute not working anymore.
This is the list of things I tried to prevent mobile chrome from input:
*
*Maxlength = 0 (no effect at all)
*readOnly (=disabled, I need focus and selection)
*blocking onKeyUp, onKeyPress, onPaste, onCut, onInput
I also tried to manually set value of textarea to '' but if I set a listener which does this, my textarea become completely broken: each time I press key on keyboard, it duplicates all previous content.
My question is how to prevent input, maybe there is a hack or trick? Please don't send me to android report forums where this bug may be discussed or another questions...
A: I would first check to see if the events are working when adding eventlisteners. There must be a way to handle key events on Android:
<textarea id="mytextarea"></textarea>
let mytextarea = document.getElementById('mytextarea');
mytextarea.addEventListener('keydown', (event) => {
console.log(event.code);
});
If this is not working; you asked for a hack or trick: try the focus and blur events, then you could run a function on interval that clears the textarea. Note that this blocking trick is something that goes against good user experience conventions, so should be considered a hack/trick for sure ;-)
<textarea id="mytextarea"></textarea>
let int1;
let mytextarea = document.getElementById('mytextarea');
mytextarea.addEventListener('focus', () => {
clearInterval(int1);
int1 = setInterval(() => {
mytextarea.value = '';
}, 10)
});
mytextarea.addEventListener('blur', () => {
clearInterval(int1);
});
A: Instead of using event.key or event.code properties of keypress (keyup, keydown) event, I have used event.inputType, event.data of update event and added few restricting attributes to the input tag to overcome 'smartness' of mobile keyboard app. It is an ugly hack but worked for my purpose.
HTML:
<textarea id="inpt" autocapitalize="none" autocomplete="off" autocorrect="off" spellcheck="false" ></textarea>
</div>
JS:
var inpt = document.getElementById('inpt');
inpt.addEventListener('input', do_on_input);
function do_on_input(e) {
if( e.inputType == "insertText"){
console.log( e.data );
}
if( e.inputType == "deleteContentBackward"){
console.log('Backspace');
}
if( e.inputType == "insertCompositionText"){
// without restrictive attribbutes you will need to deal with this type events
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67529716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.