text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: Exlude a directory in .htaccess with RedirectMatch for Wordpress I change my Wordpress permalink structure from %year%/%months%/ to %postname%
So i create this mod alias rules in .htaccess but i have a problem:
RedirectMatch 301 /\d{4}/\d{2}/([^/]+)(/?)(.*)$ http://domainname.com/$1
The rules also redirect the images under the wp-content directory, so domainname.com/wp-content/uploads/2013/11/name.jpg become domainname.com/name.jpg
I can't use RewriteCond because this RedirecMatch is mod_alias, i try to use !^/(wp-content.*)$ but doesn't work.
How can i solve? It's better to use RedirectMach or RewriteRule (i haven't changed the server)?
Can you post a better regex?
Thank you!
A: Try ^ and $:
RedirectMatch 301 ^/\d{4}/\d{2}/([^/]+)(/?)(.*)$ http://domainname.com/$1
A: You should probably stick with using mod_rewrite instead of mod_alias because it'll interfere with wordpress' mod_rewrite rules. Both mod_rewrite and mod_alias affect the same request URI at different points in the URL-file processing pipeline, so you could end up getting redirected and rewritten at the same time.
RewriteCond %{REQUEST_URI} !\.(jpeg|gif|png)$ [NC]
RewriteRule ^\d{4}/\d{2}/([^/]+?)(/?)(.*)$ http://domainname.com/$1 [L,R=301]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20006351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Using Diagrammr package to make a flow DiagrammeR I am trying to make a flow to show my experimental design. I have something that works, but I would like to add another layer at the bottom-which adds a question box to each group, which should be big enough to read. An example of what I have is image 1 hoping for is in image 2. Such that group 1 has a question and answer (with arrows) and group 2 and 3 has a question and 3 answers (with arrows). Of course, the arrows should be black and in the right place-its just hard to do in word!
Does anyone know how I can do this?
Image 1
Image 2
Code:
# install.packages("DiagrammeR")
#library(DiagrammeR)
schematic <- grViz("digraph lexicon {
# node definitions with substituted label text
node [fontname = Helvetica, shape = rectangle, style=filled,color=lightgrey]
tab1 [label = '@@1']
tab2 [label = '@@2']
tab3 [label = '@@3']
tab4 [label = '@@4']
tab5 [label = '@@5']
node [shape = rectangle, fillcolor=PeachPuff]
tab6 [label = '@@6']
node [shape = rectangle, fillcolor=CadetBlue]
tab7 [label = '@@7']
node [shape = rectangle, fillcolor=Lavender]
tab8 [label = '@@8']
node [fontname = Helvetica, shape = rectangle, style=bold]
m1 [label = 'Did not agree to participate n=18']
m2 [label = 'Under 18 years n=11']
m3 [label = 'No smoke in past 3 months n=8']
m4 [label = 'Did not complete survey n=155']
# creating horizontal lines
node [shape=none, width=0, height=0, label='']
{rank=same; tab1 -> m1}
{rank=same; tab2 -> m2}
{rank=same; tab3 -> m3}
{rank=same; tab4 -> m4}
# edge definitions with the node IDs
tab1 -> tab2 -> tab3 -> tab4 -> tab5->{tab6 tab7 tab8};
}
[1]: 'Raw Data n=434'
[2]: 'Agreed to participate n=406'
[3]: 'Over 18 years n=491'
[4]: 'smoke in past 3 months=403'
[5]: 'Final sample n=238'
[6]: 'Group1 n=82'
[7]: 'Group2 n=98'
[8]: 'Group3 n=88'
")
jpeg(file = "schematic.jpg")
schematic
A: You can just add some more nodes
schematic <- grViz("digraph lexicon {
# node definitions with substituted label text
node [fontname = Helvetica, shape = rectangle, style=filled,color=lightgrey]
tab1 [label = '@@1']
tab2 [label = '@@2']
tab3 [label = '@@3']
tab4 [label = '@@4']
tab5 [label = '@@5']
node [shape = rectangle, fillcolor=PeachPuff]
tab6 [label = '@@6']
node [shape = rectangle, fillcolor=CadetBlue]
tab7 [label = '@@7']
node [shape = rectangle, fillcolor=Lavender]
tab8 [label = '@@8']
node [fontname = Helvetica, shape = rectangle, style=bold]
m1 [label = 'Did not agree to participate n=18']
m2 [label = 'Under 18 years n=11']
m3 [label = 'No smoke in past 3 months n=8']
m4 [label = 'Did not complete survey n=155']
# ------> NEW NODES
node [fontname = Helvetica, shape = rectangle, style=bold, width = 2.5, height = 1, ALIGN = LEFT]
q1 [label = 'Question 1 \\l\n\n']
q2 [label = 'Question 2 \\l\n\n']
q3 [label = 'Question 3 \\l\n\n']
a11 [label = 'Answer 1 \\l\n\n']
a21 [label = 'Answer 1 \\l\n\n']
a22 [label = 'Answer 2 \\l\n\n']
a23 [label = 'Answer 3 \\l\n\n']
a31 [label = 'Answer 1 \\l\n\n']
a32 [label = 'Answer 2 \\l\n\n']
a33 [label = 'Answer 3 \\l\n\n']
# creating horizontal lines
node [shape=none, width=0, height=0, label='']
{rank=same; tab1 -> m1}
{rank=same; tab2 -> m2}
{rank=same; tab3 -> m3}
{rank=same; tab4 -> m4}
# edge definitions with the node IDs
tab1 -> tab2 -> tab3 -> tab4 -> tab5->{tab6 tab7 tab8};
#--------> ATTACH NEW NODES
tab6 -> q1 -> a11
tab7 -> q2 -> a21 -> a22 -> a23
tab8 -> q3 -> a31 -> a32 -> a33
}
[1]: 'Raw Data n=434'
[2]: 'Agreed to participate n=406'
[3]: 'Over 18 years n=491'
[4]: 'smoke in past 3 months=403'
[5]: 'Final sample n=238'
[6]: 'Group1 n=82'
[7]: 'Group2 n=98'
[8]: 'Group3 n=88'
")
jpeg(file = "schematic.jpg")
schematic
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71520514",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to turning back the situation when button clicked again in Qt? Basically I created QListWidget and QPushButton and I want to list current item in the widget when I clicked the button.Until here it is fine. What I want is after clicking that button again, I want to see previous situation(old item!) of that item. How can I do that?
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
for(int i = 0; i < 9; i++ ){
ui->listWidget->addItem(QString::number(i) + " old item!");
}
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::on_pushButton_clicked()
{
QListWidgetItem *itm = ui->listWidget->currentItem();
itm->setText("new item!");
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65550441",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to fetch the link that is outside the href tag? private static final Pattern ptninhref =Pattern.compile(
"(?:.*\\<[aA][^\\>]*(?i)href(?-i)=\\\"[^\\\"]*)([^\\\"]*)");
public static List<String> captureValuesinhref(String largeText){
Matcher mtchinhref = ptninhref.matcher(largeText);
List<String> inHREF = new ArrayList<>();
while(mtchinhref.find()){
inHREF.add(mtchinhref.group());
How to fetch only "link is given "?
When i am using (?:.*\<[aA][^\>]*(?i)href(?-i)=\"[^\"]*)([^\"]*)(?:[^\"]*\".*\</[aA]\>.*) this regular expression code, it gives me output like: <a href="link is given here">link is given here</a>.
But required output only: "link is given here"
I have required the link which is outside the href tag.
There are two link :
1 is inside the href tag.
2 is outside the href tag that is shown in the browser.
I have required the 2nd link only.
How to fetch that using java in netbeans?
A: public class RegexExample {
/**
* @param args
*/
public static void main(String[] args) {
String href= "<a href=\"w3schools.com\">Visit W3Schools.com!</a>";
String regexOr = "(?<=[>])(\\\\?.)*?(?=[<])";
Pattern pattern = Pattern.compile(regexOr);
Matcher matcher = pattern.matcher(href);
if (matcher.find()) {
String enrichedValue = matcher.group();
System.out.print(enrichedValue);
}
}
}
This will print:
Visit W3Schools.com!
Keep in mind \ becomes \\ in java, it needs to be escaped
Full example:
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
private static final Pattern ptninhref;
static{
ptninhref = Pattern.compile("(?<=[>])(\\\\?.)*?(?=[<])");
}
/**
* @param args
*/
public static void main(String[] args) {
String href= "<a href=\"paypal.com/signin/\">https://www.paypa1.com/signin/</a>";
List<String> results = captureValuesinhref(href);
for(String result:results){
System.out.print(result);
}
}
public static List<String> captureValuesinhref(String largeText){
Matcher mtchinhref = ptninhref.matcher(largeText);
List<String> inHREF = new ArrayList<String>();
while(mtchinhref.find()){
inHREF.add(mtchinhref.group());
}
return inHREF;
}
}
prints:
https://www.paypa1.com/signin/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29792306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: SQL - group by with two colums agregation problem My today's problem is that I have a table that has rows like that:
ID NAME NUMBER IDN
1 dsad 500600 12
1 dsad 600700 13
2 kkkk 111222 56
2 kkkk 333232 57
in one ID example 1 i have 2 identical names 2 different numbers and different IDN.
What i want is to extract single row For each Id where the idn value is the smaller one.
So I want to have sommething like that
1 dsad 500600 12
2 kkkk 111222 56
Is it posible to write a single sql to have that result? I tried to group that by ID and NAME and have the min(IDN) but I'm stuck with the number field :) any ideas?
A: You were almost there, just add the MIN(Number) field.
SELECT ID
, NAME
, MIN(NUMBER)
, MIN(IDN)
FROM ATable
GROUP BY
ID
, NAME
In response to comment
Following would get you the records with the MIN(IDN), regardless what the number for that specific record is.
SELECT t.*
FROM ATable t
INNER JOIN (
SELECT ID, IDN = MIN(IDN)
FROM ATable
GROUP BY ID
) tmin ON tmin.ID = t.ID
AND tmin.IDN = t.IDN
A: DECLARE @TABLE table (ID int, [NAME] varchar(100),NUMBER int ,IDN int)
insert into @TABLE SELECT 1,'dsad',500600,12
insert into @TABLE SELECT 1,'dsad',600700, 13
insert into @TABLE SELECT 2,'kkkk',111222, 56
insert into @TABLE SELECT 2,'kkkk',333232, 57
select t.ID, t.[Name], t.Number, t.IDN
from (
select [NAME],min(IDN) as minIDN
from @TABLE group by [NAME]
) as x inner join @TABLE as t on t.[Name]=x.[Name] and t.IDN = x.minIDN;
A: Version that only uses a left join and no subqueries, with SQlite3 and a shell script since I don't have anything other at hand ATM:
#!/bin/sh
rm -f test.sqlite
sqlite3 test.sqlite << AAA
CREATE TABLE test (id int, name text, number int, idn int);
INSERT INTO test VALUES(1,'dsad',500600,12);
INSERT INTO test VALUES(1,'dsad',600700,13);
INSERT INTO test VALUES(2,'kkkk',111222,56);
INSERT INTO test VALUES(2,'kkkk',333232,57);
INSERT INTO test VALUES(1,'dsad',600700,9);
INSERT INTO test VALUES(2,'kkkk',333232,59);
INSERT INTO test VALUES(2,'cccc',333232,59);
SELECT a.* FROM test a
LEFT JOIN test b ON
a.id=b.id AND
a.name=b.name
AND a.idn > b.idn
WHERE b.id IS NULL;
AAA
# Result:
# 1|dsad|600700|9
# 2|cccc|333232|59
# 2|kkkk|111222|56
Can anyone comment on where the performance is better? I think that matters, too!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4803231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: onSuccessListner after image crop permission I am getting image cropping like this:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
//do some activity based on permission granted or declined.
} else {
CropImage.activity(mainImageURI)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.setAutoZoomEnabled(false)
.start(this);
;
}
}
My question is I want to do some activity right after the permission is granted or declined. In current scenario, I can first grant the permission and then again click again the imageview I am using, and then the cropping. But I want to have one activity right after the permission is granted and one if permission is denied.
A: You should override onRequestPermissionsResult in your activity in order to get notified whenever permission is granted or not:
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSIONS_CODE) {
for (int i = 0; i < permissions.length; i++) {
String permission = permissions[i];
int grantResult = grantResults[i];
if (permission.equals(Manifest.permission.READ_EXTERNAL_STORAGE)) {
if (grantResult == PackageManager.PERMISSION_GRANTED) {
// TODO Open The Crop Activity
} else {
// TODO Tell the user your app can't function properly
}
}
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52799456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: WPF download multiple files with progress in popup Hy,
I am trying to make a popup indicating the progress of the download of several files. I'm not used to working with await/async and think I'm probably making a big mistake in this case.
The goal is to follow the progress of the file download one by one, I don't want to run all the downloads at the same time. And also have a general look at the progress of all the files to download.
Here is my actual code:
In a first Window I genereate the file list and send it in a PopUp:
Popupdownload inputDialog = new Popupdownload(FileList);
if (inputDialog.ShowDialog() == true)
{
MessageBox.Show(FileList.Count().ToString() + " files are downloaded");
}
My popup class :
public partial class Popupdownload: Window
{
public Popupdownload(List<string> listFiles)
{
InitializeComponent();
DowloadList(listFiles);
}
public async void DowloadList(List<string> listFiles)
{
int counter = 0;
foreach (string e in listFiles)
{
FileInfo TempFile = new FileInfo(System.IO.Path.Combine(App.folderpath, e));
Uri myUri = new Uri("http://********/" + e), UriKind.Absolute);
await DownloadFile(myUri, TempFile.FullName);
counter++;
progressBarTotal.Value = 100*(double)counter / (double)listFiles.Count();
}
}
Stopwatch sw = new Stopwatch();
public async Task DownloadFile(Uri URL, string location)
{
using (WebClient webClient = new WebClient())
{
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
sw.Start();
try
{
webClient.DownloadFileAsync(URL, location);
}
catch (Exception ex)
{
MessageBox.Show("The file " + location + " hasn't been dowload. Contact admin");
}
}
}
private void ProgressChanged(object sender, System.Net.DownloadProgressChangedEventArgs e)
{
labelSpeed.Content = string.Format("{0} kb/s", (e.BytesReceived / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00"));
progressBar.Value = e.ProgressPercentage;
labelPerc.Content = e.ProgressPercentage.ToString() + "%";
labelDownloaded.Content = string.Format("{0} MB's / {1} MB's",
(e.BytesReceived / 1024d / 1024d).ToString("0.00"),
(e.TotalBytesToReceive / 1024d / 1024d).ToString("0.00"));
}
private void Completed(object sender, AsyncCompletedEventArgs e)
{
sw.Reset();
if (e.Cancelled == true)
{
MessageBox.Show("Download has been canceled.");
}
else
{
// MessageBox.Show("Download completed!");
}
}
}
My current code is a digest of several sources, and I am not sure that some parts work well.
My previous synchronius version of it is working, but hasn't the current file download status preview that I'would like.
It seem to me that all dowloads are launch in same time and it doesn't wait until first has stopped. So it is probably my first issue.
Thanks for your help
A: Here is how I resolve my question:
First my program launch a PopUp with the file list in argument.
Popupdownload inputDialog = new Popupdownload(FileList);
The Popupdownload windows :
public partial class Popupdownload: Window
{
// Global Clock for speed processing
Stopwatch sw = new Stopwatch();
// PopUp Initialisation
public Popupdownload(List<string> listFiles)
{
InitializeComponent();
DowloadListASync(listFiles, type);
}
// List processing with Progress Status Update
public async void DowloadListASync(List<string> listFiles)
{
int counter = 0;
long totalSize = 0;
int totalcounter = listFiles.Count();
progressLabelTotal.Content = 1 + "/" + totalcounter.ToString();
var sw = Stopwatch.StartNew();
foreach (string e in listFiles)
{
progressBarTotal.Value = 100 * (double)counter / (double)totalcounter;
FileInfo TempFile = new FileInfo(System.IO.Path.Combine(App.folderpath, e));
Uri myUri = new Uri("http://www.XXXX/" + e, UriKind.Absolute);
if (!TempFile.Directory.Exists)
{
TempFile.Directory.Create();
}
if (TempFile.Exists) TempFile.Delete();
await DownloadAFile(myUri, TempFile.FullName);
counter++;
TempFile = new FileInfo(System.IO.Path.Combine(App.folderpath, e));
if (TempFile.Exists)
{
totalSize += TempFile.Length;
}
else
{
totalcounter--;
counter--;
}
var totalSpeed = (totalSize / 1024d / (sw.Elapsed.TotalSeconds));
if (totalSpeed < 800)
{
labelTotalSpeed.Content = string.Format("{0} kb/s", totalSpeed.ToString("0.00"));
}
else
{
totalSpeed = ((totalSize / 1024d) / 1024d / (sw.Elapsed.TotalSeconds));
labelTotalSpeed.Content = string.Format("{0} Mb/s", totalSpeed.ToString("0.00"));
}
progressBarTotal.Value = 100 * (double)counter / (double)totalcounter;
labelTotalPerc.Content = ((double)counter / (double)totalcounter).ToString("P");
progressLabelTotal.Content = (counter != totalcounter) ? (1 + counter).ToString() + "/" + totalcounter.ToString() : "Téléchargment effectué";
}
Close;
}
//async Download file with HttpClient, and keep progress
public async Task DownloadAFile(Uri URL, string location)
{
using (var client = new HttpClientDownloadWithProgress(URL.AbsoluteUri, location))
{
var watch = Stopwatch.StartNew();
FileInfo TempFile = new FileInfo(location);
client.ProgressChanged += (totalFileSize, totalBytesDownloaded, progressPercentage) => {
Nomfichier.Content = TempFile.Name;
labelPerc.Content = progressPercentage.ToString() + "%";
progressBar.Value = (double)progressPercentage;
// labelSpeed.Content = string.Format("{0} kb/s", (totalBytesDownloaded / 1024d / (watch.Elapsed.TotalSeconds)).ToString("0.00"));
var speed = (totalBytesDownloaded / 1024d / (watch.Elapsed.TotalSeconds));
if (speed < 800)
{
labelSpeed.Content = string.Format("{0} kb/s", speed.ToString("0.00"));
}
else
{
speed = ((totalBytesDownloaded / 1024d) / 1024d / (watch.Elapsed.TotalSeconds));
labelSpeed.Content = string.Format("{0} Mb/s", speed.ToString("0.00"));
}
// Console.WriteLine($"{progressPercentage}% ({totalBytesDownloaded}/{totalFileSize})");
};
await client.StartDownload();
Nomfichier.Content = "";
}
}
and the HttpClientDownload class used like in comment:
public class HttpClientDownloadWithProgress : IDisposable
{
private readonly string _downloadUrl;
private readonly string _destinationFilePath;
private HttpClient _httpClient;
public delegate void ProgressChangedHandler(long? totalFileSize, long totalBytesDownloaded, double? progressPercentage);
public event ProgressChangedHandler ProgressChanged;
public HttpClientDownloadWithProgress(string downloadUrl, string destinationFilePath)
{
_downloadUrl = downloadUrl;
_destinationFilePath = destinationFilePath;
}
public async Task StartDownload()
{
_httpClient = new HttpClient { Timeout = TimeSpan.FromDays(1) };
using (var response = await _httpClient.GetAsync(_downloadUrl, HttpCompletionOption.ResponseHeadersRead))
await DownloadFileFromHttpResponseMessage(response);
}
private async Task DownloadFileFromHttpResponseMessage(HttpResponseMessage response)
{
response.EnsureSuccessStatusCode();
var totalBytes = response.Content.Headers.ContentLength;
using (var contentStream = await response.Content.ReadAsStreamAsync())
await ProcessContentStream(totalBytes, contentStream);
}
private async Task ProcessContentStream(long? totalDownloadSize, Stream contentStream)
{
var totalBytesRead = 0L;
var readCount = 0L;
var buffer = new byte[8192];
var isMoreToRead = true;
using (var fileStream = new FileStream(_destinationFilePath, FileMode.Create, FileAccess.Write, FileShare.None, 8192, true))
{
do
{
var bytesRead = await contentStream.ReadAsync(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
isMoreToRead = false;
TriggerProgressChanged(totalDownloadSize, totalBytesRead);
continue;
}
await fileStream.WriteAsync(buffer, 0, bytesRead);
totalBytesRead += bytesRead;
readCount += 1;
if (readCount % 100 == 0)
TriggerProgressChanged(totalDownloadSize, totalBytesRead);
}
while (isMoreToRead);
}
}
private void TriggerProgressChanged(long? totalDownloadSize, long totalBytesRead)
{
if (ProgressChanged == null)
return;
double? progressPercentage = null;
if (totalDownloadSize.HasValue)
progressPercentage = Math.Round((double)totalBytesRead / totalDownloadSize.Value * 100, 2);
ProgressChanged(totalDownloadSize, totalBytesRead, progressPercentage);
}
public void Dispose()
{
_httpClient?.Dispose();
}
}
My last wish would be to be able to run downloads in bundles of 3-4 and handle 404 errors when the target file is missing. Work In Progress. If anyone has a clue.
Thanks @steeeve for your comment.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68739724",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to create a subgrid on one Form and pass its values to a look up in another form Hi i am a completely new to crm2011 and I'm really stuck on with this -
I have created a Candidate form with FirstName, LastName and a look up that will display his college details.
I have also created a Form named College with fields - College name and Address and below i have created a subgrid.
I want the below subgrid to show lists of registered candidates from Candidates Entity
Now onload of College form i will enter college details and choose one or more candidate from the subgrid and on click of create the college details should be assigned automatically to the look up in Candidates Form.
What i have done is-
*
*Created the College Form and created a subgrid on the same page associated it with the Candidates entity
*Created the Candidate Form and created a lookup on Candidate Form
and associated it with the College Entity
But beyond this i am not understanding how shall i go about it. Also the Subgrid is not showing candidates data in the grid onload
Please if anyone can help me kick start with this.
A: A SubGird associated with candidates will only show candidates that are already connected to collage.
When you create a new collage it does not exist yet so you can’t associate candidates with it anyway.
What you’re trying to do can only be accomplished via plug-in (server side code) and some JS that collects the selected candidates from a General SubGrid
That enlists all candidates. The JS should drill in to get selected candidates and save there guids (ids) in some arbitrary text field to be used in the plug-in.
Once candidates are related to this newly created collage you can see the association in the associated view on the navigation pane.
The easier way is to do it the way CRM intended it to be, which is to firstly create the collage record and then go to its associated candidates view and add them.
Good Luck
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19675330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Find the oldest file (recursively) in a directory I'm writing a Python backup script and I need to find the oldest file in a directory (and its sub-directories). I also need to filter it down to *.avi files only.
The script will always be running on a Linux machine. Is there some way to do it in Python or would running some shell commands be better?
At the moment I'm running df to get the free space on a particular partition, and if there is less than 5 gigabytes free, I want to start deleting the oldest *.avi files until that condition is met.
A: I think the easiest way to do this would be to use find along with ls -t (sort files by time).
something along these lines should do the trick (deletes oldest avi file under specified directory)
find / -name "*.avi" | xargs ls -t | tail -n 1 | xargs rm
step by step....
find / -name "*.avi" - find all avi files recursively starting at the root directory
xargs ls -t - sort all files found by modification time, from newest to oldest.
tail -n 1 - grab the last file in the list (oldest)
xargs rm - and remove it
A: Here's another Python formulation, which a bit old-school compared to some others, but is easy to modify, and handles the case of no matching files without raising an exception.
import os
def find_oldest_file(dirname="..", extension=".avi"):
oldest_file, oldest_time = None, None
for dirpath, dirs, files in os.walk(dirname):
for filename in files:
file_path = os.path.join(dirpath, filename)
file_time = os.stat(file_path).st_mtime
if file_path.endswith(extension) and (file_time<oldest_time or oldest_time is None):
oldest_file, oldest_time = file_path, file_time
return oldest_file, oldest_time
print find_oldest_file()
A: Hm. Nadia's answer is closer to what you meant to ask; however, for finding the (single) oldest file in a tree, try this:
import os
def oldest_file_in_tree(rootfolder, extension=".avi"):
return min(
(os.path.join(dirname, filename)
for dirname, dirnames, filenames in os.walk(rootfolder)
for filename in filenames
if filename.endswith(extension)),
key=lambda fn: os.stat(fn).st_mtime)
With a little modification, you can get the n oldest files (similar to Nadia's answer):
import os, heapq
def oldest_files_in_tree(rootfolder, count=1, extension=".avi"):
return heapq.nsmallest(count,
(os.path.join(dirname, filename)
for dirname, dirnames, filenames in os.walk(rootfolder)
for filename in filenames
if filename.endswith(extension)),
key=lambda fn: os.stat(fn).st_mtime)
Note that using the .endswith method allows calls as:
oldest_files_in_tree("/home/user", 20, (".avi", ".mov"))
to select more than one extension.
Finally, should you want the complete list of files, ordered by modification time, in order to delete as many as required to free space, here's some code:
import os
def files_to_delete(rootfolder, extension=".avi"):
return sorted(
(os.path.join(dirname, filename)
for dirname, dirnames, filenames in os.walk(rootfolder)
for filename in filenames
if filename.endswith(extension)),
key=lambda fn: os.stat(fn).st_mtime),
reverse=True)
and note that the reverse=True brings the oldest files at the end of the list, so that for the next file to delete, you just do a file_list.pop().
By the way, for a complete solution to your issue, since you are running on Linux, where the os.statvfs is available, you can do:
import os
def free_space_up_to(free_bytes_required, rootfolder, extension=".avi"):
file_list= files_to_delete(rootfolder, extension)
while file_list:
statv= os.statvfs(rootfolder)
if statv.f_bfree*statv.f_bsize >= free_bytes_required:
break
os.remove(file_list.pop())
statvfs.f_bfree are the device free blocks and statvfs.f_bsize is the block size. We take the rootfolder statvfs, so mind any symbolic links pointing to other devices, where we could delete many files without actually freeing up space in this device.
UPDATE (copying a comment by Juan):
Depending on the OS and filesystem implementation, you may want to multiply f_bfree by f_frsize rather than f_bsize. In some implementations, the latter is the preferred I/O request size. For example, on a FreeBSD 9 system I just tested, f_frsize was 4096 and f_bsize was 16384. POSIX says the block count fields are "in units of f_frsize" ( see http://pubs.opengroup.org/onlinepubs/9699919799//basedefs/sys_statvfs.h.html )
A: Check out the linux command find.
Alternatively, this post pipes together ls and tail to delete the oldest file in a directory. That could be done in a loop while there isn't enough free space.
For reference, here's the shell code that does it (follow the link for more alternatives and a discussion):
ls -t -r -1 /path/to/files | head --lines 1 | xargs rm
A: To do it in Python, you can use os.walk(path) to iterate recursively over the files, and the st_size and st_mtime attributes of os.stat(filename) to get the file sizes and modification times.
A: You can use stat and fnmatch modules together to find the files
ST_MTIME refere to the last modification time. You can choose another value if you want
import os, stat, fnmatch
file_list = []
for filename in os.listdir('.'):
if fnmatch.fnmatch(filename, '*.avi'):
file_list.append((os.stat(filename)[stat.ST_MTIME], filename))
Then you can order the list by time and delete according to it.
file_list.sort(key=lambda a: a[0])
A: The os module provides the functions that you need to get directory listings and file info in Python. I've found os.walk to be especially useful for walking directories recursively, and os.stat will give you detailed info (including modification time) on each entry.
You may be able to do this easier with a simple shell command. Whether that works better for you or not depends on what you want to do with the results.
A: Using standard library's pathlib:
from pathlib import Path
def creation_time(path: Path):
return path.stat().st_ctime
working_dir = Path()
avi_files = working_dir.glob("**/*.avi")
sorted_avi_files = sorted(avi_files, key=creation_time)
print(sorted_avi_files[0])
Or if you like one-liners:
min(Path().glob("**/*.avi"), key=lambda p: p.stat().st_ctime)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/837606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: How to use local variables when calling show on an object i.e. @object.this_#{variable}? Is there any way to pass a variable through to an instance in a show partial? Basically I'm creating a service that follows CRUD and want to be able to iterate an instanced variable. I can create it by passing a partial like so:
In the parent view:
<%= form_for(@report) do |f| %>
<%= render :partial => "reports/forms/partial_form", :locals => {:g => f, :var => "01"} %>
<% end %>
In the partial view:
<label><%= "Enter Data for Variable #{lane_number}" %></label>
<%= g.text_field :"Variable_#{var}" %>
This is useful the variables in the partial have a similar-enough naming convention to use the same var to iterate through several items. This works just fine.
I would like to do something similar when viewing the input data, but I can't figure out how to pass that var to the instance variable.
In the parent view:
<%= render :partial => "reports/shows/partial_show", :locals => {:var => "01"} %>
In the partial view:
<%= @report.Variable_#{var} %>
I know that #{var} is just used for string interpolation (which is why it works in the original create), but is there a way for me to do this by passing the variable to the partial?
A: You can use metaprogramming to get variable value because you just call a method:
<%= @report.send("variable_#{var}") %>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43416954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Button in Material UI is transparent when loading Every time I start a new project with Material UI, I have the same problem with buttons ignoring their primary color. For a second when loading, the background color is clearly visible, but after that the button is transparent.
I have installed all the necessary packages:
npm install @mui/material @emotion/react @emotion/styled
And just placed a button like this:
import {Button} from "@mui/material";
<Button variant="contained" color="primary">Contained</Button>
EDIT:
I found that if I delete the following line from globals.css, the Material UI works as it should. But I need this because we will also use tailwind for styling
@tailwind base;
@tailwind components;
@tailwind utilities;
A: You must disable preflight in your TailwindCSS configuration to prevent defaults overriding MUI styling:
// tailwind.config.js
module.exports = {
corePlugins: {
preflight: false,
}
}
If you have not done so already, you should also follow MUI instructions for changing the CSS injection order if you are going to use external style sheets in order to reliably style MUI components using TailwindCSS.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75202373",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Parse a json file and add the strings to a URL How do I parse a json output get the list from data only and then add the output into say google.com/confidetial and the other strings in the list.
so my json out put i will name it "text"
text = {"success":true,"code":200,"data":["Confidential","L1","Secret","Secret123","foobar","maret1","maret2","posted","rontest"],"errs":[],"debugs":[]}.
What I am looking to do is get the list under data only. so far the script i got is giving me the entire json out put.
json.loads(text)
print text
output = urllib.urlopen("http://google.com" % text)
print output.geturl()
print output.read()
A: jsonobj = json.loads(text)
print jsonobj['data']
Will print the list in the data section of your JSON.
If you want to open each as a link after google.com, you could try this:
def processlinks(text):
output = urllib.urlopen('http://google.com/' % text)
print output.geturl()
print output.read()
map(processlinks, jsonobj['data'])
A: info = json.loads(text)
json_text = json.dumps(info["data"])
Using json.dumps converts the python data structure gotten from json.loads back to regular json text.
So, you could then use json_text wherever you were using text before and it should only have the selected key, in your case: "data".
A: Perhaps something like this where result is your JSON data:
from itertools import product
base_domains = ['http://www.google.com', 'http://www.example.com']
result = {"success":True,"code":200,"data":["Confidential","L1","Secret","Secret123","foobar","maret1","maret2","posted","rontest"],"errs":[],"debugs":[]}
for path in product(base_domains, result['data']):
print '/'.join(path) # do whatever
http://www.google.com/Confidential
http://www.google.com/L1
http://www.google.com/Secret
http://www.google.com/Secret123
http://www.google.com/foobar
http://www.google.com/maret1
http://www.google.com/maret2
http://www.google.com/posted
http://www.google.com/rontest
http://www.example.com/Confidential
http://www.example.com/L1
http://www.example.com/Secret
http://www.example.com/Secret123
http://www.example.com/foobar
http://www.example.com/maret1
http://www.example.com/maret2
http://www.example.com/posted
http://www.example.com/rontest
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17678209",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL simultaneously transforming foreign key? (MySQL 5.5) I have a table with a natural key and another with a foreign key constaint to it:
create table A
(
id varchar(255) not null primary key
...
)
create table B
(
a_id varchar(255) not null
...
foreign key (a_id) references A (id)
)
I would like to execute a transformation on A.id, (in this specific case lowercasing it) and simulataneously on B.a_id.
Obviously if I do:
update A set id=lower(id);
update B set a_id=lower(a_id);
Than I will get a foreign key constraint violation on the first update.
Is there anyway to execute the two updates "simultaneously", or can you recommend another way to deal with this?
A: Simplest Approach might be to Drop the constraint,
Perform Update Queries
Again, Introduce the Foreign Key Constraint.
A: drop the constraint and re-create the constraint with ON UPDATE CASCADE
then execute the update stament on the parent table no child table would get modified.
ALTER TTABLE b ADD CONSTARINT fk_const
FOREIGN KEY(a_id) REFERENCE a (id) ON UPDATE CASCADE
now execute this update
update A set id=lower(id);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12927339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Commenting Out in XML Is the first set of comment out code below an issue for xml to process since it is put inside of the tag?
<!--Define name="default election policy">
<Policy name="DefaultToWaive"/>
</Define-->
<!--
<Define name="default election policy">
<Policy name="DefaultToWaive"/>
</Define>
-->
A: No, it's not an issue. It's just interpreted as a comment starting with "Define name=...". It also doesn't matter if you put it on the same line or on separate lines. You could as well write:
<!--<Define name="default election policy">
<Policy name="DefaultToWaive"/>
</Define>-->
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31253850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery .prop() returns undefined, while .attr() works as expected for data-* I am simply trying to get a couple of properties from two elements. Getting the property value from the input element works as expected. The problem is with getting the property data-detail property from the button element. It returns undefined when using .prop(), but works as expected when using .attr().
Can anyone explain this odd behaviour I am witnessing?
HTML
<div class="formRow">
<label for="firstName">First name</label>
<div class="detailsControlBtns">
<button id="editFirstName" class="btn ctaBtn greenBtn editBtn">Edit</button>
<button class="btn ctaBtn greenBtn saveBtn" data-detail="firstName">Save</button>
<button id="closeFirstName" class="btn ctaBtn greyBtn closeBtn">Close</button>
</div>
<input type="text" id="firstName" name="firstName" value="[+firstName+]" readonly>
</div>
JS
$(".saveBtn").on("click", function() {
var saveBtn = $(this);
// The following statement yields undefined. When using .attr() it works as expected.
var detail = saveBtn.prop("data-detail");
var relevantInput = saveBtn.parent().next();
// The following statement works as expected.
var value = relevantInput.prop("value");
// ...
});
A: That's because there's no data-detail property on HTML element.
Here is a quick explanation for .data(), .prop() and .attr() :
DOM element is an object which has methods, and properties (from the DOM) and attributes(from the rendered HTML). Some of those properties get their initial value by the attributes id->id, class->className, title->title, style->style etc.
Consider this element: <input type="checkbox" checked data-detail="somedata" >
The result of the following would be:
$('input').prop('id'); // => " "-empty string, property id exist on the element (defined by DOM) , but is not set.
$('input').attr('id');// => undefined - doesn't exist.
If you do the following:
$('input').attr('id',"someID");
$('input').prop('id'); // => "someID"
$('input').attr('id'); // => "someID"
And also:
$('input').prop('id',"someOtherID");
$('input').prop('id');// => "someOtherID"
$('input').attr('id');// => "someOtherID"
So, some attributes and properties have 1:1 mapping. (change of
the attr result change of the prop and vice versa).
Consider the following: <input type="text" data-detail="somedata" value="someValue">
$('input').prop('value'); // => "someValue"
$('input').val(); // => "someValue"
$('input').attr('value'); // => "someValue"
And if you do:
$('input').prop('value','newVal');
// or
$('input').val('newVal');
$('input').prop('value'); // => "newVal" -value of the property
$('input').val(); // => "newVal" -value of the property
$('input').attr('value'); // => "someValue" -value of the attr didn't change, since in this case it is not 1:1 mapping (change of the prop value doesn't reflect to the attribute value).
Case with the .data()
1) How to get:
- Have in mind that attribute name is data-* and property name is dataset, so:
<input type="checkbox" data-detail="somedata" >
$('input')[0].dataset; //=> [object DOMStringMap] { detail: "somedata"}
$('input')[0].dataset.detail; // => "somedata"
$('input').prop('dataset'); //=>[object DOMStringMap] { detail: "somedata"}
$('input').prop('dataset').detail; // => "somedata"
$('input').data('detail'); // => "somedata"
$('input').attr('data-detail'); // => "somedata"
2) How to set:
I) $('input').prop('dataset').detail='newData';
$('input').prop('dataset'); //=> [object DOMStringMap] { detail: "newData"}
$('input').prop('dataset').detail; // => "newData"
$('input').attr('data-detail'); // => "newData"
$('input').data('detail'); // => "newData"
II) $('input').attr('data-detail','newData');
$('input').prop('dataset'); //=> [object DOMStringMap] { detail: "newData"}
$('input').prop('dataset').detail; // => "newData"
$('input').attr('data-detail'); // => "newData"
$('input').data('detail'); // => "newData"
So you can see that here is 1:1 mapping, attr change reflects prop and
vice versa.
But check the third way:
III) $('input').data('detail','newData');
$('input').prop('dataset'); // => [object DOMStringMap] { detail: "somedata"}
$('input').prop('dataset').detail; // => "somedata"
$('input').attr('data-detail'); // => "somedata"
$('input').data('detail'); // => "newData" <-----******
So, what is happening up here?
$(elem).data(key, value) does not change the HTML5 data-* attributes
of the element. It stores its values in $.cache internally.
So for getting data-* you would never go wrong with .data() :
$(".saveBtn").on("click", function() {
var saveBtn = $(this);
var detail = saveBtn.data("detail");
var relevantInput = saveBtn.parent().next();
var value = relevantInput.prop("value");
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36663690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Optional Parameters: "empty" vs "not provided" Is there a way to differentiate between an empty value and one that is not mentioned at all?
For example, I'd like to the client to be able to update a Profile and only affect values which are specified in the request... EVEN empty/null ones.
so given a profile with name="Sherlok" and Birthdate="January 6":
POST api/profiles/update?name=Sherlock >> only modifies name
POST api/profiles/update?birthdate=&name=Sherlock >> modifies name AND clears birthdate
Is there a way to differentiate between the birthdate parameter in those two situations, or do I need to resort to magic values?
A: There are actually quite a few ways to do this.
*
*As @Badri suggested, you can use the Request object directly in your actions. This is a very straightforward and simple approach but mixes controller logic with formatting/binding logic. If you want to create a better separation of concerns, try one of the following.
*There are a number of parameter binding mechanisms you can choose from. Looks to me like a custom model binder could work well in this case. You can access the Request object in the model binder and use something similar to @Badri's code to set up the values you expect (String.Empty or null) before they get passed to your action.
*A value provider for the birthdate field might be a better option. You're passing a string that can ultimately be converted to a DateTime object. If you specify that that parameter should use a custom value provider (such as an IntuitiveDateTimeValueProvider), you can actually change the type of the parameter in your action to DateTime or Nullable<DateTime> (DateTime?) and let the value provider fill the value appropriately. You can also use a similar strategy for simpler strings for which you want to differentiate between empty and null (e.g., ExistenceTestingStringValueProvider).
*Create additional routes/actions. This isn't a good option if there are a lot of parameters because there are just too many possible combinations, but if there are just a few, this is a very simple solution. One way to do this is to simply create method overloads for each combination. If an overload that only has name is hit, it means birthdate wasn't specified, but if an overload with both parameters was hit, it means that birthdate was specified, even if its value is null, giving you a way to distinguish between specified but empty parameter values and unspecified parameter values.
A: If you use ASP.NET Web API binding, it is not possible. Say, you have a DTO class and use it for binding like this.
public class MyDto
{
public string Name { get; set; }
public string BirthDate { get; set; }
}
public void Update([FromUri]MyDto dto) { }
When you leave out BirthDate or have it in the query string with an empty value, it is basically the same and BirthDate property will be null in both cases. However, you can read the query string yourself like this.
string qs = Request.RequestUri.Query.Substring(1); // leave out ?
var pairs = System.Web.HttpUtility.ParseQueryString(qs);
In this case, pairs["BirthDate"] will be null, if you leave out the field from the query string (?name=Sherlock).
If you have it in the query string with an empty value (?birthdate=&name=Sherlock), then pairs["BirthDate"] will be empty string ("").
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22003933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Hide header Tabbed Navigation Page Xamarin/FreshMvvm I'm struggling with hiding the header of my TabbedNavigation Page.
public class NavigationContainerNames
{
public const string AuthenticationContainer = "AuthenticationContainer";
public const string MainContainer = "MainContainer";
}
public partial class App : Xamarin.Forms.Application
{
public App()
{
InitializeComponent();
var maintTabNav = new FreshTabbedFONavigationContainer("Aerogrow", NavigationContainerNames.MainContainer);
maintTabNav.FirstTabbedPage.On<Xamarin.Forms.PlatformConfiguration.Android>().SetToolbarPlacement(ToolbarPlacement.Bottom);
maintTabNav.AddTab<AerogrowPageModel>("Aerogrow", "");
maintTabNav.AddTab<ControlsPageModel>("Controls", "");
maintTabNav.AddTab<AccountPageModel>("Account", "");
var LoginPage = FreshPageModelResolver.ResolvePageModel<RegisterPageModel>();
var LoginNav = new FreshNavigationContainer(LoginPage, NavigationContainerNames.AuthenticationContainer);
if (DataHelpers.DataBaseHelpers.GetCurrentUser() != null)
MainPage = maintTabNav;
else
MainPage = LoginNav;
}
I create my FreshTabbed Navigation Page and add the children in it but there's is a common header in every tab that I can't hide (with "Aerogrow" written).
If someone knows how to hide it please :)
note: I've tried to hide trough XAML but it doesn't work
NavigationPage.HasNavigationBar="false"
A: Hide the first tabbed page's navigation bar via:
var maintTabNav = new FreshTabbedFONavigationContainer("Aerogrow", NavigationContainerNames.MainContainer);
maintTabNav.FirstTabbedPage.On<Xamarin.Forms.PlatformConfiguration.Android>().SetToolbarPlacement(ToolbarPlacement.Bottom);
NavigationPage.SetHasNavigationBar(maintTabNav.FirstTabbedPage, false);
If you don't want to see the navigation bar on each page make your page inherit from a base page. Then set the property in the base page:
public class BasePage : ContentPage
{
public BasePage()
{
NavigationPage.SetHasNavigationBar(this, false);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56266448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Where dependencies and services should register when using Web API and Azure Function under same solution in Clean Architecture I am working on an ASP.NET Core 6.0 Web API solution that is implemented based on Clean Architecture. Further down application using Entity Framework Core 7 in the infrastructure layer. My app dependencies and services are registered in Program.cs of the Web API project.
Now I need a time-triggered Azure Function and I am trying see the best option going forward to register dependencies as it should be in Web API or in the Azure Function?
The Web API and Azure function are in same project/solution. Is that OK from an architecture point of view to repeat dependencies based on services usage under Web API and Azure Function?
Another option I was thinking of: call Web API from Azure Function but then it kills the very purpose of service less?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72394391",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Filter object or array I would like to list all the Ids and roles in a given json but where there is only a single role, rather than an array of 1 it provides it as an object, so if I run "[]?" I get the error Cannot index string with string "Name".
Extract (example.json):
{
"Person": [
{
"Roles": {
"Role": {
"@Id": "1",
"Name": "Job1"
}
}
},
{
"Roles": {
"Role": [
{
"@Id": "2",
"Name": "Job2"
},
{
"@Id": "3",
"Name": "Job3"
}
]
}
}
]
}
I hoped this may work:
jq -r . | '.Roles.Role[]?>.@Id + "," + .Roles.Role[]?>.Name'
This is the output I'd like (so I can pipe to a csv)
1,Job1
2,Job2
3,Job3
A: The following produces the CSV shown below. It would be easy to tweak the program to remove the double-quotation marks, etc.
.Person[]
| .Roles.Role
| if type == "array" then .[] else . end
| [.["@Id"], .Name]
| @csv
Output
"1","Job1"
"2","Job2"
"3","Job3"
Adding the index in .Person
.Person
| range(0; length) as $ix
| .[$ix]
| .Roles.Role
| if type == "array" then .[] else . end
| [$ix, .["@Id"], .Name]
| @csv
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57748823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Setting an analytics custom metric server side I'm using the GTM data layer to populate data through the enhanced ecommerce interface of Analytics. The goal is to provide detailed cost data so I can build a dashboard that shows profitability for my business. It's working great on a transaction basis and I am uploading shipping costs, product costs, discounts, and a host of other transaction data. However, my business also has fixed overhead costs. I want to upload that to analytics once per day so I can see the true profitability on a day by day basis. This requires it to be a server-side request from my PHP server. I am unfamiliar with how to set a custom metric from the server side. Does anyone know how I can send this once-per-day data to analytics from the server side? Would I send it as a pageview event? The variable name would be "fixed overhead". I'm not really sure where to start. Thanks in advance!
A: Sending data server-side to Google Analytics is entirely possible (and admittedly it is pretty daunting if you've not done it before).
The two best resources to use are the Google Analytics Measurement Protocol documentation and the Google Analytics Hit Builder. Use the parameter guide to prep the custom metric data specifically.
Here is my actual snippet that I use for all of my PHP projects (first ~150 lines or so). I'm certain there are better ways to do it, but at the very least it might help you figure out some of the complexities.
It's a lot of info to soak in, but I hope that gets you headed in the right direction!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34387501",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to call a deriving class operator()? I want create an expression structure, to calculate value (by calling operator().
expr - base expression class, it should work like result = expression(100500).
const_value - struct returns constant value.
argument - returns it's argument (== function id).
e_add, prod, sub, ... - different functions.
Why code calls base class operator(), but ignore derived structires?
output:
EXPR::operator() called
EXPR::operator() called
201000
const_value 1 called arg = 100
1
Full source code:
#include <iostream>
#include <cmath>
using namespace std;
struct expr {
virtual double operator()(double) {
cerr << "EXPR::operator() called\n";
return 100500;
};
};
struct const_value : public expr {
double _value;
const_value (double value = 0): _value(value) {};
double operator()(double arg = 0) override {
cout << "const_value " << _value << " called arg = " << arg << '\n';
return _value;
};
};
#define make_bin_op(_op_name, _op) struct e_##_op_name : public expr { \
expr _left; \
expr _right; \
e_##_op_name(expr left, expr right): _left(left), _right(right) {}; \
double operator()(double arg) override { \
return _left(arg) _op _right(arg); \
}; \
}
make_bin_op(add, +);
#undef make_bin_op
int main()
{
const_value c1{1};
e_add e{c1, c1};
cout << e(100) << endl;
cout << c1(100) << endl;
return 0;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50328197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Deleting everything after a pattern in Unix I have a string replenishment_category string,Date string, I want to delete everything starting with Date (including it), also the comma before it if it is present.
I have the string to be replaced stored in a variable:
PARTITION_COLUMN='Date'
I tried sed to replace everything after the variable PARTITION_COLUMN
echo "replenishment_category string,Date string" | sed "s/"$PARTITION_COLUMN".* //g"
but the output still has the string that follows the date:
replenishment_category string,string
How do I remove the string part and also the comma preceding the Date?
A: Try this:
echo "replenishment_category string,Date string" | sed "s/$PARTITION_COLUMN.*//"
Notice the space removed after .* and the double quote around the entire command.
A: Since you want to remove variable as well as comma before it so following sed may help you here.
echo "replenishment_category string,Date string" | sed "s/,$PARTITION_COLUMN.*//g"
A: sed would obviously work here:
echo "replenishment_category string,Date string" | sed "s/\b,$PARTITION_COLUMN.*//"
Output:
replenishment_category string
A: You could do this with shell parameter expansion alone, assuming you have extended globs enabled (shopt -s extglob):
$ var='replenishment_category string,Date string'
$ part_column=Date
$ echo "${var%%?(,)"$part_column"*}"
replenishment_category string
*
*The ${word%%pattern} expansion works without extended globs and removes the longest match of pattern from the end of $word.
*The ?(pattern) extended pattern matches zero or one occurrences of pattern and is used to remove the comma if present.
*"$part_column"* matches any string that begins with the expansion of $part_column. Quoting it is not required in the example, but good practice to prevent glob characters from expanding.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50584292",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: What is the security flaw in this authentification process over unsecure HTTP? First question here :)
I've been reading many questions about how to secure login on sites without https. They are all very interesting and most answers boil down to "Use SSL if you care about security!". I agree with this, yet I also wonder, what is the flaw in this particular procedure (one user(=me), no sessions: the password is always sent with the complete content of the <html> tag, which replaces the current contents of that file.):
*
*Server sends two variables to page: random token A and B=derivedfrom(A).
*client sends back md5(password+timestamp+B) and A.
*Server derives B from A to perform the same md5hash as client and matches hashes of server and client.
*Server allows no more than 1 request per second per IP address.
Assuming the attacker knows all valid pairs of A and B, is there any way for him/her to authenticate succesfully apart from replay attacks (during a 100ms timeframe that the hash is valid) and pure luck that he guesses the right hash for this particular timeframe?
Of course, the attacker could still try all possible passwords, but that doesn't change by using https.
I'm not suggesting this is a useful strategy for sites that cannot use https, just wondering if there is a theoretical flaw that I didn't think of.
How would you force your way in if the site has no traffic at the moment?
A: There are several flaws here:
*
*You should not use md5. Please use some other hashing algorithm (e.g. sha256)
*In order to do what you are saying, the server needs to store the passwords in plaintext. This is a very bad practise, as if you get hacked, all the passwords will be compromised. Instead, you should store a salted hash of the password. More info here: https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet
*This method is infeasible, as the timestamp cannot be possibly known by the server, except if the clock of the client and the server are synchronised to the millisecond (don't assume that they will be). Even if the clocks are completely synced, this will still not work. The time from when the client takes the timestamp until the packet reaches the server is variable, and the server would need to know exactly that time. Without the correct timestamp, the server won't be able to calculate the hash. Removing the timestamp will lead to replay attacks.
*An attacker performing a man-in-the-middle attack can alter the HTML (or whatever) code on the fly and remove the hashing function (assuming it's performed in JavaScript). The browser will then transmit the password in clear. Of course the authentication will fail, but the attacker will have the password.
*Probably other flaws also exist, but these are enough for the method to be inefficient I believe.
Bottom line: Do not use HTTP for user authentication. I have not heard of any cases of secure authentication over HTTP. If SSL is very expensive, you can use it only for the login page. It is still a very bad practise, as an attacker can perform session hijacking by stealing session cookies (and other man-in-the-middle attacks), but at least the password will not be revealed this way.
A: What you describe is a minor technical detail in a larger procedure, which you do not go into detail at all. I'm assuming that the larger purpose of that procedure is to log in? Then what happens after this token is exchanged? Does the user receive some sort of permanent token like a cookie? Then this is susceptible to:
*
*man in the middle attacks reading all communication
*local network packet sniffing, famously publicised by the Firesheep attack
Even if (that's a large if) this particular token scheme were flawless, the entire communication chain is observable by third parties and all private data (including identifying cookies) can be read in the clear by unauthorised users in a privileged network position (→ session hijacking).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42000143",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: unable to compile Maven project after switching to ADT I've switched from Eclipse Indigo to ADT (version 22.3.0)
I compile a project using Maven through command line:
mvn clean install android:deploy android:run
The project compiled fine on my older system and I haven't changed it at all. Now when I import it to ADT I get the "already added" error during compilation:
...
[INFO] UNEXPECTED TOP-LEVEL EXCEPTION:
[INFO] java.lang.IllegalArgumentException: already added: Lcom/sun/activation/registries/LineTokenizer;
[INFO] at com.android.dx.dex.file.ClassDefsSection.add(ClassDefsSection.java:123)
[INFO] at com.android.dx.dex.file.DexFile.add(DexFile.java:163)
[INFO] at com.android.dx.command.dexer.Main.processClass(Main.java:490)
[INFO] at com.android.dx.command.dexer.Main.processFileBytes(Main.java:459)
[INFO] at com.android.dx.command.dexer.Main.access$400(Main.java:67)
[INFO] at com.android.dx.command.dexer.Main$1.processFileBytes(Main.java:398)
[INFO] at com.android.dx.cf.direct.ClassPathOpener.processArchive(ClassPathOpener.java:245)
[INFO] at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:131)
[INFO] at com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpener.java:109)
[INFO] at com.android.dx.command.dexer.Main.processOne(Main.java:422)
[INFO] at com.android.dx.command.dexer.Main.processAllFiles(Main.java:333)
[INFO] at com.android.dx.command.dexer.Main.run(Main.java:209)
[INFO] at com.android.dx.command.dexer.Main.main(Main.java:174)
[INFO] at com.android.dx.command.Main.main(Main.java:91)
[INFO] 1 error; aborting
...
I don't have X_src files I saw on other replies to this issue. I don't include any library in my lib folder either.
This happens even with basic POM file so I guess that ADT has changed the project somehow so it includes this LineTokenizer twice (I'm not including it anywhere), is this correct?
Does anyone know how to fix this, or to find where the multiple inclusions happen?
Edit:
the POM:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>my.package</groupId>
<artifactId>android-client</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>apk</packaging>
<name>Name</name>
<dependencies>
<dependency>
<groupId>com.google.android.services</groupId>
<artifactId>google-play-services</artifactId>
<version>1</version>
</dependency>
<dependency>
<groupId>com.google.android.support</groupId>
<artifactId>android-support-v4</artifactId>
<version>4</version>
</dependency>
<dependency>
<groupId>com.google.android</groupId>
<artifactId>android</artifactId>
<version>4.1.1.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.android.analytics</groupId>
<artifactId>analytics</artifactId>
<version>3</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>oauth.signpost</groupId>
<artifactId>signpost-core</artifactId>
<version>1.2.1.1</version>
</dependency>
<dependency>
<groupId>oauth.signpost</groupId>
<artifactId>signpost-commonshttp4</artifactId>
<version>1.2.1.1</version>
</dependency>
<dependency>
<groupId>com.facebook.android</groupId>
<artifactId>facebook-android-sdk</artifactId>
<version>3.5.2</version>
<type>apklib</type>
</dependency>
<dependency>
<groupId>com.flurry</groupId>
<artifactId>FlurryAgent</artifactId>
<version>3.2.2</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<sourceDirectory>src</sourceDirectory>
<pluginManagement>
<plugins>
<plugin>
<groupId>com.jayway.maven.plugins.android.generation2</groupId>
<artifactId>android-maven-plugin</artifactId>
<version>3.6.0</version>
<extensions>true</extensions>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>com.jayway.maven.plugins.android.generation2</groupId>
<artifactId>android-maven-plugin</artifactId>
<configuration>
<sdk>
<platform>11</platform>
</sdk>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
</plugin>
</plugins>
</build>
</project>
A: The ADT will throw that error if its finds more than one instance of the same package but with different version number to them. Looking at your pom one of your dependencies is adding the LineTokenizer which is not up-to-date in comparison to the one supplied by the compiler. I would suggest you go to the Dependency Hierarchy using the maven POM Editor. This will allow you to select the extraneous dependency, which you can then exclude by right-clicking and selecting "Exclude Maven Artifact..." which will automatically add an <exclusions> element to your POM. This will remove the duplicate JAR from your Eclipse classpath and allow you to build you project. Do a mvn clean install after you done editing the POM though.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20859029",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java HttpURLConnection only works on certain sites package internet;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class internet {
public static void main(String[] args) {
try {
URL url = new URL("http://www.wikipedia.org");
HttpURLConnection hc = (HttpURLConnection) url.openConnection();
int length = hc.getContentLength();
System.out.println(length);
InputStream input = url.openStream();
byte[] binput = new byte[100000];
input.read(binput);
input.close();
final String result = new String(binput);
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
A strange thing happened. I can't get display the result and the length is -1. But when i use other url. For example, http://www.edwinlengzai.com. It works. Any Idea?
A: Can you try in this way? address should be set as the site you want to read
URL page = new URL(address);
StringBuffer text = new StringBuffer();
HttpURLConnection conn = (HttpURLConnection) page.openConnection();
conn.connect();
InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());
BufferedReader buff = new BufferedReader(in);
box.setText("Getting data ...");
String line;
do {
line = buff.readLine();
text.append(line + "\n");
} while (line != null);
final String result = new String(text.toString());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32124955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: HTML/JS) To display timestamp list of video (capture video image at specific timestamp) I am working on html/javascript.
I want make thumbnail image list of specific timestamp in uploaded video.
I found a following code, which captures current image of video.
function captureVideo(video) {
var canvas = document.createElement("canvas");
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
var canvasContext = canvas.getContext("2d");
canvasContext.drawImage(video, 0, 0);
return canvas.toDataURL('image/png');
}
by using this, i wrote a following code.
<input id="vidImgButton" type="button" value="Set timestamp images" >
<img id = "timestamp01" width = "160" height="120">
<img id = "timestamp02" width = "160" height="120">
<img id = "timestamp03" width = "160" height="120">
...
<script>
...
vidImgButton.addEventListener("click", ()=>{ // click to set image list describing video.
timestamp01.setAttribute("src", captureVideoTime(uploadedVideo,1)) // captures image at 1s
timestamp02.setAttribute("src", captureVideoTime(uploadedVideo,4))
timestamp03.setAttribute("src", captureVideoTime(uploadedVideo,7)) // captures image at 7s
})
...
function captureVideoTime(video, time) {
var canvas = document.createElement("canvas");
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
var canvasContext = canvas.getContext("2d");
video.currentTime = time; //
canvasContext.drawImage(video, 0, 0);
return canvas.toDataURL('image/png');
}
Instead of capturing video image at (1s, 4s, 7s), this code captures video image at current time.
In other words, the result of this modified code does not changed at all.
Maybe code 'video.currentTime = time' executes after the event ends, and that is why this code does not works? I have no idea.
What should I do?
Please share your knowledge. Thank you.
I tried solution at following link and had no favoroble result as well : Capturing an image for a specific time, within a HTML5 video
Tried unbinding seeked event, pasted 'createPoster' function at link, took snaps on timeupdate event,
Tried following code, it works but well.... I wonder if there's more clever solution
timestamp01.addEventListener("click", ()=>{
videoInput.currentTime = timestamp[0];
uploadedVideo.addEventListener('seeked', ()=>{
timestamp01.setAttribute("src", captureVideo(uploadedVideo))
}, {once:true})
})
timestamp02.addEventListener("click", ()=>{
videoInput.currentTime = timestamp[1];
uploadedVideo.addEventListener('seeked', ()=>{
timestamp02.setAttribute("src", captureVideo(uploadedVideo))
}, {once:true})
})
timestamp03.addEventListener("click", ()=>{
videoInput.currentTime = timestamp[2];
uploadedVideo.addEventListener('seeked', ()=>{
timestamp03.setAttribute("src", captureVideo(uploadedVideo))
}, {once:true})
})
A: I would rather carry out this from serverside because it cannot be done only by targeting in clientside (images's), as it will become heavylifting from the front end.
Client Side Method:
<video id="video" controls>
<source src="your-video-file.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<canvas id="canvas"></canvas>
<script>
const video = document.getElementById("video");
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
video.addEventListener("loadedmetadata", function() {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
}
Example :
When a user sees a video on YouTube, the site's servers send these thumbnails, which are saved as JPEG files. The thumbnail of a video will grow and begin playing a preview when a user hovers over it in the search results or on the watch page, giving them a clearer understanding of what the video is about.
<img id="thumbnail" src="your-thumbnail-image.jpg">
<script>
const thumbnail = document.getElementById("thumbnail");
// Modify the thumbnail's properties, such as its width and height
thumbnail.width = 150;
thumbnail.height = 100;
// Add an event listener to handle user interactions
thumbnail.addEventListener("click", function() {
// Perform some action, such as playing the video
});
</script>
A: I found a solution on my own, thanks to my colleague.
This problem seems to occur because rendering engine's performance is forced to be limited (not sure though).
To solve this, use setTimeout() function to make it sequential.
For those who are having simmilar problem, I hope this codes helps.
function initialImg(){
setTimeout(function(){
uploadedVideo.currentTime = timestamp[0];
document.getElementById('img_scene00').setAttribute("src", captureVideo(uploadedVideo));
setTimeout(function(){
uploadedVideo.currentTime = timestamp[1];
document.getElementById('img_scene01').setAttribute("src", captureVideo(uploadedVideo));
setTimeout(function(){
uploadedVideo.currentTime = timestamp[2];
document.getElementById('img_scene02').setAttribute("src", captureVideo(uploadedVideo));
setTimeout(function(){
uploadedVideo.currentTime = timestamp[3];
document.getElementById('img_scene03').setAttribute("src", captureVideo(uploadedVideo));
setTimeout(function(){
uploadedVideo.currentTime = timestamp[4];
document.getElementById('img_scene04').setAttribute("src", captureVideo(uploadedVideo));
}, 0);
}, 0);
}, 0);
}, 0);
}, 0);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74858203",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Retrieving data set using jQuery.data() I set some data to a div on the first click using jQuery.data().On the second click, when I try to retrieve it, it gives me 'undefined'. Any idea where I am wrong?
Please see jsFiddle
<div class="player forward playerposition">
<input type="button" class="addplayer addforward" value="+" />
</div>
$(document).ready(function () {
$(document).on('click', '.addplayer', storeData);
$(document).on('click', '.removeplayer', deletedata);
});
function storeData() {
var div = $(this);
$.data(div, 'testdata', {
'Name': 'Ronaldo'
});
var data = $.data(div, 'testdata');
console.log(data);
div.val('x');
div.removeClass('addplayer');
div.addClass('removeplayer');
}
function deletedata() {
var div = $(this);
var data = $.data(div, 'testdata');
console.log(data);
div.removeData(div, 'testdata');
div.val('+');
div.removeClass('removeplayer');
div.addClass('addplayer');
}
A: The jQuery.data() api expects a dom element as its first param, not a jQuery object
var data = $.data(this, 'testdata');
Also removeData() expects the key to be removed as its first param
div.removeData('testdata');
Demo: Fiddle
Another way is to use the .data() method of the jQuery object like
div.data('testdata', {
'Name': 'Ronaldo'
});
var data = div.data('testdata');
Demo: Fiddle
A: JQuery
$(document).ready(function () {
$(document).on('click', '#btn',function(){
var thisObject=$(this);
if(thisObject.hasClass("addplayer"))
{
$.data( thisObject[0], "testdata", {
Name: "Ronaldo"
});
var dataName = $.data(thisObject[0], 'testdata').Name;
console.log(dataName);
thisObject.val('x').removeClass('addplayer').addClass('removeplayer');
}
else
{
var dataName = $.data(thisObject[0], 'testdata').Name;
console.log(dataName);
$.removeData(thisObject[0], 'testdata');
thisObject.val('+').removeClass('removeplayer').addClass('addplayer');
}
});
});
DEMO
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25841219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why an entry of pure virtual function in virtual table is required My understanding regarding virtual table is , whenever compiler find virtual function in a class it creates a virtual table for the class and all the function pointer for virtual function will be placed in that table.
But when it comes to pure virtual function we are not going to call that function in any point of time. So why that entry of pure virtual function is required in the virtual table.
virtual void myFunction() = 0 ;
A: The declaration is required because you need to tell the compiler to reserve a slot in the vtable for that specific method starting from the base class in which it is declared (which is the type you could want to use when calling a method on a derived class)
Just to give you the idea let's make an example (which is not to be considered exactly what happens under the hood). Let's suppose you have three virtual methods in Base, one of which is pure,
class Base {
virtual void pure() = 0;
virtual void nonpure() { }
virtual void nonpure2() { }
};
so the Base vtable will look like
0 [ pure ] -> nothing
1 [ nonpure ] -> address of Base::nonpure
2 [ nonpure2] -> address of Base::nonpure2
now let's derive it with
class Derive : public Base {
virtual pure() override { }
virtual nonpure2() override { }
};
Derived vtable will look like
0 [ pure ] -> address of Derived::pure
1 [ nonpure ] -> address of Base::nonpure
2 [ nonpure2 ] -> address of Derived::nonpure2
When you then try to do
Base* derived = new Derived();
derived->pure();
The method is roughly compiled as
address = derived->vtable[0];
call address
If you don't declare the pure virtual method in the Base class there is no way to know its index in the vtable (0) in this case at compile time since the method is not present at all.
But, if the vtable has 'a hole' in it (an implementation is missing), you can't instantiate that specific class type.
A: You cannot instantiate an object of an abstract class. Which actually makes your question kinda meaningless: since you will never instantiate your abstract class, the virtual table for that class is not needed at all. (In reality it might be needed temporarily during construction/destruction, but this is a different story.)
When you actually instantiate an object, it is an object of some derived class, which is no longer abstract. It does not have any pure virtual functions anymore. The derived class that you actually instantiate has all pure virtual functions overridden by that time. This is why an entry is needed in the virtual method table - to store a pointer to the actual overrider function.
Later in your code, you might call myFunction() through a pointer to that abstract base class
MyAbstractBaseClass *ptr = some_function();
// Pointer actually points to some non-abstract derived object
ptr->myFunction();
The compiler will generate code that will go into the virtual method table associated with *ptr object, extract the pointer entry that corresponds to myFunction() and pass the control trough that pointer. As I said above, that pointer will actually point to an overriding function from some derived class. This is exactly what that entry was reserved for.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31307723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Custom button field in blackberry I am using a custom ButtonField in my application. I have used the code from the "Blackberry Custom Button Field" blog post on Coderholic to create a custom button in my app.
Now I want to set the editable property to false for this custom button.
How do I do the equivalent of button.setEditable(false) for this custom button?
mybuttonid.setEditable(false) is not working.
A: Override Field.setEditable(boolean editable) to track your own custom editable boolean:
private boolean customEditable = true;
public void setEditable(boolean editable) {
super.setEditable(editable);
customEditable = editable;
// invalidate(); forces paint(Graphics graphics) to be called
}
Override navigationClick(int status, int time) to use that boolean to detect whether to react on click events:
protected boolean navigationClick(int status, int time) {
if (customEditable) fieldChangeNotify(1);
return true;
}
If you need a custom visual appearance for disabled state, then also override paint(Graphics graphics) to use another color. In this case you'll also need to call invalidate() from the setEditable().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7697187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: get/set value of the ACF field by ACF JavaScript API, in a custom block, on the post editing page I made a custom gutenberg block using the AdvancedCustomFields PRO plugin. This block has a gallery field. I need to make a button that fills the gallery field with certain photos. I render button using a new custom field type, but how to change the value of another field in the same block?
Function acf.findFields (args) in the ACF JavaScript API works well with fields that are attached to the page, but how I can access the field in a specific custom block?
A: I found solution
Append this script to admin panel
This code adds a button for the ACF gallery field that fill the gallery with a predefined data.
(function($){
setInterval(function() {
let fields = acf.getFields({type:"gallery"});
for (let field of fields) {
if (!field.dasupdated) {
field.dasupdated = true;
let control = $("<div><button class='button'>Append Attachment</button></div>");
control.find("button").click(()=>{
field.appendAttachment({attributes:{
id: 56060,
url: "http://site.url/image.jpg"
}});
});
$(field.$el[0]).find(".acf-gallery-main .acf-gallery-toolbar").append(control);
}
}
}, 1000);
})(jQuery);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70347817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Cronjob is not working for laravel (linux server) I've tested the cronjob in local which is working fine. But it is not working in server. Any help is appreciated. Thanks in advance.
"sudo systemctl status cron" command gives following outputs:
cron.service - Regular background program processing daemon
Loaded: loaded (/lib/systemd/system/cron.service; enabled; vendor preset: enabled)
Active: active (running) since Tue 2022-07-19 21:40:44 CST; 27min ago
Docs: man:cron(8)
Main PID: 511 (cron)
Tasks: 1 (limit: 2315)
Memory: 1.9M
CGroup: /system.slice/cron.service
└─511 /usr/sbin/cron -f
Jul 19 22:05:01 iZa2d4o64ljp79h0v3i5fvZ CRON[2292]: pam_unix(cron:session): session closed for user userr
Jul 19 22:06:01 iZa2d4o64ljp79h0v3i5fvZ CRON[2313]: pam_unix(cron:session): session opened for user userr by (uid=0)
Jul 19 22:06:01 iZa2d4o64ljp79h0v3i5fvZ CRON[2314]: (userr) CMD ( cd /var/www/abc.com.np/myproject/app/Console/Kernel.php && php artisan schedule:run >> /dev/null 2>>
Jul 19 22:06:01 iZa2d4o64ljp79h0v3i5fvZ CRON[2313]: pam_unix(cron:session): session closed for user userr
Jul 19 22:07:01 iZa2d4o64ljp79h0v3i5fvZ CRON[2333]: pam_unix(cron:session): session opened for user userr by (uid=0)
Jul 19 22:07:01 iZa2d4o64ljp79h0v3i5fvZ CRON[2334]: (userr) CMD ( cd /var/www/abc.com.np/myproject/app/Console/Kernel.php && php artisan schedule:run >> /dev/null 2>>
Jul 19 22:07:01 iZa2d4o64ljp79h0v3i5fvZ CRON[2333]: pam_unix(cron:session): session closed for user userr
Jul 19 22:08:01 iZa2d4o64ljp79h0v3i5fvZ CRON[2353]: pam_unix(cron:session): session opened for user userr by (uid=0)
Jul 19 22:08:01 iZa2d4o64ljp79h0v3i5fvZ CRON[2354]: (userr) CMD ( cd /var/www/abc.com.np/myproject/app/Console/Kernel.php && php artisan schedule:run >> /dev/null 2>>
Jul 19 22:08:01 iZa2d4o64ljp79h0v3i5fvZ CRON[2353]: pam_unix(cron:session): session closed for user userr
crontab (/etc/crontab)
# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.
MAILTO=""
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
17 * * * * root cd / && run-parts --report /etc/cron.hourly
25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
* * * * * userr cd /var/www/abc.com.np/myproject/app/Console/Kernel.php && php artisan schedule:run >> /dev/null 2>&1
#
Kernel.php in laravel project
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Illuminate\Support\Facades\DB;
class Kernel extends ConsoleKernel
{
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->call(function () {
//z; here if I remove the comment, the error should be shown in storage/log/laravel.log. It works locally but no error is seen in server
DB::table('recent_users')->delete();
})->everyMinute();
}
}
Test: here if I've uncommented "//z" inside $schedule->call(), the error should be shown in storage/log/laravel.log if cronjob is working but it does not. It works locally but no error is seen in server
Update: I removed the cd
*
*
*
*
*
*
*
*
*
*/var/www/abc.com.np/myproject/app/Console/Kernel.php && php artisan schedule:run >> /dev/null 2>&1
the error I got is following:
/var/www/abc.com.np/myproject/app/Console/Kernel.php: 1: cannot open ?php: No such file
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73063779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Trying to resize image to fit full screen when resized to a smaller screen and whitespace issue So far,I've got the images to stack on top of each other in block elements and arranged a paragraph next to it as description. What I want it to be like is that when I resize the screen to a smaller screen, the images shrink until it hits its min-width and fits the view port, however with my current code, the images do not do so and when the paragraph div goes underneath images, it leaves a lot of white space :( Any tips?
article{
width:70%;
background:yellow;
margin:0 auto;
}
#image{
max-width:48%;
float:left;
min-width:400px;
}
#image img {
display:inline-block;
max-width: 100%;
height:auto;
min-width:320px;
float:left;
}
#words{
float:left;
max-width:48%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<article>
<div id="main">
<div id="image">
<img src="mono.png">
<img src="prairie.png">
<img src="night.png">
</div>
<div id="words">
<h1>HELLO WORLD!</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Placerat in egestas erat imperdiet sed euismod nisi. Risus nec feugiat in fermentum posuere urna nec tincidunt praesent. At auctor urna nunc id cursus metus aliquam eleifend. Aliquam sem fringilla ut morbi tincidunt augue interdum. Sed libero enim sed faucibus turpis in eu mi. Erat nam at lectus urna. Eget dolor morbi non arcu risus. Tempus egestas sed sed risus. Vel turpis nunc eget lorem. Faucibus purus in massa tempor nec feugiat nisl pretium fusce. Leo in vitae turpis massa sed. Consectetur lorem donec massa sapien faucibus et molestie.
Varius vel pharetra vel turpis nunc eget lorem dolor sed. Ullamcorper dignissim cras tincidunt lobortis. Mus mauris vitae ultricies leo integer. Turpis cursus in hac habitasse platea. Volutpat diam ut venenatis tellus in. Tellus integer feugiat scelerisque varius. Vitae congue mauris rhoncus aenean vel. Tempor nec feugiat nisl pretium fusce id velit. Diam ut venenatis tellus in metus vulputate. Viverra ipsum nunc aliquet bibendum enim. Eu scelerisque felis imperdiet proin fermentum.
In hac habitasse platea dictumst vestibulum rhoncus est pellentesque. Posuere ac ut consequat semper. Pellentesque elit eget gravida cum sociis. Turpis massa sed elementum tempus. In hac habitasse platea dictumst vestibulum rhoncus est pellentesque elit. Volutpat blandit aliquam etiam erat velit scelerisque. Facilisis gravida neque convallis a cras semper auctor. Ac tincidunt vitae semper quis. Velit egestas dui id ornare arcu odio ut sem. Praesent semper feugiat nibh sed pulvinar proin gravida. Elit at imperdiet dui accumsan sit amet nulla. Mauris sit amet massa vitae tortor condimentum lacinia.
Quam vulputate dignissim suspendisse in est ante in nibh mauris. Volutpat blandit aliquam etiam erat. Eleifend quam adipiscing vitae proin sagittis. Facilisis mauris sit amet massa vitae tortor condimentum lacinia. Phasellus egestas tellus rutrum tellus pellentesque eu. Lacinia quis vel eros donec ac odio tempor orci dapibus. Eu scelerisque felis imperdiet proin fermentum leo vel orci. A diam sollicitudin tempor id eu nisl nunc mi ipsum. Hac habitasse platea dictumst quisque sagittis purus sit amet. Lacus laoreet non curabitur gravida. Massa id neque aliquam vestibulum morbi blandit cursus. Malesuada proin libero nunc consequat interdum varius sit. Aliquam eleifend mi in nulla posuere sollicitudin. Morbi tristique senectus et netus et malesuada fames ac. At elementum eu facilisis sed odio morbi quis commodo odio. Vitae tortor condimentum lacinia quis vel eros. A iaculis at erat pellentesque adipiscing commodo elit at.
Erat imperdiet sed euismod nisi porta. Facilisi cras fermentum odio eu feugiat. Nisl purus in mollis nunc sed id semper risus in. Egestas erat imperdiet sed euismod nisi porta lorem mollis. Bibendum est ultricies integer quis auctor elit. Congue mauris rhoncus aenean vel elit scelerisque mauris pellentesque. Tempor nec feugiat nisl pretium. Dictum fusce ut placerat orci nulla pellentesque dignissim enim sit. Maecenas pharetra convallis posuere morbi leo. Tellus id interdum velit laoreet id donec ultrices tincidunt arcu. Sapien eget mi proin sed. Mattis molestie a iaculis at erat.</p>
</div>
</div>
</article>
</body>
</html>
A: Either you can use frameworks like bootstrap and include the images inside grid view. or you can manually to adjust the width of image
@media screen and (min-width: 400px) {
img{
//adjust the width - eg 40%
}
}
@media screen and (min-width: 800px) {
img{
//adjust the width - eg 80%
}
}
A: You need to use media query when the paragraph moves down on next line make an css media query breakpoint at that point and add width of image as 100%.
|
{
"language": "la",
"url": "https://stackoverflow.com/questions/49254614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: What is the best approach to centralzing error messages in an application? All throughout an application wherever error messages (or other user messages) are used I typically hard-code a string. Obviosly this can be really bad (especially when you may have to come back and localize an app). What is the best approach to centralize these strings? A static class? Constants? An XML File? Or a combination (like creating a static class with constants that are used to read from an xml file).
A: Create the strings in a resource file. You can then localise by adding additional resource files.
Check out http://geekswithblogs.net/dotNETPlayground/archive/2007/11/09/116726.aspx
A: Use string resources.
A: I've always defined constants wherever they make the most sense based on your language (a static class? application-wide controller? resource file?) and just call them where/whenever needed. Sure they're still "hard-coded" in a way at that point, but they're also nicely centralized, with naming conventions that make sense.
A: Create a Resource (.resx) file and add your strings there. VS will generate a class for you for easy access to these resources with full intellisence. You can then add localised resources in the same manner.
A: .net has a pretty good support for so-called ressource-files where you can store all strings for one language.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Disabling some code completely in standard c++? Trying to understand what the best way to disable code parts currently is with all the fancy features we have in C++ nowadays.
My test implementations are as follows.
1) Using static if (c++17 and newer):
inline constexpr bool LogEnabled = false; // this would come from, say, Makefile
struct logger
{
static logger &instance()
{
static logger lg;
return lg;
}
inline void log(std::string_view msg)
{
if constexpr (LogEnabled)
{
cout << msg << endl;
}
}
};
2) Using template specialization (fine for c++98 i believe):
inline constexpr bool LogEnabled = false;
struct logger
{
static logger &instance()
{
static logger lg;
return lg;
}
template <bool Enable = LogEnabled>
inline void log(std::string_view msg)
{
// nop version
}
template <>
inline void log<true>(std::string_view msg)
{
cout << msg << endl;
}
};
3) I had an idea to use SFINAE with std::enable_if but could not quite get it to work.
Here is the call site requirement:
int main()
{
logger::instance().log("bruh");
return 0;
}
So what happens if you compile both versions with -O3 -std=c++17 is that the optimizer completely removes generated code for the whole log line in main leaving main look like this:
main: # @main
xor eax, eax
ret
This is great. Both versions do exactly what we want and completely remove the code. But this only happens if the optimization flag is used. If we have -O0 then the call to logger remains even tho it's a nop in both cases.
Is there a better way to do this in clean C++ (please no preprocessor from all the way back to the 90s). Something that would not need the optimizer to do work. Maybe SFINAE could do that better? Can anyone please show an example of a SFINAE version of this?
Thank you!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59437654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Selecting Table TD without TR I have a html Table like this:
<table>
<tr onClick="someFunc();">
<td>Foo</td>
<td><button onClick="anotherFunc();">Bar</button></td>
</tr>
</table>
and Javascript:
function somefunc(){
alert("Foo");
}
function anotherfunc(){
alert("Bar");
}
The problem is when I click on tr works fine but when I press on the button inside TD it fires both functions so I want when I click on the button to just fire the button function.
A: For starters, do not use inline handler with jQuery. That separates the handler from the registration for no good reason and leads to maintenance problems. Use classes or IDs to match the elements and use jQuery handlers.
The problem is event propagation. To stop the click propagating use e.stopPropagation() in the handler:
<table>
<tr class="doSomeFunc">
<td>Foo</td>
<td><button class="doAnotherFunc">Bar</button></td>
</tr>
</table>
$('.doSomeFunc').click(function(e){
alert("Foo");
});
$('.doAnotherFunc').click(function(e){
e.stopPropagation();
alert("Bar");
});
If you want to stick with your existing non-jQuery code, just change this:
<button onClick="anotherFunc();return false;">
return false from a mouse handler will do the same as e.stopPropagation() and e.preventDefault().
A: Your click action is being propagated to all parent elements of the button. To stop that, use event.cancelBubble = true (or, if you're using jQuery you can use event.stopPropagation()) in the click event.
A: You need to use e.stopPropagation();
Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event https://api.jquery.com/event.stoppropagation/
Here is a demo: https://jsfiddle.net/j81czwky/
$("tr").click(function(e){
alert("Foo");
})
$("button").click(function(e){
e.stopPropagation();
alert("Bar");
});
<table>
<tr>
<td>Foo</td>
<td><button>Bar</button></td>
</tr>
</table>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29651854",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I pass data from one component to another for edit form? Currently, I have a modal material dialog window that asks the user to input a number and then hit search. On search, it fetches data from api call and gets back a response object. I want to use the response object to populate a new page (edit form).
My question is, how can I past the data, particularly the number the user entered on the material dialog component to another component, so that it can fetch the api call results or how can I pass my response object to my edit from from dialog?
E.g.
Here's my search function:
search(searchNumber) {
if (this.selectedOption === 'Bill Number') {
this._transactionService.findExistingTransactionByBillNumber('U001', searchNumber)
.subscribe(data => this.transactionResponse = data);
console.log(JSON.stringify(this.transactionResponse));
this.router.navigate(['/edit-transaction-portal']);
} else {
this._transactionService.findExistingTransactionByTransactionNumber('U001', searchNumber)
.subscribe(data => this.transactionResponse = data);
console.log(JSON.stringify(this.transactionResponse));
this.router.navigate(['/edit-transaction-portal']);
}
}
I want to be able to either 1) pass the response object I get here or pass the searchNumber the user entered, so that I can do a lookup within my edit form component. I need to pass in either one from this component to my new component that I navigate to.
EDIT: Accepted solution shows how to add query params to this.router.navigate() and how to retrieve it by subscribing to activateRoute, a different approach than the one identified in the other SO post.
A: You can pass the number (bill/transaction)
this.router.navigate(['/edit-transaction-portal'], { queryParams: { bill: 'U001' } });
this.router.navigate(['/edit-transaction-portal'], { queryParams: { transaction: 'U001' } });
then in your component(edit-transaction-portal) hit the api to get the data. In component you should include ActivatedRoute in constructor. It will be something like:
isBill: boolean;
isTransaction: boolean;
number: string;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.sub = this.route
.queryParams
.subscribe(params => {
this.isBill = params['bill'] != undefined;
this.isTransaction = params['transaction'] != undefined;
this.number = this.isBill ? params['bill'] : params['transaction'];
// Call API here
});
}
A:
My question is, how can I past the data, particularly the number the
user entered on the material dialog component to another component
You can pass it throw material dialog component. Inject dialogRef to you component which opened in the dialog:
constructor(
public dialogRef: MatDialogRef<SomeComponent>,
@Inject(MAT_DIALOG_DATA) public data: any,
) { }
After the submitting data, you can pass any data to component which opened this dialog, by closing the dialog:
onSubmit() {
this.service.postProduct(this.contract, this.product)
.subscribe(resp => {
this.dialogRef.close(resp);
});
}
And in your Parent component, who opened this dialog can get this passed data by subscribing to afterClosed() observable:
Parent.component.ts:
openDialog(id) {
const dialogRef = this.dialog.open(SomeComponent, {
data: { id: anyData}
});
dialogRef.afterClosed().subscribe(result => {
if (result) {
// do something...
}
});
}
Would I pass the data object in dialog.open()? How would I retrieve it
from there?
Look at openDialog() above. It has data property, that you can send to dialog components. And in the opened component inject MAT_DIALOG_DATA as this:
@Inject(MAT_DIALOG_DATA) public data: any,
to access passed data object as shown code above
Official docs[sharing-data-with-the-dialog-component]
A: if you want to pass data which the help of routing you have to define route which takes value as part of rout like as below
const appRoutes: Routes = [
{ path: 'hero/:id', component: HeroDetailComponent },];
it will from code side
gotoHeroes(hero: Hero) {
let heroId = hero ? hero.id : null;
// Pass along the hero id if available
// so that the HeroList component can select that hero.
// Include a junk 'foo' property for fun.
this.router.navigate(['/heroes', { id: heroId, foo: 'foo' }]);
}
Read : https://angular.io/guide/router#router-imports
If you want to pass data between two component then there is @Input and @Output property concept in angular which allows you to pass data between components.
@Input() - this type of property allows you to pass data from parent to child component.
Output() - this type of property allows you to pass data from child to parent component.
Other way to do it is make use of Service as use the same instance of service between component.
Read : 3 ways to communicate between Angular components
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49548623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Should I use a VM Argument or Environment Variable? I have a piece of Java code using Apache Spark to join two dataframes with a conditional that relies on a VM argument -DearlyData=TRUE for an inner join, and -DearlyData=FALSE for a leftanti join depending on whether the VM argument is set to TRUE or FALSE (Technically, if it is set to TRUE or any other value.)
This is a simplified version of my code:
``
String earlyData = System.getProperty(Constants.EARLY_DATA);
if(earlyData.equalsIgnoreCase("TRUE")){
log.trace("Running Early Data");
DataBo.processData(earlyDF.join(cassandraDF,
earlyDF.col(AA).equalTo(example.col(BB))
.and(earlyDF.col(CC).equalTo(example.col(DD))),"inner")
drop(Constants.AA, Constants.CC));
}else{
log.trace("Running Late Data");
DataBo.processData(earlyDF.join(cassandraDF,
earlyDF.col(AA).equalTo(example.col(BB))
.and(earlyDF.col(CC).equalTo(example.col(DD))), "leftanti")
.drop(Constants.AA, Constants.CC));
``
My code works, but my question is this:
*
*Should I use an Environment Variable or a VM Argument for the String earlyData?
*Are there drawbacks or unforeseen complications of using one versus the other in a conditional like this?
A: Based on the information provided here by user Jose Martinez, a VM argument is correct for this use case.
To elaborate, I have a Cron that kicks off the inner join in the morning by having -DearlyData=TRUE to retrieve early data, and a Cron that utilizes the leftanti join in the evening by using -DearlyData=FALSE in the script for late data.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46184047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Docker + ReactJS + Webpack Hot-reload + Django Webpack hotreload creates a static asset/bundle that usually is picked up by Django's collectstatic command. Since I have this setup dockerized, I'm looking for advice on how to get the hotreload working on a docker host. Specifically, when I change some code in the React App, Webpack should generate a bundle and I should be able to visit http://DOCKER_MACHINE_IP to see the hot-reload. I'm hoping to use volumes to persist the bundles, but can I call collectstatic multiple times? Is there another way to do this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35385070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Value cannot be null. Parameter name: username. Starting .net application When I start the application from Visual Studio 2010 the following error shows up:
Value cannot be null.\r\nParameter name: username
I can see this error in Global.asax.cs in the parameter sender of this method:
void Application_Error(object sender, EventArgs e)
{
}
The problem is that I'm not using username anywhere and my web.config
<configuration>
<connectionStrings>
<add name="MYSQL"
connectionString="Driver={MySQL ODBC 5.2w Driver};Server=server_name;Database=database_name;uid=my_user_id;pwd=my_pwd"
providerName="System.Data.Odbc"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
</configuration>
Any help will be welcome.
EDIT:
More information:
What I can see is:
sender.base.Profile.base.base.Session = '((System.Web.HttpApplication)(sender)).Session' threw an exception of type 'System.Web.HttpException'
and
sender.Profile.base.LastActivityDate = '((System.Web.Profile.ProfileBase)(((ASP.global_asax)(sender)).Profile)).LastActivityDate' threw an exception of type 'System.ArgumentNullException'
and
sender.Profile.base.LastActivityDate.base = {"Value cannot be null.\r\nParameter name: username"}
EDIT
This code works without any problem, and also I can execute queries.
void Application_Start(object sender, EventArgs e)
{
string ConnStr = System.Configuration.ConfigurationManager.ConnectionStrings["MYSQL"].ConnectionString;
OdbcConnection con = new OdbcConnection(ConnStr);
con.Open();
con.Close();
}
A: Your connection string is malformed.
It should probably be:
Driver={MySQL ODBC 5.2w Driver};Server=server_name;Database=database_name;User=my_user_id;Password=my_pwd
User instead of uid and Password instead of pwd.
See connectionstrings.com for the different options.
A: For some reason this error only happens when I run the application from Visual Studio and not when it is deployed in IIS.
Thank you for your help!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13643275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Scraping a specific tweet's data from Twitter in R R data analysts,
I tried to scrape all retweeters' user names (i.e. screen_names) from a specific tweet, but 'get_retweeters' function in 'rtweet' package does not seem to be able to do so. How can I scape all the screen_names (i.e. twitter accounts) of the people who retweeted the following tweet:
https://twitter.com/POTUS/status/1366863876206264327?s=20
Example:
status_id = '1366863876206264327'
test_tweet=rtweet::get_retweeters(status_id, n = 100, parse = TRUE, token = NULL)
test_tweet # this shows only "user_id"s, but it does not show the "screen_name".
I need the "screen_name"s of whoever retweeted this tweet. Thanks in advance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66463788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Highcharts stock data grouping not working properly without groupPixelWidth I cannot get Highchart stock to properly group my data according to my units with a line chart (xAxis type is 'datetime'). Here's my settings:
series: {
dataGrouping: {
enabled: true,
forced: true,
groupAll: true,
approximation: 'sum',
units: [
['minute', [5, 15, 30]],
['hour', [1]],
['day', [1]],
],
dateTimeLabelFormats: {
minute: ['%A %e %b, %H:%M', '%A %e %b, %H:%M', '-%H:%M'],
hour: ['%A %e %b, %H:%M', '%A %e %b, %H:%M', '-%H:%M'],
day: ['%A %e %b, %Y', '%A %e %b', '%A %e %b, %Y'],
}
},
}
I expect the data to be grouped by days when the chart first loads. But the data are actually grouped according to my minimum unit (5 minutes). I can get it to work if I add groupPixelWidth: 100, but that's quite arbitrary and I'm afraid the user experience will change on different screen sizes (moreover, my chart container width is dynamic). Does someone knows a better way to achieve what I want?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61910469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Swift - Get array item with an IndexSet I have my Contact object:
struct Contact: Codable, Identifiable {
var id: Int = 0
var name: String
var lastName: String
var phoneNumber: String
}
And in my view I have a list of contacts that will be fetched from a server.
List {
ForEach(viewModel.contacts) { contact in
ContactView(contact: contact)
}
.onDelete(perform: self.viewModel.delete)
}
When I delete a contact I call my viewModel method delete which only removes the item from the array. But since I will make a server request to delete a contact, I would like to get info about the item I'm deleting, like the Id.
class ContactsViewModel: ObservableObject {
@Published contacts = [
Contact(id: 1, name: "Name 1", lastName: "Last Name 1", phoneNumber: "613456789"),
Contact(id: 2, name: "Name 2", lastName: "Last Name 2", phoneNumber: "623456789"),
Contact(id: 3, name: "Name 3", lastName: "Last Name 3", phoneNumber: "633456789"),
Contact(id: 4, name: "Name 4", lastName: "Last Name 4", phoneNumber: "643456789")
]
func delete(at offsets: IndexSet) {
self.contacts.remove(atOffsets: offsets)
}
}
I wonder if I can do something like this:
func delete(at offsets: IndexSet) {
// Get the contact from array using the IndexSet
let itemToDelete = self.contacts.get(at: offsets)
deleteRequest(itemToDelete.id){ success in
if success {
self.contacts.remove(atOffsets: offsets)
}
}
}
A: Taking into account that mentioned deleteRequest semantically is asynchronous and there might be, in general, several contacts deleted in one user action, I would do it like below
func delete(at offsets: IndexSet) {
// preserve all ids to be deleted to avoid indices confusing
let idsToDelete = offsets.map { self.contacts[$0].id }
// schedule remote delete for selected ids
_ = idsToDelete.compactMap { [weak self] id in
self?.deleteRequest(id){ success in
if success {
DispatchQueue.main.async {
// update on main queue
self?.contacts.removeAll { $0.id == id }
}
}
}
}
}
Note: also some feedback in UI would be needed marking progressed contacts and disabling user from other manipulations with them till end of corresponding deleteRequest
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61347408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Is the Unicode code point value equal to the UTF-16BE representation for every character? I saved some strings in Microsoft Agenda in Unicode big endian format (UTF-16BE). When I open it with the shell command xxd to see the binary value, write it down, and get the value of the Unicode code point by ord() to get the ordinal value character by character (this is a python built-in function which takes a one-character Unicode string and returns the code point value), and compare them, I find they are equal.
But I think that the Unicode code point value is different to UTF-16BE — one is a code point; the other is an encoding format. Some of them are equal, but maybe they are different for some characters.
Is the Unicode code point value equal to the UTF-16BE encoding representation for every character?
A: No, codepoints outside of the Basic Multilingual Plane use two UTF-16 words (so 4 bytes).
For codepoints in the U+0000 to U+D7FF and U+E000 to U+FFFF ranges, the codepoint and UTF-16 encoding map one-to-one.
For codepoints in the range U+10000 to U+10FFFF, two words in the range U+D800 to U+DFFF are used; a lead surrogate from 0xD800 to 0xDBFF and a trail surrogate from 0xDC00 to 0xDFFF.
See the UTF-16 Wikipedia article on the nitty gritty details.
So, most UTF-16 big-endian bytes, when printed, can be mapped directly to Unicode codepoints. For UTF-16 little-endian you just swap the bytes around. For UTF-16 words in starting with a 0xD8 through to 0xDF byte, you'll have to map surrogates to the actual codepoint.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22865167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Uppercase Lowercase SAMBA file creation Is there anyway, using C# .Net 2 framewort to create two files differing in Uppercase/Lowercase in a case-sensitive SAMBA drive?
For example:
myFile.txt
MyFile.txt
This is the SAMBA configuration:
smb.conf
case sensitive = yes
preserve case = yes
short preserve case = yes
Thanks!!!
A: Is your client perhaps running Windows?
The "case insensitive" setting in Samba is only useful if the client supports case insensitive filename lookups. Windows does not, and it will have trouble if you have two files with the same name but a different case.
Clients that do support case insensitivity include the SMB support in the Linux kernel and Samba's own "smbclient".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8160933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Configuring same ports with different protocols in Azure Container Instance I am trying to set up pi-hole in Azure Container Instance. Here is the link to the docker-compose file of pi-hole.
Following the YAML reference for the Azure Container Instance, I am trying to convert this docker-compose file.
Here is the YAML file I have populated.
name: pi-hole
apiVersion: '2018-10-01'
location: westus2
tags: {}
properties:
containers:
- name: pihole
properties:
image: pihole/pihole:latest
ports:
- protocol: TCP
port: 53
- protocol: UDP
port: 53
- protocol: UDP
port: 67
- protocol: TCP
port: 80
- protocol: TCP
port: 443
environmentVariables:
- name: TZ
value: Asia/Kolkata
resources: # Resource requirements of the instance
requests:
memoryInGB: 1
cpu: 1
restartPolicy: Always
ipAddress:
ports:
- protocol: TCP
port: 53
- protocol: UDP
port: 53
- protocol: UDP
port: 67
- protocol: TCP
port: 80
- protocol: TCP
port: 443
type: public
dnsNameLabel: my-pihole
osType: Linux
When I give same ports with different protocols (TCP 53 and UDP 53), like how it was given in the docker-compose file, the creation of the container group fails with the following error
> az container create -g myResourceGroup -f container.yaml
Duplicate ports '53' found in container group 'pi-hole' container 'pihole'.
How should I enter the ports to configure the port 53 in TCP and UDP like the sample docker-compose file.
A: Unfortunately, the port for ACI to exposed to the Internet should be a unique one, it means the port only can appear one time. And I know that you want the port 53 allowing both TCP and UDP protocol, but it does not support in ACI currently.
If you do not mind, the VM can help you achieve your purpose.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61053139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Invalid rectstyle object I am following a Tutorial and cannot seem to find what I am doing wrong. I tried it multiple times while changing the value of the rect to no avail.
import pygame
width = 500
height = 500
win = pygame.display.set_mode((width, height))
pygame.display.set_caption("Client")
clientNumber = 0
class Player():
def __init__(self, x, y, width, height, color):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color
self.rect = (x,y,width,height)
self.vel = 3
def draw(self, win):
pygame.draw.rect(win, self.color, self.rect)
def move(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.x -= self.vel
if keys[pygame.K_RIGHT]:
self.x += self.vel
if keys[pygame.K_UP]:
self.y -= self.vel
if keys[pygame.K_DOWN]:
self.y += self.vel
def redrawWindow(win, player):
win.fill(255, 255, 255)
player.draw(win)
pygame.display.update()
def main():
run = True
p = Player(50, 50, 100, 100, (0, 255, 0))
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
p.move()
redrawWindow(win, p)
main()
I copied the tutorial down to a T but it is a quite old video so I don't know if it is a change to the software.
A: It looks like you just forgot a set of parentheses for your "win.fill()" function. Instead of:
win.fill(255, 255, 255)
the program needs:
win.fill((255, 255, 255))
That function is actually wanting a single three-color tuple value.
When I made that change, the window appeared.
Hope that helps.
Regards.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73059323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to attach a few entities to context? Here is code:
public void CreateNewAttempt(QuizAttemptDto attemptModel)
{
var attempt = Mapper.Map<QuizAttemptDto, QuizAttempt>(attemptModel);
_context.Set<Student>().Attach(attempt.Student);
_context.Set<Quiz>().Attach(attempt.Quiz);
_context.Attempts.Add(attempt);
_context.SaveChanges();
}
When I attach 1 entity, it's working fine, but when I'm trying to attach 2 entities, I'm getting an error
Attaching an entity failed because another entity of the same type already has the same primary key value
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51876282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C array of structs initialization issues when using macros Why is adsafe_tags[1] is not getting properly initialized?
// local string (via static)
#define SSTRL(varname, val) \
static const char varname[] = val
#define SSTRLEN(var) \
(sizeof(var) - 1)
struct scs_data_tag
{
uint16_t key_size;
uint16_t val_size;
char data[];
};
SSTRL(ADSAFE_KEY, "p.as.rsa");
SSTRL(ADSAFE_VAL_BAD, "0");
SSTRL(ADSAFE_VAL_GOOD, "1000");
#define ADSAFE_KV_BAD "p.as.rsa0"
#define ADSAFE_KV_GOOD "p.as.rsa1000"
struct scs_data_tag adsafe_tags[] = {
{SSTRLEN(ADSAFE_KEY), SSTRLEN(ADSAFE_VAL_BAD), ADSAFE_KV_BAD},
{SSTRLEN(ADSAFE_KEY), SSTRLEN(ADSAFE_VAL_GOOD), ADSAFE_KV_GOOD}
};
and in gdb I get this:
(gdb) p adsafe_tags
$7 = {{key_size = 8, val_size = 1, data = 0x8ce664 <adsafe_tags+4> "p.as.rsa0"}, {key_size = 11888, val_size = 29537, data = 0x8ce668 ".rsa0"}}
A: You have not specified the size of the data member of struct scs_data_tag. This declares a C99 flexible array member. This member has size 0 by default, and you'd need to malloc more than the actual struct size in order for it to be able to contain data.
According to the standard, it should not be possible for struct scs_data_tag to be an element of an array (because it contains a flexible array member). But this is supported by some compilers as an extension.
If you instead give this array a large enough size (e.g. char data[40]), your code should work.
A: Adding to interjay's answer,. You see adsafe_tags[1].key_size = 11888 which is 0x2e70 in hex, which denotes ASCII characters p (= 0x70) and . (= 0x2e), therefore "p.".
Similarly, adsafe_tags[1].val_size = 29537, which is 0x7361 or "as", rest is printed correctly as a string.
This shows that no space is allocated to adsafe_tags[0].data.
The string you provided for initializing it got mapped to next data set.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21552551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Error with await operator There is problem with my code. How can I solve this problem? This problem in await operator.
public MyModel()
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("https://api.vkontakte.ru/method/video.get?uid=219171498&access_token=d61b93dfded2a37dfcfa63779efdb149653292636cac442e53dae9ba6a049a75637143e318cc79e826149");
string googleSearchText = await response.Content.ReadAsStringAsync();
JObject googleSearch = JObject.Parse(googleSearchText);
IList<JToken> results = googleSearch["response"].Children().Skip(1).ToList();
IList<MainPage1> searchResults = new List<MainPage1>();
foreach (JToken result in results)
{
MainPage1 searchResult = JsonConvert.DeserializeObject<MainPage1>(result.ToString());
searchResults.Add(searchResult);
}
A: You're trying to use await within a constructor. You can't do that - constructors are always synchronous.
You can only use await within a method or anonymous function with the async modifier; you can't apply that modifier to constructors.
One approach to fixing this would be to create a static async method to create an instance - that would do all the relevant awaiting, and then pass the results to a simple synchronous constructor. Your callers would then need to handle this appropriately, of course.
public static async Task<MyModel> CreateInstance()
{
string googleSearchText;
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(...))
{
googleSearchText = await response.Content.ReadAsStringAsync();
}
}
// Synchronous constructor to do the rest...
return new MyModel(googleSearchText);
}
A: You can't use await in the constructor of a class.
An async method returns a Task object which can be executed async. A constructor does not have a return type and thus can't return a Task object, and thus can't be awaited.
A simple fix for this problem is create a Init function:
public MyModel()
{
}
public async Task Init()
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("https://api.vkontakte.ru/method/video.get?uid=219171498&access_token=d61b93dfded2a37dfcfa63779efdb149653292636cac442e53dae9ba6a049a75637143e318cc79e826149");
string googleSearchText = await response.Content.ReadAsStringAsync();
JObject googleSearch = JObject.Parse(googleSearchText);
IList<JToken> results = googleSearch["response"].Children().Skip(1).ToList();
IList<MainPage1> searchResults = new List<MainPage1>();
foreach (JToken result in results)
{
MainPage1 searchResult = JsonConvert.DeserializeObject<MainPage1>(result.ToString());
searchResults.Add(searchResult);
}
}
Then when you create your model:
var model = new MyModel();
await model.Init();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18205810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
}
|
Q: Image clicked from Camera inside android app is blurred and has square pattern all over it I am developing an app that uses phone camera to click pictures. On a few phones the camera images captured has square pattern as shown in the picture. I was earlier using the default Camera intent for opening the camera. Now I use the https://github.com/commonsguy/cwac-cam2 library. Also ths problem occurs only in portrait mode and not in landscape.
**strong text**photoFile = Camera.createImageFile();
Intent i=newCameraActivity.IntentBuilder(this)
.skipConfirm()
.facing(CameraActivity.Facing.BACK)
.to(photoFile)
.debug()
.updateMediaStore()
.build();
startActivityForResult(i, RESULT_CLICK_IMAGE);
A: This happens because the image is interpolated from a TV screen.
If you would take this image from a paper for example this is would not happen
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32937360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Roomle Model Falls Through Floor If Model Has Glass Like Material A few of our furniture models have acrylic legs, which for some reason makes the model "fall" through the floor. If for example it's an acrylic bench with a fabric cushion on top, the model falls through 'till it reaches the bottom of the cushion.
Is this a bug in Roomle where when you apply a transparent material onto something it thinks it's actually not there? We've tried importing it with flipped planes underneath the legs to try and "trick" the configurator that there was some geo there without any transparency. But this did not work either.
If wanted, I can link to an example that we have. Any help will be greatly appreciated!
Kind Regards,
Wade Morrison
A: It looks as if your configuration is placed below the floor. The floor (where the shadows are) is placed exactly on coordinate 0.
Try moving your configuration up until you bottom of the product is on floor level.
You can find more information about scripting here: https://docs.roomle.com/scripting/resources/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69544174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C# WinForms - Button on Form2, to hide Form1 So I have 2 Forms:
*
*Form1
*Form2
There is a button on Form2, that I'd like to have hide Form1 when clicked.
Button Click from Button in Form2
var mainFrm = new Form1();
mainFrm.Hide();
This does nothing. I'm obviously missing something, but can't seem to figure it out.
Any help is definitely appreciated!
A: If your form1 is already present in the page, then why do you need to initialize it again? Just set the visible status to false to hide it.
mainFrm.Visible = false;
A: without seeing more of the code it's hard to answer, but you definitely need to reference the the old Form1 that is already visible and hide it. You are creating a new form and hiding it.
A: You have to define your Form2 class to store the reference to the main form.
public partial class Form2 : Form
{
/* reference to the main form will be stored here */
private Form1 _mainForm;
public Form2(Form1 mainForm)
{
InitializeComponent();
/* Initialize the main form field */
this._mainForm = mainForm;
}
private void button1_Click(object sender, EventArgs e)
{
/* Set the main form visibility to false */
_mainForm.Visible = false;
}
}
Now when you are creating the Form2 instance just add the main form to the constructor:
/* Show the form2 */
_form2 = new Form2(this);
_form2.Show();
Note: this will refer to the form that creates the Form2 object.
A: You could create a static form type property in your Form1 and set it when Form1 is Shown, and then use it to hide your form
Here is a code that worked for me.
private void button1_Click(object sender, EventArgs e)
{
var objForm1 = new Form1();
Form1.Fom1ref = objForm1;
objForm1.Show();
}
private void button2_Click(object sender, EventArgs e)
{
Form1.Fom1ref.Hide();
}
Here is the property that should be set in Form1.
public static Form Fom1ref { get; set; }
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37420027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: How to convert .rda to .pmml and use it in Python I've got myself a neural network model in .rda format that is already trained, and I'm not sure how to convert it to .pmml so that I can use it as a predictive engine in Python. Once this is done, which libraries should I install to allow the pmml file to be used in Python? Are there any special interactions I should be aware of?
-UPDATE- I installed r2pmml into my RStudio, and I was wondering if its possible to load a model from .rda format and instantly export it without having to train it. Can this be done?
-UPDATE 2- Managed to convert .Rda to .pmml successfully. I have a list of 0/1 vectors to use with the pmml file, (53,850 1's and 0's); how do I run the list through the predictive model in Python? One of the suggestions was to use Augustus.
A: The .rda file contains the model object in a R-specific serialization data format. You should be able to de-serialize it using the readRDS(rds_path) method, and then invoke the r2pmml(model, pmml_path) method.
Training a model, and serializing it into a RDS file:
library("randomForest")
rf = randomForest(Species ~ ., data = iris)
saveRDS(rf, "rf.rds")
De-serializing the model from the RDS file, and exporting it into a PMML file:
library("r2pmml")
rf_clone = readRDS("rf.rds")
r2pmml(rf_clone, "rf.pmml")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45387069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Selecting specific rows based on conditions in MySQL 5.6 Following is a small snapshot of data from which I need to extract information.
ID FREQ LTD SD LWD DPD
_______________________________________________________
1021 Weekly 2016-05-27 2016-05-23 2016-05-31 0
1021 Weekly 2016-05-27 2016-05-27 2016-05-31 0
1021 Weekly 2016-06-02 2016-06-06 2016-06-30 24
1021 Weekly 2016-06-02 2016-06-13 2016-06-30 17
1021 Weekly 2016-06-02 2016-06-20 2016-06-30 10
1021 Weekly 2016-06-02 2016-06-27 2016-06-30 0
1021 Weekly 2017-02-27 2017-02-06 2017-02-28 0
1021 Weekly 2017-02-27 2017-02-13 2017-02-28 0
LTD = Last Transaction Date of that month
SD = Scheduled Dates of that month when the payment was supposed to come.
LWD = Last Working Day of that month.
DPD = Days Past Due which is calculated as
when freq = 'Weekly' and SD between LTD and LWD AND datediff(LWD, SD) > 7 THEN datediff(LWD, SD) as DPD. All the Dates are of Date Datatype.
Now, see the sample data and notice the 6th and the 7th row. The 7th row calculates the DPD as 0 taking in account the LWD and 'SD' of that month. However it should be calculating the DPD taking in account that after 2016-06-02 the next payment came on 2017-02-27 so in DPD calculation, days should be added for the next 6 months in which there was no transaction.
How can I achieve this? Any help appreciated.
My current Query is:
select y.*,
case when freq_term = 'Daily' and scheduled_date between last_transaction_date and last_working_day
AND datediff(last_working_day, Scheduled_Date) > 1 THEN datediff(last_working_day, Scheduled_Date)
-- WHEN freq_term = 'Daily' AND datediff(last_working_day, Scheduled_Date) > 1 THEN datediff(last_working_day, Scheduled_Date)
-- when freq_term = 'Weekly' and scheduled_date between last_transaction_date and last_working_day
-- AND datediff(last_working_day, Scheduled_Date) > 7 THEN datediff(last_working_day, Scheduled_Date)
WHEN freq_term = 'Weekly' AND datediff(last_working_day, Scheduled_Date) > 7 THEN datediff(last_working_day, Scheduled_Date)
WHEN freq_term = 'Bi-Monthly' AND datediff(last_working_day, Scheduled_Date) > 14 THEN datediff(last_working_day, Scheduled_Date)
WHEN freq_term = 'Monthly' AND datediff(last_working_day, Scheduled_Date) > 30 THEN datediff(last_working_day, Scheduled_Date) END 'DPD'
from
(
select id,
freq_term,
max_date 'Last_Transaction_date',
t3.date 'Scheduled_date',
date(last_day(date) - (CASE DAYOFWEEK(last_day(date)) WHEN 1 THEN 2 WHEN 7 THEN 1 ELSE 0 END)) as 'Last_working_day'
from
(
select
jlp.id,
jlp.freq_term,
t1.max_date,
t1month,
t1year
from jos_lender_portfolio jlp
inner join
(
select lpid, year(date) t1year, month(date) t1month, max(date) max_date
from jos_lender_transactions
where description in('Payment', 'Partial Payoff', 'Early Payoff')
and date <= '2018-01-01'
group by lpid, year(date),month(date)
)t1 on jlp.id = t1.lpid
where id = 1021
order by 3
)t
inner join
(SELECT
lpid,
date,
MONTH(DATE) t3month,
year(date) t3year
from jos_lender_trans_backup where description = 'Payment' and lpid = 1021 order by date
)t3
on t.id = t3.lpid and t.t1month = t3.t3month and t.t1year = t3.t3year
)y
group by id, last_day(Last_Transaction_date)
order by Scheduled_Date;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48619030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cannot set checkbox to checked using jquery I have the following javascript function. A the top of the function, I am able to detect if a checkbox is checked using $(elem).is(':checked'). Later in the function I want to wire up an onclick event in a modal window such that it will checkmark the elem's checkbox, but this does not seem to work.
Here is the function:
function toggleProductChkBx(elem,id)
{
if ($(elem).is(':checked')) {
} else {
$('#clearProductModal').on('show', function () {
removeBtn = $(this).find('.danger');
removeBtn.click(function () { clearProduct(id) });
cancelBtn = $(this).find('.secondary');
//THIS IS THE LINE THAT IS NOT WORKING
cancelBtn.click(function () { $(elem).attr("checked", "true"); });
})
.modal({ backdrop: true });
}
}
Thanks for the help!
A: Change
cancelBtn.click(function () { $(elem).attr("checked", "true"); });
To
cancelBtn.click(function () { $(elem).prop("checked", true); });
A: try this:
$(elem).attr("checked", true);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16409153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Magento - Importing Products in csv file - empty columns I am currently adding all my products into a csv file ready to import into my store. To get the template i exported my existing products and am using that csv as the template which contains every single column.
I have a lot of empty columns such as...
custom_design_from manufacturer minimal_price msrp special_price
etc..
Do i need to include these empty columns? If i remove them will that mess up my import?
A: no it will not effect , you can remove them from csv and import
A: No it will not mess up your import, however be careful when making edits to the csv file as some programs save the file in the wrong csv format I'd recommend open office and when you hit save make sure you push in current format
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23898204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: create index using openquery How do I create an index on a table that exist in a remote SQL Server database using the openquery syntax?
A: You can't on your side. The index must be added to a local object only. You can't use an indexed view either.
You can ask the other party to add an index for you to their table...
Edit:
Expanding John's answer... You could try:
SELECT * FROM OPENQUERY(LinkedServer, 'CREATE INDEX etc;SELECT 0 AS foobar')
A: I'm not certain however I suspect that this cannot be done.
OPENQUERY is intended to return a Result Set and so is unlikely to accept DDL statements.
See the Microsoft Books Online reference for examples of acceptable usage scenarios.
http://technet.microsoft.com/en-us/library/ms188427.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1109476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Sftp (paramiko) put method not working (FileNotFoundError: [Errno 2] No such file) but sometimes the file is uploaded anyway I have a strange behaviour when trying to upload a file into an sftp by using paramiko.
myHostname = "xxx"
port = 22
myUsername = "yyy"
myPassword = "zzz"
try:
t = paramiko.Transport((myHostname, port))
t.connect(username = myUsername, password = myPassword)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.put("C:\Users\simeone\Documents\Repository\REC_bbgAIM\f6431recupload.csv.TEMPL_BNP_MIL_CASH.inc","/f6431recupload.csv.TEMPL_BNP_MIL_CASH.inc")
### Comment: you see that as first argument I passed the whole path with \, result does not change if I use / or \\
finally:
sftp.close()
t.close()
I get the following error:
Traceback (most recent call last):
File "C:\Users\simeone\Documents\Repository\REC_bbgAIM\main.py", line 25, in <module>
sftp.put("f6431recupload.csv.TEMPL_BNP_MIL_CASH.inc", "/f6431recupload.csv.TEMPL_BNP_MIL_CASH.inc")
File "C:\Users\simeone\Documents\Repository\REC_bbgAIM\REC_AIM_bbg\Lib\site-packages\paramiko\sftp_client.py", line 759, in put
return self.putfo(fl, remotepath, file_size, callback, confirm)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\simeone\Documents\Repository\REC_bbgAIM\REC_AIM_bbg\Lib\site-packages\paramiko\sftp_client.py", line 720, in putfo
s = self.stat(remotepath)
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\simeone\Documents\Repository\REC_bbgAIM\REC_AIM_bbg\Lib\site-packages\paramiko\sftp_client.py", line 493, in stat
t, msg = self._request(CMD_STAT, path)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\simeone\Documents\Repository\REC_bbgAIM\REC_AIM_bbg\Lib\site-packages\paramiko\sftp_client.py", line 822, in _request
return self._read_response(num)
^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\simeone\Documents\Repository\REC_bbgAIM\REC_AIM_bbg\Lib\site-packages\paramiko\sftp_client.py", line 874, in _read_response
self._convert_status(msg)
File "C:\Users\simeone\Documents\Repository\REC_bbgAIM\REC_AIM_bbg\Lib\site-packages\paramiko\sftp_client.py", line 903, in _convert_status
raise IOError(errno.ENOENT, text)
FileNotFoundError: [Errno 2] No such file
I checked references:
Upload all files from local folder with specific extension to SFTP server using Paramiko
Paramiko SFTPClient.get fails with "FileNotFoundError: [Errno 2] No such file or directory" referring to the remote file path
The error happens in the put, but the behaviour I get is very strange because sometimes the file is uploaded correctly although I get the error message.
I work on Windows and python 3.11.1
I tried with pysftp as well, but was not working and thought was due to the fact that is no longer maintained.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75017523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get index of marked text in Edittext, Android studio kotlin
I'm trying to get the start and end index for the marked text in my editText in android studio.
A: Get selectionStart and selectionEnd:
val startIndex = editText.selectionStart
val endIndex = editText.selectionEnd
A: You need to make use of this class Selection
https://developer.android.com/reference/android/text/Selection
Try out method from it
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54381318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Beginner - Springboot weather program I'm learning Java and SpringBoot. Trying to make a web app to check the weather. I'm using API from https://openweathermap.org/api.
I do not know how to retrieve data from API (JSON). Could someone tell me something?
public String connectAndResponse(String url) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getResponseCode()==200 ? connection.getInputStream() : connection.getErrorStream()
));
String line = "";
while((line = reader.readLine()) !=null){
stringBuilder.append(line);
}
return stringBuilder.toString();
}
I have already processed JSON on a string but I do not know how to use JSON to use spring boot (it would work on a form where the locale is typing).
A: From Spring documentation "Consuming a RESTful Web Service" :
This guide walks you through the process of creating an application
that consumes a RESTful web service.
First, you will have to define your model. In this case, it is Quote and Value.
Then, you will be able to call your API.
Here's the example :
public class Application {
private static final Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String args[]) {
RestTemplate restTemplate = new RestTemplate();
Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class);
log.info(quote.toString());
}
}
RestTemplate will automatically transform JSON from API into Java object.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46003140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Moving Elements to a New Line on Browser Resize I'm looking for a solution that will dynamically move elements depending on the size of the browser.
Example:
I will use "X" as example of an element
If one user is viewing on a resolution similar to a mac, they will see
X X X X X X - The maximum amount of LIs / DIVs
If the browser is resized to half the size, they will see
X X X - Half the amount of LIs / DIVs
What would be the best way of going about this to try and replicate? an working example is seen here : http://www.therugcompany.com/gb/collection.html
Thanks for Looking!
A: If the LIs/DIVs are floated elements, they'll naturally fall down to the next line as the width of their container gets smaller.
W3Schools has a nice example of exactly what you are describing, here:
http://www.w3schools.com/css/tryit.asp?filename=trycss_float_elements
That's from the main CSS Float topic page, here:
http://www.w3schools.com/css/css_float.asp
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16105849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Python Pillow not working on raspbian I installed Pillow 3.3.0 using easy_install (pip install results in the same behavior). After succesfull installation I get an "illegal instruction" error when I import the Image class.
The output of the installation:
root@rasp01:/data/server# easy_install Pillow
Searching for Pillow
Reading http://pypi.python.org/simple/Pillow/
Best match: Pillow 3.3.0
Downloading https://pypi.python.org/packages/e0/27/f61098a12f14690689924de93ffdd101463083a80bf8ff3e0c218addf05b/Pillow-3.3.0.tar.gz#md5=b5a15b03bf402fe254636c015fcf04da
Processing Pillow-3.3.0.tar.gz
Running Pillow-3.3.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-c1OEYc/Pillow-3.3.0/egg-dist-tmp-iwARkP
Single threaded build, not installing mp_compile:1 processes
warning: no files found matching '*.sh'
no previously-included directories found matching 'docs/_static'
warning: no previously-included files found matching '.coveragerc'
warning: no previously-included files found matching '.editorconfig'
warning: no previously-included files found matching '.landscape.yaml'
warning: no previously-included files found matching 'appveyor.yml'
warning: no previously-included files found matching 'build_children.sh'
warning: no previously-included files found matching 'tox.ini'
warning: no previously-included files matching '.git*' found anywhere in distribution
warning: no previously-included files matching '*.pyc' found anywhere in distribution
warning: no previously-included files matching '*.so' found anywhere in distribution
--------------------------------------------------------------------
PIL SETUP SUMMARY
--------------------------------------------------------------------
version Pillow 3.3.0
platform linux2 2.7.3 (default, Mar 18 2014, 05:13:23)
[GCC 4.6.3]
--------------------------------------------------------------------
--- JPEG support available
*** OPENJPEG (JPEG2000) support not available
--- ZLIB (PNG/ZIP) support available
*** LIBIMAGEQUANT support not available
*** LIBTIFF support not available
--- FREETYPE2 support available
*** LITTLECMS2 support not available
*** WEBP support not available
*** WEBPMUX support not available
--------------------------------------------------------------------
To add a missing option, make sure you have the required
library and headers.
To check the build, run the selftest.py script.
Adding Pillow 3.3.0 to easy-install.pth file
Installing pilfont.py script to /usr/local/bin
Installing thresholder.py script to /usr/local/bin
Installing gifmaker.py script to /usr/local/bin
Installing viewer.py script to /usr/local/bin
Installing createfontdatachunk.py script to /usr/local/bin
Installing enhancer.py script to /usr/local/bin
Installing pilconvert.py script to /usr/local/bin
Installing pilfile.py script to /usr/local/bin
Installing player.py script to /usr/local/bin
Installing explode.py script to /usr/local/bin
Installing pildriver.py script to /usr/local/bin
Installing painter.py script to /usr/local/bin
Installing pilprint.py script to /usr/local/bin
Installed /usr/local/lib/python2.7/dist-packages/Pillow-3.3.0-py2.7-linux-armv6l.egg
Processing dependencies for Pillow
Finished processing dependencies for Pillow
And the output of the error:
root@rasp01:/data/server# python
Python 2.7.3 (default, Mar 18 2014, 05:13:23)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from PIL import Image
Illegal instruction
root@rasp01:/data/server#
Does anyone have an idea what is wrong here? Thanks in advance!
A: You could try
from PIL import *
and just import everything from the library instead
or if that doesn't work try
import PIL
A: Raspberry Pi uses ARM, PILLOW that is installed is not compatible, hence the instruction is illegal.
Try installing PILLOW with sudo apt-get command
A: Thanks for your replies. Eventually I installed PIL using:
sudo apt-get install python-imaging
This installed PIL in the right architecture an is working.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38777429",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Several controls bound (two way) on a same field in Silverlight 4 I have an issue with several controls bound on a same field. Let me explain with a simple example :
I have an instance of this class in my datacontext :
class X { string myVar; }
myVar is a composed variable, for instance contains things like "42;bar"
I have two TextBoxes bound on myVar in my Silverlight :
<TextBox Text="{Binding myVar, Mode=TwoWay, Converter=XConverter}" /><!-- 42 -->
<TextBox Text="{Binding myVar, Mode=TwoWay, Converter=YConverter}" /><!-- bar -->
XConverter knows how to convert myVar to 42.
YConverter knows how to convert myVar to bar.
But how can I ConvertBack ? For instance if I change 42 to 43, how can I recreate 43;bar ? Because in the converter, I don't have the previous value of myVar.
And I don't want to add properties to the class X (in this example, I have 2 controls bound on a field, but in reality, it's much more).
Thanks!
edit: And I don't want to add handlers such as TextChanged, I'd like a "Binding way" to do it.
A: I would do a multibinding http://www.scottlogic.co.uk/blog/colin/2010/05/silverlight-multibinding-solution-for-silverlight-4/ for XConverter and YConverter (with the ConvertBack method filled in).
I would have each XConverter and YConverter bound to both textboxes. Then in XConverter replace only before the ; and YConverter replace after the ;
A: I would probably utilize a decorator class for class X.
Internally, the decorator class would break the myVar into separate properties, each of which can be bound to the screen. Then you would have a ToX() method to get the X object back out of the decorator. That method would do the easy construction of the myVar property. Example is something like this:
public class X
{
public string myVar { get; set; }
}
public class XDecorator
{
public XDecorator(X x)
{
var pieces = x.Split(';');
XPart = pieces[0];
YPart = pieces[1];
}
public string XPart { get; set; }
public string YPart { get; set; }
public X ToX()
{
return new X { myVar = string.Format("{0};{1}", XPart, YPart) };
}
}
Then, when you're setting this property on your ViewModel, you first wrap it in this decorator class. And when you go to save it, you call the ToX() method to get the X object out - the thing you really want.
Hope that makes sense.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4670082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: in IE9 uploadFile is not working 1 Add the file input box
<input type="file" id="uploadFile" ng-model="upFile" onchange="angular.element(this).scope().setFile(this)" />
2 Create the setFile method in the controller
$scope.setFile = function (element) {
$scope.uploadedFile = element.files[0];
}
as above,I use this way to upload file ,it works in FireFox but in IE9 it shows that the "element is null our undefined". What can i do?
A: files is a HTML5 file api feature and works only on browsers that support it.
It's not supported in IE9 see: http://caniuse.com/#feat=fileapi
You can check if files is supported before use it, try (not tested):
if( ev.target.files ){
$scope.uploadedFile = element.files[0];
}else{
$scope.uploadedFile = ev.target.value;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16321791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Change A5 to A4 format on runtime I created a A5 report in ireport and use in java application.
I change A5 to A4 format on runtime and View Page but when print Page output be A5 format.
following code:
JasperDesign _des = JRXmlLoader.load("report1.jrxml");
_des.setPageHeight(842);
_des.setPageWidth(595);
JasperReport _rep = JasperCompileManager.compileReport(_des);
JasperPrint jasperPrint = JasperFillManager.fillReport(_rep, params, _data);
JRViewer_com = new JRViewer(jasperPrint);
A: There must be something missing in your code that is not supplied in your question. When I created an example and ran it it works. The only change I made was I used the static method JasperViewer.viewReport(jasperPrint, true); to view the report.
public static void main(String[] args) throws JRException {
File file = new File("C:\\Test\\src\\report1.jrxml");
System.out.println("file = "+file.exists());
JasperDesign _des = JRXmlLoader.load(file);
_des.setPageHeight(842);
_des.setPageWidth(595);
JasperReport _rep = JasperCompileManager.compileReport(_des);
JasperPrint jasperPrint = JasperFillManager.fillReport(_rep, new HashMap<String, Object>());
JasperViewer.viewReport(jasperPrint, true);
}
If you could provide a small single java class that is runnable and reproduces the issue, I may be able to help more.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13859926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Adding tool tips to dojo DataGrid items I would like to add a tooltip with some extra data to each row in a dojox.grid.DataGrid. I have tried to create an onCellMouseOver-handler, but I can't get the data item data out of the event object I'm getting.
What is the best way to add a tooltip to a DataGrid-row?
A: In your onCellMouseOver you can get the row index (e.rowIndex). From that you can get the item from the grid assuming you are using an ItemFileReadStore (I have not tried it with a ItemFileWriteStore)
function cellMouseOver (e)
{
var rowIndex = e.rowIndex;
var item = grid.getItem(e.rowIndex);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2410962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Highcharts / HighStock issue, series disappearing on dynamic update I have this high stocks area chart, consuming a JSON api. Each n seconds, the chart recalls the API for the delta in points.
After a few minutes, the left hand side series disappears, however, if you mouse over it, the labels still appear. Happens on Mac and Windows, FF IE Chrome and Safari. Would appreciate any help.
You can view a demo here:
https://dev-mv-charts.azurewebsites.net/goldarea.htm
Update: If I use the below code, take from the highcharts site, it seems to work. Just need to replace the initial load of random data now.
$(function () {
Highcharts.setOptions({
global : {
useUTC : true
}
});
// Create the chart
$('#container').highcharts('StockChart', {
chart : {
events : {
load : function () {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function () {
var _update_url = 'http://api.bullionmark.com/v1/ask?currencyId=2&commodityId=1';
$.ajax({
type: 'GET',
url: _update_url}).done(function (resp1) {
var x2 = parseInt(resp1.Timestamp) * 1000;
var y2 = parseFloat(resp1.Current);
//var x = (new Date()).getTime(), // current time
//y = Math.round(Math.random() * 100);
series.addPoint([x2, y2], true, true);
});
}, 5000);
}
}
},
rangeSelector: {
buttons: [{
count: 1,
type: 'minute',
text: '1M'
}, {
count: 5,
type: 'minute',
text: '5M'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: false,
selected: 0
},
title : {
text : 'Live random data'
},
exporting: {
enabled: false
},
series : [{
name : 'Random data',
type : 'area',
data : (function () {
// generate an array of random data
var data = [], time = (new Date()).getTime(), i;
for (i = -999; i <= 0; i += 1) {
data.push([
time + i * 1000,
Math.round(Math.random() * 100)
]);
}
return data;
}())
}]
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31280558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Create basic php page not working I'm trying to create new page in PHP(new_page.php), successful created page will be insert into database (create_page.php), but now it is not working, not sure which steps i am missing, any helps are appreciate. Below is my code & screenshots:
Mysql table:
http://i60.tinypic.com/2h3aofr.png
new_page.php
http://i60.tinypic.com/21dmop2.png
<?php $host = "localhost";
$name = "root";
$password = "";
$db = "test_son";
$connection = mysqli_connect($host, $name, $password, $db);
//Check if connect to MySQL works
if (mysqli_connect_errno()){
die("Connection to MySql error " . mysqli_connect_errno());
}?>
<?php
function find_all_pages(){
global $connection;
$query = "select * from pages ";
$query .= "order by position asc";
$page_set = mysqli_query($connection, $query);
confirm_query($page_set);
return $page_set;
}?>
<h2>Create Page</h2>
<form action="create_page.php" method="post">
<p>Subject Id:
<input type="number" name="subject_id" value="" />
</p>
<p>Book name:
<input type="text" name="book_name" value="" />
<br/><br/>
</p>
<p>Position:
<select name="position">
<?php
$page_set = find_all_pages();
$page_count = mysqli_num_rows($page_set);
for ($count=1; $count <= $page_count; $count++){
echo "<option value=\"1\">{$count}</option>";}
?>
</select>
</p>
<p>visible
<input type="radio" name="visible" value="0" /> No
<input type="radio" name="visible" value="0" /> Yes
</p>
<input type="submit" name ="submit" value="Create Page" />
</form>
create_page.php
<?php
if (isset($_POST["submit"])){
//Process the form
$subject_id = $_POST["subject_id"];
$book_name = $_POST["book_name"];
$position = $_POST["position"];
$visible = $_POST["visible"];
$book_name = mysqli_real_escape_string($connection, $book_name);
$subject_id = mysqli_real_escape_string($connection, $subject_id);
//Perform database query
$query = "insert into pages (";
$query .= " subject_id, 'book_name', position, visible";
$query .= " ) values ( ";
$query .= "$subject_id, '$book_name', $position, $visible ";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result){
//Success will redirect to manage content page
$_SESSION["message"] = "page was created. ";
redirect("manage_content.php");
} else {
//Failure will redirect to new subject page
//$_SESSION["message"] = "subject was not created. Please check following possible errors: <br/> "
//. " menu name is not blank <br/> visible is not blank";
//redirect("new_page.php");
echo "fail " . mysqli_error($connection) ;
}
}
?>
When i submitted the create page button, error appears:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''book_name', position, visible ) values ( 121, 'how to win influence 1234', 1, 0'
A: There are security vulnerabilities in the way you are creating that query. But to specifically respond to your issue, get rid of the ' around 'book_name'.
A: You shouldn't have a ' character in the list of column_names .... column names are not string literals, they're column names. If they absolutely have to be quoted (e.g. if you have a column name that is a MySQL reserved word, then you use backticks(`) not quotes (')
$query = "insert into pages (";
$query .= " subject_id, book_name, position, visible";
$query .= " ) values ( ";
$query .= "$subject_id, '$book_name', $position, $visible ";
$query .= ")";
Now please learn about prepared statements and bind variables
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24625731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
}
|
Q: How to count the number of occurrences in one array from the values of a second array in PHP? I have 2 arrays in PHP that look something like this:
$rows = array(11,12,14,14,11,13,12,11);
$cols = array(1,2,1,2,2,2,1,1);
I need to combine these arrays in a way that tells how many of each $cols value is in each $rows value.
So my result should look something like this:
Array
(
[0] => Array
(
[row] => 11
[1] => 2 //the count of 1 cols for 11
[2] => 1 //the count of 2 cols for 11
)
[1] => Array
(
[row] => 12
[1] => 1
[2] => 1
)
...
)
The values of $rows and $cols will change based upon the users input, they may even be strings.
Clarification:
The duplicates values come from the data. Think survey results or test questions. So question 11 had 2 people answer 1 and 1 person answer 2.
Question:
How do I count the number of occurrences of $cols in $rows and add the results into a multidimensional array?
A: Check out array_intersect(). Use it to get values that are the same and do a count() on the resulting array.
A: I figured it out. It was not as complicated as I first thought. Just needed a function to calculate the sum. Perhaps it could be more efficient, I would love any ideas on that, but here it is:
$rowColumns = array();
for($i=0;$i<=$count-1;$i++)
{
$currentRow = $rows[$i];
$currentCol = $cols[$i];
//count occurences of columns in row
$colSum = $this->getColumnOccurences($count,$rows,$cols,$currentRow,$currentCol);
$rowColumns[$currentRow][$currentCol] = $colSum;
}
private function getColumnOccurences($count,$rows,$cols,$rowValue,$colValue)
{
$retValue = 0;
for($i=0;$i<=$count-1;$i++)
{
if($rows[$i] == $rowValue && $cols[$i] == $colValue)
{
$retValue = $retValue + 1;
}
}
return $retValue;
}
The result is:
Array (
[11] => Array ( [1] => 2 [2] => 1 )
[12] => Array ( [1] => 1 [2] => 1 )
[13] => Array ( [2] => 1 )
[14] => Array ( [1] => 1 [2] => 1 )
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4268234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get the last N lines from an unlimited Popen.stdout object I'm trying to get the last N lines from an unlimited Popen.stdout object at the current time. And by unlimited I mean unlimited/many log entries which are getting written to stdout.
I tried Popen.stdout.readline() limited by time, but this just produce a whole lot of random issues, especially with little output.
Some sort of snapshot of the current output would help me, but I am unable to find anything like that. All the solutions I mostly find are for external processes which terminate, but mine is an server application which should be able to write to stdout after I read the last lines.
Greetings,
Faerbit
A: On Unix, when you launch your process you can pipe it into tail first:
p=subprocess.Popen("your_process.sh | tail --lines=3", stdout=subprocess.PIPE, shell=True)
r=p.communicate()
print r[0]
Usage of shell=True is the key here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14924316",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Stopping/Starting a remote Windows service and waiting for it to open/close The top answer to this question tells me how to stop/start a remote service. Great.
Now, all I need is to wait for the actual stop/start to complete. So, what I'm looking for is a dos command to:
*
*Start a service, should return only after the service is started (or after a timeout, raising error level)
*Stop a service, return only after the service is stopped
A: I've never actually seen something that does this specifically but it would be quite easy to knock such a utility out in C\C#\VB or any other language that gives easy access to the Service API. Here's a sample of something in C#.
using System;
using System.ComponentModel;
using System.ServiceProcess;
namespace SCSync
{
class Program
{
private const int ERROR_SUCCESS = 0;
private const int ERROR_INVALID_COMMAND_LINE = 1;
private const int ERROR_NO_ACCESS = 2;
private const int ERROR_COMMAND_TIMEOUT = 3;
private const int ERROR_NO_SERVICE = 4;
private const int ERROR_NO_SERVER = 5;
private const int ERROR_INVALID_STATE = 6;
private const int ERROR_UNSPECIFIED = 7;
static int Main(string[] args)
{
if (args.Length < 2 || args.Length > 4)
{
ShowUsage();
return ERROR_INVALID_COMMAND_LINE;
}
string serviceName = args[0];
string command = args[1].ToUpper();
string serverName = ".";
string timeoutString = "30";
int timeout;
if (args.Length > 2)
{
if (args[2].StartsWith(@"\\"))
{
serverName = args[2].Substring(2);
if (args.Length > 3)
{
timeoutString = args[3];
}
}
else
{
timeoutString = args[2];
}
}
if (!int.TryParse(timeoutString, out timeout))
{
Console.WriteLine("Invalid timeout value.\n");
ShowUsage();
return ERROR_INVALID_COMMAND_LINE;
}
try
{
ServiceController sc = new ServiceController(serviceName, serverName);
switch (command)
{
case "START":
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 0, timeout));
break;
case "STOP":
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 0, timeout));
break;
case "PAUSE":
sc.Pause();
sc.WaitForStatus(ServiceControllerStatus.Paused, new TimeSpan(0, 0, 0, timeout));
break;
case "CONTINUE":
sc.Continue();
sc.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 0, timeout));
break;
default:
Console.WriteLine("Invalid command value.\n");
ShowUsage();
return ERROR_INVALID_COMMAND_LINE;
}
}
catch (System.ServiceProcess.TimeoutException)
{
Console.WriteLine("Operation timed out.\n");
return ERROR_COMMAND_TIMEOUT;
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("You are not authorized to perform this action.\n");
return ERROR_NO_ACCESS;
}
catch (InvalidOperationException opEx)
{
Win32Exception winEx = opEx.InnerException as Win32Exception;
if (winEx != null)
{
switch (winEx.NativeErrorCode)
{
case 5: //ERROR_ACCESS_DENIED
Console.WriteLine("You are not authorized to perform this action.\n");
return ERROR_NO_ACCESS;
case 1722: //RPC_S_SERVER_UNAVAILABLE
Console.WriteLine("The server is unavailable or does not exist.\n");
return ERROR_NO_SERVER;
case 1060: //ERROR_SERVICE_DOES_NOT_EXIST
Console.WriteLine("The service does not exist.\n");
return ERROR_NO_SERVICE;
case 1056: //ERROR_SERVICE_ALREADY_RUNNING
Console.WriteLine("The service is already running.\n");
return ERROR_INVALID_STATE;
case 1062: //ERROR_SERVICE_NOT_ACTIVE
Console.WriteLine("The service is not running.\n");
return ERROR_INVALID_STATE;
default:
break;
}
}
Console.WriteLine(opEx.ToString());
return ERROR_UNSPECIFIED;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return ERROR_UNSPECIFIED;
}
return ERROR_SUCCESS;
}
private static void ShowUsage()
{
Console.WriteLine("SCSync usage:\n");
Console.WriteLine("SCSync.exe service command <server> <timeout>\n");
Console.WriteLine(" service The name of the service upon which the command will act. (Required)");
Console.WriteLine(" command The command to execute - one of: start|stop|pause|continue. (Required)");
Console.WriteLine(" server The name of the server on which the target service runs. This must start with \\. (Optional)");
Console.WriteLine(" timeout The timeout period in seconds in which the command should finish. The default is 30 seconds. (Optional)");
Console.WriteLine("\n");
}
}
}
The WaitForStatus is just a polling loop and could be easily replaced in any other language. The rest is just OpenService and ControlService.
A: Eric Falsken's solution works perfectly. +1.
But I'd like to add that the timeout command would sometimes fail with error:
"Input redirection is not supported, exiting the process immediately"
To fix this I've had to replace the timeout command:
timeout /t 2 /nobreak >NUL
with the following:
ping -n 2 127.0.0.1 1>NUL
A: Edit on 10/20/2011 - updated my code. I posted it before fully debugging.
Many thanks to Eric Falsken. What a great solution. I tweaked Eric's code (BTW look for a couple of typographical errors if you intend to use it). I added logging and some additional error-checking for some conditions Eric didn't account for. Since I'm most interested in a service restart (not just stopping and/or starting), I only built upon Eric's restart code. Anyway, I'm posting my version, hope you like it!
@ECHO off
:: This script originally authored by Eric Falsken http://stackoverflow.com/
:: Revised for by George Perkins 10/20/2011
IF [%1]==[] GOTO Usage
IF [%2]==[] GOTO Usage
:SetLocalVariables
SET /A MyDelay=0
SET MyHours=%time:~0,2%
IF %MyHours%==0 SET MyHours=00
IF %MyHours%==1 SET MyHours=01
IF %MyHours%==2 SET MyHours=02
IF %MyHours%==3 SET MyHours=03
IF %MyHours%==4 SET MyHours=04
IF %MyHours%==5 SET MyHours=05
IF %MyHours%==6 SET MyHours=06
IF %MyHours%==7 SET MyHours=07
IF %MyHours%==8 SET MyHours=08
IF %MyHours%==9 SET MyHours=09
SET MyMinutes=%time:~3,2%
SET MySeconds=%time:~6,2%
SET MyHundredths=%time:~9,2%
SET MyMonth=%date:~4,2%
SET MyDay=%date:~-7,2%
SET MyCentury=%date:~-4,4%
SET MyTimeStamp=%MyCentury%%MyMonth%%MyDay%%MyHours%%MyMinutes%%MySeconds%
IF "%3" == "" (
SET MyLog=C:\Temp
) ELSE (
SET MyLog=%3
)
SET MyLogFile=%MyLog%\ServiceRestart%MyTimeStamp%.log
ECHO.
ECHO. >> %MyLogFile%
ECHO ------------- ------------- %MyHours%:%MyMinutes%:%MySeconds%.%MyHundredths% %MyMonth%/%MyDay%/%MyCentury% ------------- -------------
ECHO ------------- ------------- %MyHours%:%MyMinutes%:%MySeconds%.%MyHundredths% %MyMonth%/%MyDay%/%MyCentury% ------------- ------------- >> %MyLogFile%
ECHO Begin batch program %0.
ECHO Begin batch program %0. >> %MyLogFile%
ECHO Logging to file %MyLogFile%.
ECHO Logging to file %MyLogFile%. >> %MyLogFile%
ECHO Attempting to restart service %2 on computer %1.
ECHO Attempting to restart service %2 on computer %1. >> %MyLogFile%
PING -n 1 %1 | FIND "TTL=" >> %MyLogFile%
IF errorlevel 1 IF NOT errorlevel 2 GOTO SystemOffline
SC \\%1 query %2 | FIND "FAILED 1060" >> %MyLogFile%
IF errorlevel 0 IF NOT errorlevel 1 GOTO InvalidServiceName
SC \\%1 query %2 | FIND "STATE" >> %MyLogFile%
IF errorlevel 1 IF NOT errorlevel 2 GOTO SystemOffline
:ResolveInitialState
SET /A MyDelay+=1
SC \\%1 query %2 | FIND "STATE" | FIND "RUNNING" >> %MyLogFile%
IF errorlevel 0 IF NOT errorlevel 1 GOTO StopService
SC \\%1 query %2 | FIND "STATE" | FIND "STOPPED" >> %MyLogFile%
IF errorlevel 0 IF NOT errorlevel 1 GOTO StartService
SC \\%1 query %2 | FIND "STATE" | FIND "PAUSED" >> %MyLogFile%
IF errorlevel 0 IF NOT errorlevel 1 GOTO SystemOffline
ECHO Service State is changing, waiting %MyDelay% seconds for service to resolve its state before making changes.
ECHO Service State is changing, waiting %MyDelay% seconds for service to resolve its state before making changes. >> %MyLogFile%
TIMEOUT /t %MyDelay% /nobreak >> %MyLogFile%
GOTO ResolveInitialState
:StopService
SET /A MyDelay=0
ECHO Stopping %2 on \\%1.
ECHO Stopping %2 on \\%1. >> %MyLogFile%
SC \\%1 stop %2 | FIND "FAILED" >> %MyLogFile%
IF errorlevel 0 IF NOT errorlevel 1 GOTO Unstoppable
:StoppingServiceDelay
SET /A MyDelay+=1
IF %MyDelay%==21 GOTO MaybeUnStoppable
ECHO Waiting %MyDelay% seconds for %2 to stop.
ECHO Waiting %MyDelay% seconds for %2 to stop. >> %MyLogFile%
TIMEOUT /t %MyDelay% /nobreak >> %MyLogFile%
:StoppingService
SC \\%1 query %2 | FIND "STATE" | FIND "STOPPED" >> %MyLogFile%
IF errorlevel 0 IF NOT errorlevel 1 GOTO StoppedService
SC \\%1 query %2 | FIND "STATE" | FIND "STOP_PENDING" >> %MyLogFile%
IF errorlevel 0 IF NOT errorlevel 1 GOTO StoppingServiceDelay
GOTO StoppingServiceDelay
:MaybeUnStoppable
:: If we got here we waited approximately 3 mintues and the service has not stopped.
SC \\%1 query %2 | FIND "NOT_STOPPABLE" >> %MyLogFile%
IF errorlevel 0 IF NOT errorlevel 1 GOTO OneLastChance
GOTO Unstoppable
:OneLastChance
SC \\%1 stop %2 >> %MyLogFile%
SET /A MyDelay+=1
ECHO Waiting %MyDelay% seconds for %2 to stop.
ECHO Waiting %MyDelay% seconds for %2 to stop. >> %MyLogFile%
TIMEOUT /t %MyDelay% /nobreak >> %MyLogFile%
SC \\%1 query %2 | FIND "STATE" | FIND "STOPPED" >> %MyLogFile%
IF errorlevel 0 IF NOT errorlevel 1 GOTO StoppedService
SC \\%1 query %2 | FIND "STATE" | FIND "RUNNING" >> %MyLogFile%
IF errorlevel 1 IF NOT errorlevel 2 GOTO UnknownState
SC \\%1 query %2 | FIND "NOT_STOPPABLE" >> %MyLogFile%
IF errorlevel 0 IF NOT errorlevel 1 GOTO Unstoppable
GOTO StoppingServiceDelay
:StoppedService
ECHO %2 on \\%1 is stopped.
ECHO %2 on \\%1 is stopped. >> %MyLogFile%
GOTO StartService
:StartService
SET /A MyDelay=0
ECHO Starting %2 on \\%1.
ECHO Starting %2 on \\%1. >> %MyLogFile%
SC \\%1 start %2 >> %MyLogFile%
GOTO StartingService
:StartingServiceDelay
SET /A MyDelay+=1
ECHO Waiting %MyDelay% seconds for %2 to start.
ECHO Waiting %MyDelay% seconds for %2 to start. >> %MyLogFile%
TIMEOUT /t %MyDelay% /nobreak >> %MyLogFile%
:StartingService
SC \\%1 query %2 | FIND "STATE" | FIND "RUNNING" >> %MyLogFile%
IF errorlevel 1 IF NOT errorlevel 2 GOTO StartingServiceDelay
:StartedService
ECHO %2 on \\%1 is started.
ECHO %2 on \\%1 is started. >> %MyLogFile%
GOTO EndExit
:SystemOffline
ECHO Failure! Server \\%1 or service %2 is not accessible or is offline!
ECHO Failure! Server \\%1 or service %2 is not accessible or is offline! >> %MyLogFile%
ECHO See log file %MyLogFile% for details!
GOTO EndExit
:InvalidServiceName
ECHO Failure! Service %2 is not valid!
ECHO Failure! Service %2 is not valid! >> %MyLogFile%
ECHO See log file %MyLogFile% for details!
GOTO EndExit
:UnknownState
ECHO Failure! Service %2 in an unknown state and cannot be stopped!
ECHO Failure! Service %2 in an unknown state and cannot be stopped! >> %MyLogFile%
ECHO See log file %MyLogFile% for details!
GOTO EndExit
:UnStoppable
ECHO Failure! Service %2 cannot be stopped! Check dependencies or system state.
ECHO Failure! Service %2 cannot be stopped! Check dependencies or system state. >> %MyLogFile%
ECHO See log file %MyLogFile% for details!
GOTO EndExit
:Usage
ECHO Will restart a remote service, waiting for the service to stop/start (if necessary).
ECHO.
ECHO Usage:
ECHO %0 [system name] [service name] [logfile path]
ECHO Example: %0 server1 MyService C:\Temp\Log
ECHO.
GOTO EndExit
:EndExit
ECHO.
ECHO %0 Ended.
ECHO.
A: What about PowerShell and Restart-Service commandlet? :)
Get-Service W3SVC -computer myserver | Restart-Service
A: Eric Falsken's scripts are fantastic for this purpose. But note that they use the timeout command which is only available in Vista/Server2003 and newer. For an XP machine you can use sleep.exe from the NT Resource Kit instead. (This should be a commment to Eric's answer but not enough rep to do that).
A: I improved the script of Eric Falsken and revised by Gerorge Perkins.
Changes:
*
*now it is not only a restart script. The script can start, stop and restart a local or remote service;
*removed logging (if you want this, you can use it simply by launching SCRIPT_NAME.bat > logfile.txt);
*sparse optimizations.
@ECHO off
:: This script originally authored by Eric Falsken http://stackoverflow.com/
:: Revised by George Perkins 10/20/2011
:: Revised by Armando Contestabile 02/23/2015
IF "%1"=="" GOTO Usage
IF "%2"=="" GOTO Usage
SET ACTION=%1
SET SERVICENAME=%2
IF "%3"=="" (
SET SYSTEMNAME=%COMPUTERNAME%
) ELSE (
SET SYSTEMNAME=%3
)
IF "%ACTION%" == "stop" (
SET ACTION=STOP
) ELSE IF "%ACTION%" == "STOP" (
SET ACTION=STOP
) ELSE IF "%ACTION%" == "start" (
SET ACTION=START
) ELSE IF "%ACTION%" == "START" (
SET ACTION=START
) ELSE IF "%ACTION%" == "restart" (
SET ACTION=RESTART
) ELSE IF "%ACTION%" == "RESTART" (
SET ACTION=RESTART
) ELSE GOTO Usage
SET STATE=
SET CURRENT_STATUS=
SET /A DEFAULT_DELAY=5
SET /A SLEEP_COUNT=0
SET /A RESTARTED=0
SET /A MAX_WAIT_PERIODS=5
ECHO.
ECHO Attempting to %ACTION% service %SERVICENAME% on computer %SYSTEMNAME%.
PING -n 1 %SYSTEMNAME% | FIND "TTL=" >nul 2>&1
IF ERRORLEVEL 1 IF NOT ERRORLEVEL 2 (
ECHO Failure! Server \\%SYSTEMNAME% or service %SERVICENAME% is not accessible or is offline!
EXIT /B 1
)
SC \\%SYSTEMNAME% query %SERVICENAME% | FIND "FAILED 1060" >nul 2>&1
IF ERRORLEVEL 0 IF NOT ERRORLEVEL 1 (
ECHO Failure! Service %SERVICENAME% is not valid!
EXIT /B 2
)
SC \\%SYSTEMNAME% query %SERVICENAME% | FIND "STATE" >nul 2>&1
IF ERRORLEVEL 1 IF NOT ERRORLEVEL 2 (
ECHO Failure! Server \\%SYSTEMNAME% or service %SERVICENAME% is not accessible or is offline!
EXIT /B 3
)
:Dispatch
FOR /f "tokens=*" %%i IN ('SC \\%SYSTEMNAME% query %SERVICENAME% ^| FIND "STATE"') DO SET STATE=%%i
ECHO %STATE% | FINDSTR /C:"1" >nul
IF %ERRORLEVEL%==0 SET CURRENT_STATUS=STOPPED
ECHO %STATE% | FINDSTR /C:"2" >nul
IF %ERRORLEVEL%==0 SET CURRENT_STATUS=START_PENDING
ECHO %STATE% | FINDSTR /C:"3" >nul
IF %ERRORLEVEL%==0 SET CURRENT_STATUS=STOP_PENDING
ECHO %STATE% | FINDSTR /C:"4" >nul
IF %ERRORLEVEL%==0 SET CURRENT_STATUS=RUNNING
ECHO %STATE% | FINDSTR /C:"5" >nul
IF %ERRORLEVEL%==0 SET CURRENT_STATUS=CONTINUE_PENDING
ECHO %STATE% | FINDSTR /C:"6" >nul
IF %ERRORLEVEL%==0 SET CURRENT_STATUS=PAUSE_PENDING
ECHO %STATE% | FINDSTR /C:"7" >nul
IF %ERRORLEVEL%==0 SET CURRENT_STATUS=PAUSED
ECHO Current status of service is %CURRENT_STATUS%
IF NOT "%CURRENT_STATUS%"=="RUNNING" IF NOT "%CURRENT_STATUS%"=="STOPPED" IF NOT "%CURRENT_STATUS%"=="PAUSED" (
IF "%SLEEP_COUNT%"=="%MAX_WAIT_PERIODS%" (
ECHO Service state won't change. Script exececution is canceled.
EXIT /B 4
)
ECHO Service State is changing, waiting %DEFAULT_DELAY% seconds...
SLEEP %DEFAULT_DELAY%
SET /A SLEEP_COUNT+=1
GOTO Dispatch
)
IF "%ACTION%"=="START" (
IF "%CURRENT_STATUS%"=="RUNNING" (
ECHO Service %SERVICENAME% is running.
GOTO EndExit
) ELSE (
GOTO StartService
)
) ELSE IF "%ACTION%"=="RESTART" (
IF "%CURRENT_STATUS%"=="RUNNING" (
IF %RESTARTED%==1 (
ECHO Service %SERVICENAME% restarted.
GOTO EndExit
)
SET /A SLEEP_COUNT=0
GOTO StopService
) ELSE (
SET /A RESTARTED=1
GOTO StartService
)
) ELSE IF "%ACTION%"=="STOP" (
IF "%CURRENT_STATUS%"=="STOPPED" (
ECHO Service %SERVICENAME% is stopped.
GOTO EndExit
) ELSE (
GOTO StopService
)
)
:StartService
ECHO Starting %SERVICENAME% on \\%SYSTEMNAME%
SC \\%SYSTEMNAME% start %SERVICENAME% >nul 2>&1
SET SLEEP_COUNT=0
GOTO Dispatch
:StopService
ECHO Stopping %SERVICENAME% on \\%SYSTEMNAME%
SC \\%SYSTEMNAME% stop %SERVICENAME% >nul 2>&1
SET SLEEP_COUNT=0
GOTO Dispatch
:Usage
ECHO This script can start/stop/restart a local or remote service, waiting for the service to stop/start ^(if necessary^).
ECHO.
ECHO Usage:
ECHO %0 ^<start^|stop^|restart^> ^<SERVICE^> [SYSTEM]
ECHO.
ECHO If no SYSTEM is provided, the script attempts to execute on the local system.
EXIT /B 5
:EndExit
ECHO.
EXIT /B 0
A: I created a set of batch scripts that use sc.exe to do just this. They are attached below. To run these scripts, you should be a user with administration rights on the target machine and running this from a computer that is a member of the same domain. It's possible to set it up to be able to run from outside of the domain (like from a VPN) but there are a lot of layers of security to work through involving firewalls, DCOM and security credentials.
One of these days, I'm going to figure out the PowerShell equivalent, which should be much easier.
safeServiceStart.bat
@echo off
:: This script originally authored by Eric Falsken
IF [%1]==[] GOTO usage
IF [%2]==[] GOTO usage
ping -n 1 %1 | FIND "TTL=" >NUL
IF errorlevel 1 GOTO SystemOffline
SC \\%1 query %2 | FIND "STATE" >NUL
IF errorlevel 1 GOTO SystemOffline
:ResolveInitialState
SC \\%1 query %2 | FIND "STATE" | FIND "STOPPED" >NUL
IF errorlevel 0 IF NOT errorlevel 1 GOTO StartService
SC \\%1 query %2 | FIND "STATE" | FIND "RUNNING" >NUL
IF errorlevel 0 IF NOT errorlevel 1 GOTO StartedService
SC \\%1 query %2 | FIND "STATE" | FIND "PAUSED" >NUL
IF errorlevel 0 IF NOT errorlevel 1 GOTO SystemOffline
echo Service State is changing, waiting for service to resolve its state before making changes
sc \\%1 query %2 | Find "STATE"
timeout /t 2 /nobreak >NUL
GOTO ResolveInitialState
:StartService
echo Starting %2 on \\%1
sc \\%1 start %2 >NUL
GOTO StartingService
:StartingServiceDelay
echo Waiting for %2 to start
timeout /t 2 /nobreak >NUL
:StartingService
SC \\%1 query %2 | FIND "STATE" | FIND "RUNNING" >NUL
IF errorlevel 1 GOTO StartingServiceDelay
:StartedService
echo %2 on \\%1 is started
GOTO:eof
:SystemOffline
echo Server \\%1 is not accessible or is offline
GOTO:eof
:usage
echo %0 [system name] [service name]
echo Example: %0 server1 MyService
echo.
GOTO:eof
safeServiceStop.bat
@echo off
:: This script originally authored by Eric Falsken
IF [%1]==[] GOTO usage
IF [%2]==[] GOTO usage
ping -n 1 %1 | FIND "TTL=" >NUL
IF errorlevel 1 GOTO SystemOffline
SC \\%1 query %2 | FIND "STATE" >NUL
IF errorlevel 1 GOTO SystemOffline
:ResolveInitialState
SC \\%1 query %2 | FIND "STATE" | FIND "RUNNING" >NUL
IF errorlevel 0 IF NOT errorlevel 1 GOTO StopService
SC \\%1 query %2 | FIND "STATE" | FIND "STOPPED" >NUL
IF errorlevel 0 IF NOT errorlevel 1 GOTO StopedService
SC \\%1 query %2 | FIND "STATE" | FIND "PAUSED" >NUL
IF errorlevel 0 IF NOT errorlevel 1 GOTO SystemOffline
echo Service State is changing, waiting for service to resolve its state before making changes
sc \\%1 query %2 | Find "STATE"
timeout /t 2 /nobreak >NUL
GOTO ResolveInitialState
:StopService
echo Stopping %2 on \\%1
sc \\%1 stop %2 %3 >NUL
GOTO StopingService
:StopingServiceDelay
echo Waiting for %2 to stop
timeout /t 2 /nobreak >NUL
:StopingService
SC \\%1 query %2 | FIND "STATE" | FIND "STOPPED" >NUL
IF errorlevel 1 GOTO StopingServiceDelay
:StopedService
echo %2 on \\%1 is stopped
GOTO:eof
:SystemOffline
echo Server \\%1 or service %2 is not accessible or is offline
GOTO:eof
:usage
echo Will cause a remote service to STOP (if not already stopped).
echo This script will waiting for the service to enter the stopped state if necessary.
echo.
echo %0 [system name] [service name] {reason}
echo Example: %0 server1 MyService
echo.
echo For reason codes, run "sc stop"
GOTO:eof
safeServiceRestart.bat
@echo off
:: This script originally authored by Eric Falsken
if [%1]==[] GOTO usage
if [%2]==[] GOTO usage
ping -n 1 %1 | FIND "TTL=" >NUL
IF errorlevel 1 GOTO SystemOffline
SC \\%1 query %2 | FIND "STATE" >NUL
IF errorlevel 1 GOTO SystemOffline
:ResolveInitialState
SC \\%1 query %2 | FIND "STATE" | FIND "RUNNING" >NUL
IF errorlevel 0 IF NOT errorlevel 1 GOTO StopService
SC \\%1 query %2 | FIND "STATE" | FIND "STOPPED" >NUL
IF errorlevel 0 IF NOT errorlevel 1 GOTO StartService
SC \\%1 query %2 | FIND "STATE" | FIND "PAUSED" >NUL
IF errorlevel 0 IF NOT errorlevel 1 GOTO SystemOffline
echo Service State is changing, waiting for service to resolve its state before making changes
sc \\%1 query %2 | Find "STATE"
timeout /t 2 /nobreak >NUL
GOTO ResolveInitialState
:StopService
echo Stopping %2 on \\%1
sc \\%1 stop %2 %3 >NUL
GOTO StopingService
:StopingServiceDelay
echo Waiting for %2 to stop
timeout /t 2 /nobreak >NUL
:StopingService
SC \\%1 query %2 | FIND "STATE" | FIND "STOPPED" >NUL
IF errorlevel 1 GOTO StopingServiceDelay
:StopedService
echo %2 on \\%1 is stopped
GOTO StartService
:StartService
echo Starting %2 on \\%1
sc \\%1 start %2 >NUL
GOTO StartingService
:StartingServiceDelay
echo Waiting for %2 to start
timeout /t 2 /nobreak >NUL
:StartingService
SC \\%1 query %2 | FIND "STATE" | FIND "RUNNING" >NUL
IF errorlevel 1 GOTO StartingServiceDelay
:StartedService
echo %2 on \\%1 is started
GOTO:eof
:SystemOffline
echo Server \\%1 or service %2 is not accessible or is offline
GOTO:eof
:usage
echo Will restart a remote service, waiting for the service to stop/start (if necessary)
echo.
echo %0 [system name] [service name] {reason}
echo Example: %0 server1 MyService
echo.
echo For reason codes, run "sc stop"
GOTO:eof
A: What about powershell and WaitForStatus? Eg, the script below would restart SQL Server on a remote machine:
$computer = "COMPUTER_NAME"
$me = new-object -typename System.Management.Automation.PSCredential -argumentlist "DOMAIN\user", (convertto-securestring "password" -asplaintext -force)
$restartSqlServer = {
$sqlServer = get-service mssqlserver
$waitInterval = new-timespan -seconds 5
if (-not ($sqlServer.Status -eq "Stopped")) {
$sqlServer.Stop()
$sqlServer.WaitForStatus('Stopped', $waitInterval)
}
$sqlServer.Start()
$sqlServer.WaitForStatus('Running', $waitInterval)
}
icm -ComputerName $computer -ScriptBlock $restartSqlServer -Credential $me
A: I've made a minor change to the script, so that it is running under Windows 10 or similar Versions.
The command "sleep" was replaced with the command "timeout".
@ECHO off
:: This script originally authored by Eric Falsken http://stackoverflow.com/
:: Revised by George Perkins 10/20/2011
:: Revised by Armando Contestabile 02/23/2015
:: Revised by Sascha Jelinek 11/13/2020
IF "%1"=="" GOTO Usage
IF "%2"=="" GOTO Usage
SET ACTION=%1
SET SERVICENAME=%2
IF "%3"=="" (
SET SYSTEMNAME=%COMPUTERNAME%
) ELSE (
SET SYSTEMNAME=%3
)
IF "%ACTION%" == "stop" (
SET ACTION=STOP
) ELSE IF "%ACTION%" == "STOP" (
SET ACTION=STOP
) ELSE IF "%ACTION%" == "start" (
SET ACTION=START
) ELSE IF "%ACTION%" == "START" (
SET ACTION=START
) ELSE IF "%ACTION%" == "restart" (
SET ACTION=RESTART
) ELSE IF "%ACTION%" == "RESTART" (
SET ACTION=RESTART
) ELSE GOTO Usage
SET STATE=
SET CURRENT_STATUS=
SET /A DEFAULT_DELAY=5
SET /A SLEEP_COUNT=0
SET /A RESTARTED=0
SET /A MAX_WAIT_PERIODS=5
ECHO.
ECHO Attempting to %ACTION% service %SERVICENAME% on computer %SYSTEMNAME%.
PING -n 1 %SYSTEMNAME% | FIND "Antwort von" >nul 2>&1
IF ERRORLEVEL 1 IF NOT ERRORLEVEL 2 (
ECHO Failure!! Server \\%SYSTEMNAME% or service %SERVICENAME% is not accessible or is offline!
EXIT /B 1
)
SC \\%SYSTEMNAME% query %SERVICENAME% | FIND "FAILED 1060" >nul 2>&1
IF ERRORLEVEL 0 IF NOT ERRORLEVEL 1 (
ECHO Failure! Service %SERVICENAME% is not valid!
EXIT /B 2
)
SC \\%SYSTEMNAME% query %SERVICENAME% | FIND "STATE" >nul 2>&1
IF ERRORLEVEL 1 IF NOT ERRORLEVEL 2 (
ECHO Failure! Server \\%SYSTEMNAME% or service %SERVICENAME% is not accessible or is offline!
EXIT /B 3
)
:Dispatch
FOR /f "tokens=*" %%i IN ('SC \\%SYSTEMNAME% query %SERVICENAME% ^| FIND "STATE"') DO SET STATE=%%i
ECHO %STATE% | FINDSTR /C:"1" >nul
IF %ERRORLEVEL%==0 SET CURRENT_STATUS=STOPPED
ECHO %STATE% | FINDSTR /C:"2" >nul
IF %ERRORLEVEL%==0 SET CURRENT_STATUS=START_PENDING
ECHO %STATE% | FINDSTR /C:"3" >nul
IF %ERRORLEVEL%==0 SET CURRENT_STATUS=STOP_PENDING
ECHO %STATE% | FINDSTR /C:"4" >nul
IF %ERRORLEVEL%==0 SET CURRENT_STATUS=RUNNING
ECHO %STATE% | FINDSTR /C:"5" >nul
IF %ERRORLEVEL%==0 SET CURRENT_STATUS=CONTINUE_PENDING
ECHO %STATE% | FINDSTR /C:"6" >nul
IF %ERRORLEVEL%==0 SET CURRENT_STATUS=PAUSE_PENDING
ECHO %STATE% | FINDSTR /C:"7" >nul
IF %ERRORLEVEL%==0 SET CURRENT_STATUS=PAUSED
ECHO Current status of service is %CURRENT_STATUS%
IF NOT "%CURRENT_STATUS%"=="RUNNING" IF NOT "%CURRENT_STATUS%"=="STOPPED" IF NOT "%CURRENT_STATUS%"=="PAUSED" (
IF "%SLEEP_COUNT%"=="%MAX_WAIT_PERIODS%" (
ECHO Service state won't change. Script exececution is canceled.
EXIT /B 4
)
ECHO Service State is changing, waiting %DEFAULT_DELAY% seconds...
TIMEOUT /t %DEFAULT_DELAY% /NOBREAK
SET /A SLEEP_COUNT+=1
GOTO Dispatch
)
IF "%ACTION%"=="START" (
IF "%CURRENT_STATUS%"=="RUNNING" (
ECHO Service %SERVICENAME% is running.
GOTO EndExit
) ELSE (
GOTO StartService
)
) ELSE IF "%ACTION%"=="RESTART" (
IF "%CURRENT_STATUS%"=="RUNNING" (
IF %RESTARTED%==1 (
ECHO Service %SERVICENAME% restarted.
GOTO EndExit
)
SET /A SLEEP_COUNT=0
GOTO StopService
) ELSE (
SET /A RESTARTED=1
GOTO StartService
)
) ELSE IF "%ACTION%"=="STOP" (
IF "%CURRENT_STATUS%"=="STOPPED" (
ECHO Service %SERVICENAME% is stopped.
GOTO EndExit
) ELSE (
GOTO StopService
)
)
:StartService
ECHO Starting %SERVICENAME% on \\%SYSTEMNAME%
SC \\%SYSTEMNAME% start %SERVICENAME% >nul 2>&1
SET SLEEP_COUNT=0
GOTO Dispatch
:StopService
ECHO Stopping %SERVICENAME% on \\%SYSTEMNAME%
SC \\%SYSTEMNAME% stop %SERVICENAME% >nul 2>&1
SET SLEEP_COUNT=0
GOTO Dispatch
:Usage
ECHO This script can start/stop/restart a local or remote service, waiting for the service to stop/start ^(if necessary^).
ECHO.
ECHO Usage:
ECHO %0 ^<start^|stop^|restart^> ^<SERVICE^> [SYSTEM]
ECHO.
ECHO If no SYSTEM is provided, the script attempts to execute on the local system.
EXIT /B 5
:EndExit
ECHO.
EXIT /B 0
A: NET START and NET STOP shouldn't return until the service has indicated that the service has started or stopped successfully.
A: I don't believe you can do this with a straight dos command. You might check Code Project or other similar sites to see if there's a custom solution for this already.
If not, you could write a secondary Windows service that does this for you by exposing the start/stop functionality through a WCF endpoint. To access this secondary service remotely, you could write a simple console app that connects to this service to start/stop the Windows service in question. Since it's a console app, it would mimic the desired behavior of working from the command line and not returning until complete (or an error occurred). It's not the straightforward, simple solution you're looking for, but I'll throw it out there for consideration.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1405372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "70"
}
|
Q: Facebook SDK project with Errors After following these steps: http://developers.facebook.com/docs/mobile/android/build/
I find that everything goes well, but when I create the new Facebook SDK project (Step 3), which I add from here: https://github.com/facebook/facebook-android-sdk
The project is full of errors in Eclipse when I open it. For example, here is one of many:
Multiple markers at this line
- Line breakpoint:Facebook [line: 621] - logout(Context)
- The method clearCookies(Context) from the type Util refers to the missing type
I added this when creating the project: facebook-facebook-android-sdk-1f0b0ea\facebook
That's what the instructions say ... add that for the sdk. The errors are in Facebook.java, FbDialog.java, and Util.java. Is this normal? What do other people do when they have the same issue?
Also, when I added the reference to the Facebook SDK to my Android app project, the root folder in Eclipse has a red exclamation mark on it. What does that mean?
A: Eclipse > Right-click project > Properties > Java Compiler > Compiler compliance level > 1.6
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9677418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Installation for SQLAlchemy Doesn't link to Flask I am trying to install SQLAlchemy on a Windows 8 64 bit machine for Python 2.7
When I run the setup.py file that comes with the download from the SQLAlchemy site, a .egg file called 'SQLAlchemy-1.0.0-py2.7.egg' is placed in C:\Python27\Lib\site-packages.
But when I try to do a basic import of the library using an import statement on given in the SQLAlchemy documentation, I get an error message.
The import code is:
from flask.ext.sqlalchemy import SQLAlchemy
And the error message I get is:
c:\Users\Me\MyCode>ws_dbwrite.py
Traceback (most recent call last):
File "C:\Users\Me\MyCode\ws_dbwrite.py", line 2, in <module>
from flask.ext.sqlalchemy import SQLAlchemy
File "C:\Python27\lib\site-packages\flask-0.10.1-py2.7.egg\flask\exthook.py",
line 87, in load_module
raise ImportError('No module named %s' % fullname)
ImportError: No module named flask.ext.sqlalchemy
Should I be going about installation in a different manner? Or should the .egg file for SQLAlchemy go at a different file level? Or am I missing something obvious here?
Edit: If I change the import line to just
import SQLAlchemy
The import works, but Python does not recognize things like
db = SQLAlchemy(app)
as valid commands.
A: You have installed SQLAlchemy, but you are trying to use the Flask extension, Flask-SQLAlchemy. While the two are related, they are separate libraries. In order to use
from flask.ext.sqlalchemy import SQLAlchemy
you need to install it first.
pip install Flask-SQLAlchemy
(You installed SQLAlchemy directly from source. You can also do that for Flask-SQLAlchemy.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29722895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Casting a generic class I have a class of the following type:
class OptionViewModel<T: SelectableOption>: ViewModel
At some other point I need to be able to do something like the following:
func configure(viewModel: ViewModel) {
guard let model = model as? OptionViewModel else { return }
}
I don't care at this point what the generic type is (only that it conforms to the protocol) but I can't get this line to compile due to having to supply a concrete type here (which I don't know - currently I have 4 possibilities).
Generic parameter 'T' could not be inferred in cast to 'OptionViewModel'
I'm looking for any suggestions on how to restructure this, or get around my issue. Thanks!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68242201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Return first XElement in node with greatest number of fields LINQ gurus, I have a quick one.
Say I have the following XML document:
<?xml version="1.0" encoding="utf-8"?>
<xamDataPresenter version="12.1.20121.1010" formatVersion="1.6">
<fieldLayouts>
<fieldLayout key="ems:airportsType" >
<fields>
<field name="IKO" />
<field name="Name" />
<field name="the_geom" />
<field name="DistanceKm" />
<field name="DistanceNm" />
</fields>
<recordFilters />
</fieldLayout>
<fieldLayout key="ems:airportsType" >
<fields>
<field name="IKO"/>
<field name="na3" />
<field name="Name"/>
<field name="Type"/>
<field name="the_geom"/>
<field name="Mod_time" />
<field name="Country" />
<field name="Operator"/>
<field name="Contact"/>
<field name="DistanceKm"/>
<field name="DistanceNm"/>
</fields>
<recordFilters />
</fieldLayout>
......
</fieldLayouts>
</xamDataPresenter>
What is the LINQ syntax I use to get the fieldLayout node with the most field elements?
A: var res = XDocument.Load(filename)
.Descendants("fieldLayout")
.OrderByDescending(x => x.Descendants("field").Count())
.First();
A: var fieldLayout = xDoc.Root
.Element("FieldLayout")
.Elements("fieldLayout")
.OrderByDescending(fl => fl.Element("fields")
.Elements("field")
.Count())
.First();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21415877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ActiveAdmin giving timeout error in Heroku When I try to access ActiveAdmin in local in my rails app, it loads way to slowly, and when pushing to heroku and trying to access my admin panel, it will give Application Error.
In my logs, I have:
2014-07-09T11:27:13.175216+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=POST path="/admin/login" host=myapp.herokuapp.com request_id=30b8a647-6c82-4af5-b9a1-2d0eb3ecfa67 fwd="" dyno=web.1 connect=0 service=30003 status=503 bytes=1644
2014-07-09T11:55:12.294230+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=POST path="/admin/login" host=myapp.herokuapp.com request_id=9b5c462a-6d8e-4f67-b19f-307d732ab4ca fwd="" dyno=web.1 connect=1 service=30002 status=503 bytes=1644
What can it be? I can't get it to work :(
A: Mostly it's a problem with to big association filters.
Disable the auto created filters and reenable them one by one, to find the problem filter.
This will help you if your filter is not to big:
filter :foo, as: :select, collection: Foo.pluck(:name, :id)
(but works only for rails > 4.0, you can build a similar thing by hand in rails 3.x)
A: Yes, this is usualy because of auto created filters, you can disable filters by:
remove_filter :some_param
Also you can eager-load some association with include in scoped collection, and if you have a huge count of records may be it can help to set:
index pagination_total: false
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24653099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Unable to create service reference for wsdl file I have wsdl file and xsd files at my local machine. I want to add service reference in project. I don't have web service I only have wsdl file.
I'm getting the following error:
The document was understood, but it could not be processed.
- The WSDL document contains links that could not be resolved.
- There was an error downloading 'http://localhost/DService/AllService.svc?xsd=xsd0'.
- The request failed with HTTP status 404: Not Found.
A: Your setup is complete with a wsdl file and a couple of xsd files.
The reason you're having that problem is because the link 'http://localhost/DService/AllService.svc?xsd=xsd0'. is broken.
The solution is to search the folder that has the xsd files for AllService .
To make it easier, place all the files in a single folder. Next is that you copy the absolute path to the file that contain the search phrase AllService, replace the localhost url with the absolute path to the file.
Run the command again and watch it work.
Note: Do not remove the url as this is essential in making your complete proxy.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28828511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: What regex expression can replace every other word? Given the following sentence: Crazy Fredrick bought many very exquisite opal jewels., what regex expression would allow me to filter out every other word? I am doing my replace like this:
"Crazy Fredrick bought many very exquisite opal jewels.".replace(/regex goes here/gi, "replace string goes here")
So I want to create a regex expression that will turn that sentence into either Fredrick many exquisite jewels. or crazy bought very opal.
A: Could use the following (assumes your words are all matched by \w)
"Crazy Fredrick bought many very exquisite opal jewels.".replace(/(\w+) (\w+)/g, '$1');
-> "Crazy bought very opal."
Replacing $1 with $2 gives you:
"Fredrick many exquisite jewels."
A: Not sure if RegEx is the right tool, but you could split the string by space into an array and then use filter to remove the odd or even elements:
var s = "Crazy Fredrick brought many very exquisite opal jewels";
s.split(/\s+/)
.filter(function (_, index) {
return index % 2 !== 0; // only want "odd" words
}).join(" ");
// yields "Fredrick many exquisite jewels"
A: Not the best solution, but you can try using these regexes:
\b\S+\b\s?(?=((\b\S+\b\s?){2})*\.?$)
\b\S+\b\s?(?=\b\S+\b\s?((\b\S+\b\s?){2})*\.?$)
Explanation and demonstration here: http://regex101.com/r/kR3hS5
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21579641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why am I getting a CSRF 403 from OAuth2 Proxy when running on GKE but not locally? I have a simple setup that is using OAuth2 Proxy to handle authentication. It works fine locally using minikube but when I try to use GKE when the oauth callback happens I get a 403 status and the the following message...
Login Failed: Unable to find a valid CSRF token. Please try again.
The offending url is http://ourdomain.co/oauth2/callback?code=J_6ao0AxSBRn4bwr&state=r_aFqM9wsSpPvyKyyzE_nagGnpNKUp1pLyZafOEO0go%3A%2Fip
What should be configured differently to avoid the CSRF error?
A: In my case it was because I needed to set the cookie to secure = false. Apparently I could still have secure true no problem with http and an IP but once I uploaded with a domain it failed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71353947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Centering images horizontally in container div when height is set to 100% Sorry if this has been answered - I've tried virtually all the tips I've already come across so far on centering images without any luck. This image just refuses to center horizontally!
JSFiddle here
HTML: (Note: images are note mine, just taken from google as examples)
Each image either receives "height:100%;" or "width:100%;" when loading depending on whether the height to width ratio is within or outside of the 4:3 ratio in landscape orientation.
This is done to ensure the image completely fills the containing div no matter what size and shape it is.
<div class="imgOuter">
<div class="imgInner">
<img src="http://www.woroni.com.au/wp-content/uploads/2013/12/Cars-Lamborghini-Free-Wallpaper.jpg" style="height: 100%;">
</div>
</div>
<div class="imgOuter">
<div class="imgInner">
<img src="http://cdn.acidcow.com/pics/20100118/celebrity_portraits_by_tom_munro_03.jpg" style="width: 100%;">
</div>
</div>
CSS:
The main outer div is set to conform to the constant aspect ratio of 4:3
The inner div adds a border internally to the outer div which must remain specifically sized.
div.imgOuter{
float: left;
position: relative;
width: 33.3333%;
padding-bottom: 25%;
overflow:hidden;
clear:none;
}
div.imgInner{
position:absolute;
top:0;bottom:0;left:0;right:0;
overflow:hidden;
text-align:center;
border:2px solid #444;
cursor:pointer;
}
div.imgInner>img{
display:block;
position:absolute;
top:0;bottom:0;left:0;right:0;
margin:auto;
}
.imgInner: I have tried text-align:center; tried additionally dimensioning with height and width @ 100%...
You'll notice in the fiddle that the second image is in a portrait orientation and sits perfectly as expected centered vertically.
If you take a landscape image and set the width to 100% instead of height, it also centers vertically without issue, leaving white space above and below its ratio is wider than 4:3.
Only when the height is 100% does the image default to left alignment seemingly ignoring the left and right positioning.
My only suspicion is that the div.imgOuter does not have a height, only a padding value. If thats the case then I'm stuck attempting to solve both scaling aspect ratios and center alignment :(
Any suggestions?
A: Fairly sure you can't do this with CSS alone--because any negative margin workarounds for horizontal and vertical centering only works when you can used fixed sizes (as using a negative percentage margin will take the percentage from the parent container rather than the element's original size.)
However, you can do this with JS.
http://jsfiddle.net/HkuMW/7/
So, we apply the percentage left and top to sit exactly in the middle (but from the image's top-left corner):
div.imgInner>img {
display:block;
position:absolute;
top:50%;
left:50%;
}
Then we use jQuery to re-position the image by finding out the exact pixel dimensions, halving it, and popping that in:
$('.imgInner > img').each(function (i) {
var imgWidth = ((0 - parseInt($(this).css('width'))) / 2);
var imgHeight = ((0 - parseInt($(this).css('height'))) / 2);
$(this).css('margin-top', imgHeight);
$(this).css('margin-left', imgWidth);
});
A: See if this answers your question.
http://jsfiddle.net/HkuMW/17/
You can change the background-size:100% auto; to background-size:auto 100%; if you need to swap the resizing method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21034319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: i want to formate date using jquery or javascript I just want to know how can i format date in java script.
I have date string is.
2015-04-21T09:31:04+05:00
I need to convert this 21 April, 2015
Can any one help me ?
Thanks
A: Use JavaScript Date object.
var date = new Date("2015-04-21T09:31:04+05:00");
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
console.log(date.getDate() + ' ' + months[date.getMonth()] + ', ' + date.getFullYear());
A: If you are open to libraries and you plan to "heavily" use Date you have MomentJS which would do it easily:
moment().format('MMMM Do YYYY'); // April 22nd 2015
//or
moment("2015-04-21T09:31:04+05:00").format('MMMM Do YYYY'); // April 21nd 2015
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29791137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Deserialize/Parse JSON in Java I am searching a good and dynamic way to parse JSON in Java.
I've seen things such as:
List<String> list = new ArrayList<String>();
JSONArray array = obj.getJSONArray("test");
for(int i = 0 ; i < array.length() ; i++){
list.add(array.getJSONObject(i).getString("testKey"));
}
But that's not what I'm searching. In C# I had something like that:
dynamic results = JsonConvert.DeserializeObject<dynamic>(json);
info.Text = results["test"]["testKey"];
Here's an example of my JSON:
{"date":"07.05.2017 11:44",
"monday":{"1":{"subject":"test","room":"test","status":"test"}}}
So for example I would like to make:
results["monday"]["1"]["subject"];
I hope someone understands my problem and can help me.
Thanks in advance!
A: The core Java runtime does not offer a JSON parser (edit: technically, it does, see bottom of answer), so you will need a library. See Jackson, Gson, perhaps others.
Even with that, you will not get the dynamic features you want, because Java is statically typed. Example with Jackson:
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(json, new TypeReference<Map<String, Object>>(){});
map.get("monday").get("1").get("subject");
^^^
This fails because the result of get("monday") is Object, not Map
The "right" approach in Java-land, would be to create a class (or set of classes) that represents your JSON model, and pass it to the JSON parser's "object mapper". But you said "dynamic" so I'm not exploring this here.
So you'll need to cast to Map when you know it's not primitive values:
((Map<String,Map<String,String>>)map.get("monday")).get("1").get("subject");
This works but with a warning about unchecked cast...
All in all, Java is not a dynamic language and I see no way to do exactly what you want (perhaps I'm missing approaches that are still slightly easier than what I have suggested).
Are you limited to Java-the-language or Java-the-platform? In the latter case you can use a dynamic language for the Java platform, such as Groovy, who has excellent features to parse JSON.
EDIT: a funny alternative is to use Java's own JavaScript implementation. This works and is easy and dynamic, but I don't know if it's "good":
String json = "{\"date\":\"07.05.2017 11:44\",\n" +
"\"monday\":{\"1\":{\"subject\":\"test\",\"room\":\"test\",\"status\":\"test\"}}}";
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.put("data", json);
System.out.println(engine.eval("JSON.parse(data)['monday']['1']['subject']"));
A: If you are sure about the value you want to get then you can do following as well :
String str = "{\"date\":\"07.05.2017 11:44\", \"monday\":{\"1\":{\"subject\":\"test\",\"room\":\"test\",\"status\":\"test\"}}}";
JSONObject results= new JSONObject(str);
String str1 = results.getJSONObject("monday").getJSONObject("1").getString("subject");
System.out.println(str1);
For array kind of results, we have to write logic for that. In this case org.json library is used.
A: You can use GCON library:
https://github.com/google/gson
Very good for parsing JSON objects.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43830111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the proper way to write assert statements in javascript in development that is meant to be easily stripped away in production? There are functions and methods in my javascript code base that need to have assert statements to check for invalid arguments passed in. But these assertion statements should be stripped away when in production.
How are these assertion statements written in modern ES6 in development and how are they stripped away in production?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73256625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: multiple instances of the same sound on iOS i'm making a bubble popping game and hit a bit of a snag :/
i have a sound (pop.mp3), this sound needs to play EVERY time one of the bubbles are tapped
all the bubbles are buttons that call the same method (-(IBACTION)bubblePop)
i initialised an AVAudioPlayer in the Viewdidload method
and call it's play function inside the bubblePop method
this clearly did not work however because the bubble's pop sound only plays one at a time, it doest overlap like i would expect it to
does anybody know how i can resolve this?
Extra info
if i initialise the audio player inside bubblePop i get no sound at all
A: You should initialize AVPlayer inside bubblePop and keep strong reference to it.
Try this:
@interface ViewController()
@property (strong, nonatomic) NSMutableDictionary *players;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.players = [[NSMutableDictionary alloc] init];
}
- (void)bubblePop {
NSURL *URL = your sound URL;
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:URL];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(itemDidFinishPlaying:) name:AVPlayerItemDidPlayToEndTimeNotification object:playerItem];
AVPlayer *player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
self.players[playerItem] = player;
[player play];
}
-(void)itemDidFinishPlaying:(AVPlayerItem *)sender {
[self.players removeObjectForKey:sender];
}
@end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19610439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Entity framework - Return to list error? I got the problem - return to list from the entity framework. I need to return as a object. Here is my code:
Public Function GetHardwareDetail() As List(Of HardwareDetailApp)
Dim idList As New List(Of String)
Dim Data = (From p In DB.TT_HARDWARE Select New HardwareDetailApp With {.InternalNum = p.INTERNAL_NUM, .Description = p.DESCRIPTION, .TerminalModel = p.HARDWARE_MODEL, .HardwareInternalNum = p.HARDWARE_ID, .Status = p.ISACTIVE, .Firmware = Nothing, .SerialNum = Nothing})
If Data.Count > 0 Then
For Each row In Data
idList.Add(row.InternalNum)
Next
End If
Dim Data2 = (From p In DB.TT_TERMINAL_HARDWARE Where idList.Contains(p.HARDWARE_INTERNAL_NUM)
Select New HardwareDetailApp With
{.Firmware = p.HARDWARE_FIRMWARE, .SerialNum = p.HARDWARE_SERIAL_NUM, .InternalNum = Data.FirstOrDefault.InternalNum, .Description = Data.FirstOrDefault.Description, .TerminalModel = Data.FirstOrDefault.TerminalModel, .HardwareInternalNum = Data.FirstOrDefault.HardwareInternalNum, .Status = Data.FirstOrDefault.Status})
Return Data2.ToList
End Function
This is the error which I get:
The type 'HardwareDetailApp' appears in two
structurally incompatible initializations within a single LINQ to
Entities query. A type can be initialized in two places in the same
query, but only if the same properties are set in both places and
those properties are set in the same order.
A: in your code, you have created from HardwareDetailApp in two place, in every creation of that you must set the same property with same order.
for example if in linq to entity you Select something like:
Place1:
...
Select new MyClass()
{
PropA: 1,
}
...
and in that query you need to another Select from MyClass but with some other properties like PropB, Like:
Place2:
...
Select new MyClass()
{
PropB: 2,
}
...
you must change all Select from MyClass into same, and set the properties you dont need to them, to its default, and set the properties in same order like:
Place1:
...
Select new MyClass()
{
PropA: 1,
PropB: default(int),
}
...
and
Place2:
...
Select new MyClass()
{
PropA: default(int),
PropB: 2,
}
...
my codes are in c#..
in this part of your code Dim Data = (From p In DB.TT_HARDW .... try to set Firmware and SerialNum at first like the second select, (i have not checked other properties carefully)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22291410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Asp.Net MVC and Strategy pattern I have an MVC application that uses Entity Framework. I am using a repository, unit of work and unity as dependency injection.
The problem I have is that I have different authentication types, and each type I want a different class, so I decided to use the Strategy pattern
public interface IAuthStrategy
{
OperationResponse<AuthenticationMechanismDTO> GetAuthenticationMechanism(string userName);
}
public class AuthStrategy
{
readonly IAuthStrategy _authStrategy;
public AuthStrategy(IAuthStrategy authStrategy)
{
this._authStrategy = authStrategy;
}
public OperationResponse<AuthenticationMechanismDTO> GetAuthenticationMechanism(string userName)
{
return _authStrategy.GetAuthenticationMechanism(userName);
}
}
public class UserNamePasswordMechanism : IAuthStrategy
{
private IInstitutionRepository _institutionRepository;
public UserNamePasswordMechanism(IInstitutionRepository institutionRepository)
{
this._institutionRepository = institutionRepository;
}
public OperationResponse<AuthenticationMechanismDTO> GetAuthenticationMechanism(string userName)
{
throw new NotImplementedException();
}
}
My problem is that I am injecting IAuthStrategy into the controller, and it gives me an error, because instead of implementing IAuthStrategy, I am passing that to AuthStrategy constructor, as you can see that in my code.
How can I fix this error?
Here is my controller
public class EmployeeController : ApiController
{
private IAuthStrategy _auth;
public EmployeeController(IAuthStrategy auth)
{
this._employeeBL = employeeBL;
this._auth = auth;
}}
}
Here is unity config where i am registering my types
public class UnityConfig
{
#region Unity Container
private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
});
/// <summary>
/// Gets the configured Unity container.
/// </summary>
public static IUnityContainer GetConfiguredContainer()
{
return container.Value;
}
#endregion
/// <summary>Registers the type mappings with the Unity container.</summary>
/// <param name="container">The unity container to configure.</param>
/// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to
/// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>
public static void RegisterTypes(IUnityContainer container)
{
// NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.
// container.LoadConfiguration();
// TODO: Register your types here
container.RegisterType<IInstitutionRepository, InstitutionRepository>();
container.RegisterType<IAuthStrategy, AuthStrategy>();
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
}
}
A: Your unit registrations and classes look a little off.
From what I can gather, this is what you really want to do.
Setup a factory that will determine at runtime which IAuthStrategy should be used:
public interface IAuthStrategyFactory
{
IAuthStrategy GetAuthStrategy();
}
public class AuthStrategyFactory : IAuthStrategyFactory
{
readonly IAuthStrategy _authStrategy;
public AuthStrategy(...)
{
//determine the concrete implementation of IAuthStrategy that you need
//This might be injected as well by passing
//in an IAuthStrategy and registering the correct one via unity at startup.
_authStrategy = SomeCallToDetermineWhichOne();
}
public IAuthStrategy GetAuthStrategy()
{
return _authStrategy;
}
}
This is your existing AuthStrategy:
public interface IAuthStrategy
{
OperationResponse<AuthenticationMechanismDTO> GetAuthenticationMechanism(string userName);
}
public class UserNamePasswordMechanism : IAuthStrategy
{
private IInstitutionRepository _institutionRepository;
public UserNamePasswordMechanism(IInstitutionRepository institutionRepository)
{
this._institutionRepository = institutionRepository;
}
public OperationResponse<AuthenticationMechanismDTO> GetAuthenticationMechanism(string userName)
{
throw new NotImplementedException();
}
}
Register the factory with unity:
container.RegisterType<IAuthStrategyFactory, AuthStrategyFactory>();
In your controller:
public class EmployeeController : ApiController
{
private IAuthStrategy _auth;
public EmployeeController(IAuthStrategyFactory authFactory)
{
this._employeeBL = employeeBL;
this._auth = authFactory.GetAuthStrategy();
}
}
A: Actually i missed implemented IAuthStrategyFactory on AuthStrategyFactory, once i implemented and register in unity container that worked.
Thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30492226",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Using reflection throws error in EF Core 3 We formerly used reflection to create linq queries, e.g. for the GetById method:
private IQueryable<T> GetQueryById(TKey id)
{
var query = _dbset; //DbSet<T>
var keyNames = _context.Model
.FindRuntimeEntityType(typeof(T))
.FindPrimaryKey()
.Properties
.Select(x => x.Name)
.ToList();
if (keyNames.Count() == 1)
{
query = query.Where(e => e.GetType().GetProperty(keyNames[0]).GetValue(e, null)
.Equals(id)); //throws error
}
return query;
}
This does not seem to work any more in EF Core 3:
The LINQ expression 'DbSet
.Where(c => c.GetType().GetProperty(__get_Item_0).GetValue(
obj: c,
index: null).Equals((object)__id_1))' could not be translated.
Is it possible to rewrite the query so that EF Core does not complain?
A: You have to create predicate dynamically:
private IQueryable<T> GetQueryById(TKey id)
{
IQueryable<T> query = _dbset; //DbSet<T>
var keyNames = _context.Model
.FindRuntimeEntityType(typeof(T))
.FindPrimaryKey()
.Properties
.Select(x => x.Name)
.ToList();
if (keyNames.Count == 1)
{
var keyExpression = Expression.Constant(id);
var entityParam = Expression.Parameter(typeof(T), "e");
var body = Expression.Equal(Expression.PropertyOrField(entityParam, keyNames[0]), keyExpression);
var predicate = Expression.Lambda<Func<T, bool>>(body, entityParam);
query = query.Where(predicate);
}
else
// better to throw exception
throw new Exception($"Cannot find entity key.");
return query;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64050904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android: App crashes when doing httpclient.execute in AsyncTask i'm having problems with httpclient. I debugged the app and it crashes when calling execute function. Here's the code:
public class MyAsyncTask extends AsyncTask<String, String, String> {
GridView mGridView;
Activity mContex;
public MyAsyncTask(Activity contex) {
this.mContex = contex;
}
@Override
protected String doInBackground(String... params) {
//fetch data
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("localhost:3000/api/send");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email", params[1]));
nameValuePairs.add(new BasicNameValuePair("name", params[0]));
nameValuePairs.add(new BasicNameValuePair("gender", "male"));
nameValuePairs.add(new BasicNameValuePair("result", "lazy bee"));
nameValuePairs.add(new BasicNameValuePair("age", "28"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return "success";
}
}
I call MyAsyncTask here, from a fragment and passing the activity:
public class SendResultPageFragment extends Fragment implements View.OnClickListener {
EditText name, email;
MyAsyncTask task;
public static SendResultPageFragment newInstance() {
return new SendResultPageFragment();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_screen_slide_send_result, container, false);
rootView.findViewById(R.id.result_next_button).setOnClickListener(this);
name = (EditText)rootView.findViewById(R.id.name_txt);
email = (EditText)rootView.findViewById(R.id.email_txt);
return rootView;
}
@Override
public void onClick(View view) {
this.task = new MyAsyncTask(getActivity());
this.task.execute(this.name.getText().toString(), this.email.getText().toString());
return ;
}
}
Does anybody know the solution ? Thanks
A: new HttpPost("localhost:3000/api/send"); every http request needs to be fully qualified. also do not use local host.Android wont recognize your endpoint that way. I always use ngrok to broadcast to internet. switch to
new HttpPost("http://your_domain");
also switch to retrofit2, it uses java annotations to compose its request. Highly recommended. here is a great link to start:https://futurestud.io/tutorials/retrofit-getting-started-and-android-client
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42631137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: what option controls numeric brace expansion in zsh? I'm getting a really weird bug on one of my zsh installations. I can do this:
for k in {1..6}; do echo $k; done
# 1
# 2
# 3
# 4
# 5
# 6
but I can't step through it:
for k in {1..6..2}; do echo $k; done
# {1..6..2}
I'm sure my current shell is zsh, and in a different computer it works, so I'm just wondering what option I might have set that changed the default behavior. Any ideas?
A: While the {x..y} syntax originated in zsh decades ago, ksh93 was the one adding the {x..y..step} one and zsh only added it in version 4.3.10-test-3 in 2010.
You probably have an older version of zsh there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20731088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: overlapping floats: z-index doesn't work I'm trying to write a horizontal navigation bar with simple drop down menus (again horz). The main menu displays fine. To hide the submenus when not hovering, I did
ul#submenu {
visibility: hidden;
display: inline;
position: absolute;
top: 10pt;left: 0;
}
ul#mainmenu li:hover ul#submenu li {
visibility: visible;
position: relative;
float: right;
}
The visibility and appear on hover work fine. However, part of the submenu gets hidden under the float right below. I tried setting z-index: 0 for that and z-index: 1 for the submenus, but it still doesn't work. How do I bring it to the top?
A: Check if overflow: hidden; or overflow: auto is set in the parent div. That could prevent it from showing up.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5373797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to change viewport of 2D image? I'm developing a mobile app for money recognition. Now I'm trying to build the database for this app.
The next step is generate some image from an original image in different view. Here is the example:
Original:
View 1:
As you can see in above image, the view 1 image is view of original from left edge. What I want to do is generate 4 image from original with 4 view from left, right, bottom, up. With the very large number of image, I can not use camera to capture so I need a write a program to do this work. But I can not found any thing about this issue.
Please tell me are there any tools to do what I need? or any library, framework support this? I can code on MATLAB and openCV.
Thanks for your help.
A: You can do the following:
*
*you assume that your original image is looking with 90 degree angle on a planar object
*you assume some camera intrinsic parameters (e.g. focal point in the middle of the image and uniform pixel size), some camera extrinsics (e.g. looking "down" with some position from above the plane) and some plane coordinates (xy-plane). This will result in every pixel to lie on some coordinates of the plane.
*you change your camera extrinic parameters by rotating around the camera center
*you project some (4 or more) plane positions to your camera image (e.g. use cv::projectPoints()).
*you compute the perspective homography that describes the pixel "motion" between both camera views (input pixel positions are those projected plane positions and the same plane positions in your original image)
*remember that homography for each chosen view.
*for each image, just use those homographies, you don't have to recompute them because they are the same for each image.
EDIT:
this is how it looks like in action (sorry for ugly code):
cv::Mat getRotationMatrixAroundY(double angle)
{
cv::Mat rVec;
cv::Mat deg45 = cv::Mat::zeros(3,3,CV_64FC1);
double cos45 = cos(CV_PI*angle/180.0);
double sin45 = sin(CV_PI*angle/180.0);
// different axis:
/* deg45.at<double>(1,1) = cos45; deg45.at<double>(1,2) = sin45; deg45.at<double>(0,0) = 1; deg45.at<double>(2,1) = -sin45; deg45.at<double>(2,2) = cos45; */
/* deg45.at<double>(0,0) = cos45; deg45.at<double>(0,1) = in45; deg45.at<double>(2,2) = 1; deg45.at<double>(1,0) = -sin45; deg45.at<double>(1,1) = cos45; */
deg45.at<double>(0,0) = cos45;
deg45.at<double>(0,2) = sin45;
deg45.at<double>(1,1) = 1;
deg45.at<double>(2,0) = -sin45;
deg45.at<double>(2,2) = cos45;
cv::Rodrigues(deg45, rVec);
return rVec;
}
// banknode training sample generator
int main()
{
cv::Mat input = cv::imread("../inputData/bankNode.jpg");
std::vector<cv::Point3f> pointsOnPlane;
pointsOnPlane.push_back(cv::Point3f(0-input.cols/2,0-input.rows/2,0));
pointsOnPlane.push_back(cv::Point3f(input.cols-input.cols/2,0-input.rows/2,0));
pointsOnPlane.push_back(cv::Point3f(input.cols-input.cols/2,input.rows-input.rows/2,0));
pointsOnPlane.push_back(cv::Point3f(0-input.cols/2,input.rows-input.rows/2,0));
std::vector<cv::Point2f> originalPointsInImage;
originalPointsInImage.push_back(cv::Point2f(0,0));
originalPointsInImage.push_back(cv::Point2f(input.cols,0));
originalPointsInImage.push_back(cv::Point2f(input.cols,input.rows));
originalPointsInImage.push_back(cv::Point2f(0,input.rows));
std::cout << "original pixel positions:" << std::endl;
for(unsigned int i=0; i<originalPointsInImage.size(); ++i)
std::cout << originalPointsInImage[i] << std::endl;
cv::Mat cameraIntrinsics = cv::Mat::eye(3,3,CV_64FC1);
cameraIntrinsics.at<double>(0,0) = 500.0;
cameraIntrinsics.at<double>(1,1) = 500.0;
cameraIntrinsics.at<double>(0,2) = input.cols/2.0;
cameraIntrinsics.at<double>(1,2) = input.rows/2.0;
std::vector<double> distCoefficients;
cv::Mat rVec;
cv::Mat tVec;
cv::solvePnP(pointsOnPlane, originalPointsInImage, cameraIntrinsics, distCoefficients, rVec, tVec);
// let's increase the distance a bit
tVec = tVec*2;
double angle = -45; // degrees
cv::Mat rVec2 = getRotationMatrixAroundY(angle);
// TODO: how to "add" some rotation to a previous rotation in Rodrigues?!?
// atm just overwrite:
std::vector<cv::Point2f> projectedPointsOnImage;
cv::projectPoints(pointsOnPlane, rVec2, tVec, cameraIntrinsics, distCoefficients, projectedPointsOnImage);
cv::Mat H = cv::findHomography(originalPointsInImage, projectedPointsOnImage);
cv::Mat warped;
cv::warpPerspective(input, warped, H, input.size());
cv::imshow("input", input);
cv::imshow("warped", warped);
cv::waitKey(0);
return 0;
}
with this result:
as you can see there is one problem: the rotation isn't around the center of the banknode. If someone can fix that, the result will be better. Atm I had to scale the translation part, this might not be necessary afterwards. Probably the problem occurs because of wrong translation + rotation combination.
for comparison: tranlation scaled by 1.5:
and not scaled:
Is this what you wanted to achieve (if the viewing center of the camera could be fixed at the middle of the banknode)?
A: Look here for a Projective Transformation using Matlab. You only have to find the right warping matrices (so-called homographies). You can build them with the mathematics on wikipedia, given a rotation matrix and an assumed camera intrinsics.
However, I think synthetically created training data possibly causes some problems regarding your task. The reflecting parts of bank notes are engineered to look different from different view points. You'll lose information.
Further, do not underestimate the effort, which will be necessary to develop this. There is quite sophisticated research going on in this field.
See here:
Towards Mobile Recognition and Verification of Holograms using Orthogonal Sampling
Mobile User Interfaces for Efficient Verification of Holograms
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34315187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I save a byte[] returned from a WCF call? In the code behind of my web page, I call a WCF service. The service returns a byte[] representing a file. In the code behind I have the following line that captures the bytes.
byte[] bytes = client.GeneratePDFBytes(crObj);
The question is, now what do I do with it? I want the user to be prompted to open/save the file. How do I add this functionality? I'm new to services and web stuff so it's likely something really simple but I'm overlooking it.
A: You can use the following:
Response.ContentType = "application/pdf";
Response.BinaryWrite(bytes);
A: Don't get hung up on the fact that you retrieved the byte array from a WCF service. Once you have the result stored in a byte array, you're looking at the exact same technique for writing to disk as if you read it out of a database or off the file system. If you change you research from WCF to flat-out reading/writing bytes I think you'll have better luck. Here's one from SO that had some good suggestions:
C# - How do I read and write a binary file?
Edit: I somehow managed to miss that this was ASP.NET... sorry about that, you have to write to response and set content type to binary then, as other answers have provided examples for.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7474618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Deserializing DbGeometry with Newtonsoft.Json I'm building a SPA using Angular,Breeze and Web API 2 following the approach as outlined by John Papa in his latest PluralSight course.
Everything works well and I can pull information, update, insert, delete back to the server. However I'm using Spatial Types, and when I try to update an entity with a spatial type I get the following error
An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in
Newtonsoft.Json.dll but was not handled in user code
Additional information: Error getting value from 'WellKnownValue' on
'System.Data.Entity.Spatial.DbGeometry'.
The inner exception seems to point to the fact that the WellKnownValue is null, its not though, as I have checked the JSON being sent to the server which is then sent to the Breeze ContextProvider and saved using the SaveChanges method.
{
"entities": [
{
"TableKey": 2,
"CaseName": "Mikhail Lermontov",
"StartDate": "2013-06-11T00:00:00Z",
"EndDate": null,
"IsCurrent": true,
"SRID": 109,
"Shape": {
"$id": "2",
"$type": "System.Data.Entity.Spatial.DbGeometry, EntityFramework",
"Geometry": {
"$id": "3",
"$type": "System.Data.Entity.Spatial.DbGeometryWellKnownValue, EntityFramework",
"CoordinateSystemId": 2193,
"WellKnownText": "POLYGON ((1695943 5462665, 1713098 5462665, 1713098 5449659, 1695943 5449659, 1695943 5462665))"
}
},
"SpillLocation": "Marlborough Sounds",
"Image": "http://www.nzmaritime.co.nz/images/lm5.jpg\r\n",
"DefaultBaseMapKey": 2,
"__unmapped": {
"isPartial": false
},
"entityAspect": {
"entityTypeName": "DatSpillCase:#Osiris.Model",
"defaultResourceName": "DatSpillCases",
"entityState": "Modified",
"originalValuesMap": {
"CaseName": "Mikhail Lermontov"
},
"autoGeneratedKey": {
"propertyName": "TableKey",
"autoGeneratedKeyType": "Identity"
}
}
}
],
"saveOptions": {}
}
So my question is, is possible to deserialize DbGeometry types within the NewtonSoft library, and if not, what suggestions are there to get around that.
A: The answer above works great, but is hardcoded for SRID (CoordinateSystemId) 2193.
The Coordinate System Id can however be present in the serialised data as shown in the question, or it can be present in the WellKnownText "SRID=2193;POINT (0 0)". Also this method will only read a polygon, but the WellKnownText can be a lot of things, like Geometry Collections, Point, Linestring, etc. To retreive this the ReadJson method can be updated to use the more generic FromText method as shown below.
Here is the class above updated with a more generic Coordinate System, and also for any Geometry Type. I have also added the Geography version for reference.
public class DbGeometryConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType.IsAssignableFrom(typeof(string));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject location = JObject.Load(reader);
JToken token = location["Geometry"]["WellKnownText"];
string value = token.ToString();
JToken sridToken = location["Geometry"]["CoordinateSystemId"];
int srid;
if (sridToken == null || int.TryParse(sridToken.ToString(), out srid) == false || value.Contains("SRID"))
{
//Set default coordinate system here.
srid = 0;
}
DbGeometry converted;
if (srid > 0)
converted = DbGeometry.FromText(value, srid);
else
converted = DbGeometry.FromText(value);
return converted;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
// Base serialization is fine
serializer.Serialize(writer, value);
}
}
public class DbGeographyConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType.IsAssignableFrom(typeof(string));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject location = JObject.Load(reader);
JToken token = location["Geography"]["WellKnownText"];
string value = token.ToString();
JToken sridToken = location["Geography"]["CoordinateSystemId"];
int srid;
if (sridToken == null || int.TryParse(sridToken.ToString(), out srid) == false || value.Contains("SRID"))
{
//Set default coordinate system here.
//NOTE: Geography should always have an SRID, and it has to match the data in the database else all comparisons will return NULL!
srid = 0;
}
DbGeography converted;
if (srid > 0)
converted = DbGeography.FromText(value, srid);
else
converted = DbGeography.FromText(value);
return converted;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
// Base serialization is fine
serializer.Serialize(writer, value);
}
}
A: System.Data.Spatial.DbGeometry does not play nicely with Newtonsoft.Json
You need to create a JsonConverter to convert the DbGeometry
public class DbGeometryConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType.IsAssignableFrom(typeof(string));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject location = JObject.Load(reader);
JToken token = location["Geometry"]["WellKnownText"];
string value = token.ToString();
DbGeometry converted = DbGeometry.PolygonFromText(value, 2193);
return converted;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
// Base serialization is fine
serializer.Serialize(writer, value);
}
}
Then on your property in your model add the attribute
[JsonConverter(typeof(DbGeometryConverter))]
public DbGeometry Shape { get; set; }
Now when you hit your BreezeController the deserialization will be handled by our new DbGeometryConverter.
Hope it helps.
A: I don't see why not. On the line with (DbGeometryWellKnownValue):
"$type": "System.Data.Entity.Spatial.DbGeometryWellKnownValue, EntityFramework",
should this be (DbGeometry.WellKnownValue)?
"$type": "System.Data.Entity.Spatial.DbGeometry.WellKnownValue, EntityFramework",
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20926102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Why does QtCreator not show the 'Applications' section on Mac? The lists of templates differ. For example when I load the tutorial "Creating a Qt Widget Based Application", it shows the following screenshot.
"Applications" is clearly a visible section of templates available on the left.
I've just downloaded Qt Creator 2.8.1 for Mac (53 MB) from http://qt-project.org/downloads and when I run it I see:
What's going on? I can't even get a simple project started.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19227761",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to compare across multiple columns containing list value in Python Pandas? I have the following sample data
ID VAR1 VAR2 VAR3 DATE
1 NaN [Timestamp('2012-08-03'), 'M'] [Timestamp('2012-08-03'), 'M'] 2012-08-03
2 [Timestamp('2009-04-01'), 'F'] NaN [Timestamp('2009-04-03'), 'F'] 2009-04-01
3 NaN [Timestamp('2004-01-01'), 'M'] NaN 2004-01-01
4 NaN [Timestamp('2004-02-15'), 'M'] [Timestamp('2000-08-07'), 'M'] 2000-08-07
For each row, I want to go through VAR1, VAR2, and VAR3 and have each to compare against the DATE. Each of the three columns would either have a np.nan (missing value) or a list value (containing a date and gender). I want to compare the first element of the list against the DATE column. If the first-element date is more than a day difference than the DATE value, I want to replace that cell value as np.nan.
I like to use Pandas' apply function as I am clear with the underlying logics.
The desired processed df should be as follows:
ID VAR1 VAR2 VAR3 DATE
1 NaN [Timestamp('2012-08-03'), 'M'] [Timestamp('2012-08-03'), 'M'] 2012-08-03
2 [Timestamp('2009-04-01'), 'F'] NaN NaN 2009-04-01
3 NaN [Timestamp('2004-01-01'), 'M'] NaN 2004-01-01
4 NaN NaN [Timestamp('2000-08-07'), 'M'] 2000-08-07
This is my working code
df = df.apply(remove_value_if_unmatched_against_index_date, axis=1)
def remove_value_if_unmatched_against_index_date(df):
vars = ['VAR1', 'VAR2', 'VAR3']
for var in vars:
if isinstance(df[var], list): # doesn't work
# if df[var].notnull(): # doesn't work
# if df[var] != np.nan: # doesn't work
if abs(df[var][0] - df['DATE']) >= timedelta(days=1):
df[var] = np.nan
return df
The problem is none of the followings (if isinstance(df[var], list):, if df[var].notnull():, and if df[var] != np.nan:) works to help check if there is a list value within the cell.
A: Try with bfill
df['new'] = df.bfill(axis=1)['VAR1'].str[0]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67453798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Encrypting with AES Why can I encrypt only 16 characters of text?
Works:
string plainText = "1234567890123456";
Doesn't work:
string plainText = "12345678901234561";
Doesn't work:
string plainText = "123456789012345";
Code:
string plainText = "1234567890123456";
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
byte[] keyBytes = System.Text.Encoding.UTF8.GetBytes("1234567890123456");
byte[] initVectorBytes = System.Text.Encoding.UTF8.GetBytes("1234567890123456");
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.Zeros;
ICryptoTransform encryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherTextBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
string cipherText = Convert.ToBase64String(cipherTextBytes);
Console.ReadLine();
A: Not sure I understand the question, but looking at what I assume the intent is of the code the following
symmetricKey.CreateDecryptor
Should probably be
symmetricKey.CreateEncryptor
A: Probably because AES is a block cipher with 128 bits per block.. maybe you just need to add a padding such that length % 128 == 0.
(I'm not a C# developer but it can happen that an implementation doesn't care about adding padding by itself)
Just a hint: try if it works with 256 bits
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2663862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: get the observations for chi2 test We have a collection of Data that we can draw a histogram with the specified distribution curve on and get the centers of bins, using:
[counts,centers]=hist(Data,14)
h=histfit(Data,14,'normal')
we can get the 100 point XData and YData of the drawn curve, using:
h(2).XData
h(2).YData
How can we find the YData of the curve corresponding to the bin centers of the histogram of Data (in commands without knowing the curve equation)?
Thanks in advance
A: I think you can use fitdistr
%Generate data
r=randn(100,1);
[counts,centers]=hist(r,20) %r=Data in your case
%fit a Gaussian
pd=fitdist(r(:),'normal')
pd =
NormalDistribution
Normal distribution
mu = 0.0700439 [-0.111376, 0.251463]
sigma = 0.914313 [0.802773, 1.06213]
x=-3:0.1:3;
PDF=pdf(pd,x); %PDF is a vector of y values: it's our fit
%overplot
PDF=PDF/max(PDF);
%scale to y axis
y=ylim;
PDF=PDF*y(2);
hold on
plot(x,PDF,'r-','LineWidth',2)
hold off
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35916980",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PowerShell sends empty JSON payload I am calling GraphAPI to update keycredentials for a service principal. I create the JSON payload through combining data from a GET call and a custom JSON object.
I have a variable that is not empty, but when I make an API call I get an "empty payload" error. Why is my $body variable considered empty when it clearly isn't?
Below is the information on how I populate this variable.
Information
Here is the script:
. .\GetSecretToken.ps1
. .\pull_cert_data.ps1
$response = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/servicePrincipals/{id}" -Method Get -Headers $Header
$current_keys = $response.keycredentials
$key_credentials = $current_keys + $new_KeyCredentials
$key_credentials | ConvertTo-Json | Out-File .\checkkeys.txt
$hash_body =
@{"keyCredentials" = $key_credentials
"passwordCredentials" = $password_credentials}
$body = $hash_body | ConvertTo-Json -Depth 5
$body | out-file .\checkvalue.txt
$body
$json = $body
$update_cert = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/servicePrincipals/{id}" -Method Patch -Headers $Header -Body $json
If I use the $body variable in the $update_cert call, I get an empty payload error:
{"error":{"code":"BadRequest","message":"Empty Payload. JSON content | expected."
However, if I use the $json variable, which just equals the $body variable, my call is successful. It will also print the contents of the $body variable in the terminal, so I know it isn't empty. The script creates two files that were originally done to make sure the JSON formatting was correct.
Here is the output of the $body variable:
{
"keyCredentials": [
{
"customKeyIdentifier": "<HASH_OF_THUMBPRINT>",
"displayName": "<CN>",
"endDateTime": "<EXPIRY_DATE>",
"key": null <EXISTING_CERT>,
"keyId": "<GUID>",
"startDateTime": "<START_DATE>",
"type": "AsymmetricX509Cert",
"usage": "Verify"
},
{
"customKeyIdentifier": "<HASH_OF_THUMBPRINT>",
"displayName": "<CN>",
"endDateTime": "<EXPIRY_DATE>",
"key": null <EXISTING_CERT>,
"keyId": "<GUID>",
"startDateTime": "<START_DATE>",
"type": "AsymmetricX509Cert",
"usage": "Sign"
},
{
"customKeyIdentifier": "<HASH_OF_THUMBPRINT>",
"displayName": "<CN>",
"endDateTime": "<EXPIRY_DATE>",
"key": null <EXISTING_CERT>,
"keyId": "<GUID>",
"startDateTime": "<START_DATE>",
"type": "AsymmetricX509Cert",
"usage": "Verify"
},
{
"customKeyIdentifier": "<HASH_OF_THUMBPRINT>",
"displayName": "<CN>",
"endDateTime": "<EXPIRY_DATE>",
"key": null <EXISTING_CERT>,
"keyId": "<GUID>",
"startDateTime": "<START_DATE>",
"type": "AsymmetricX509Cert",
"usage": "Sign"
},
{
"customKeyIdentifier": "<HASH_OF_THUMBPRINT>",
"endDateTime": "<EXPIRY_DATE>",
"type": "X509CertandPassword",
"key": "<NEWCERT-PrivateKey>",
"displayName": "<CN>",
"startDateTime": "<START_DATE>",
"keyId": "<GUID>",
"usage": "Sign"
},
{
"customKeyIdentifier": "<HASH_OF_THUMBPRINT>",
"endDateTime": "<EXPIRY_DATE>",
"type": "AsymmetricX509Cert",
"key": "<NEWCERT-PublicKey>",
"displayName": "<CN>",
"startDateTime": "<START_DATE>",
"keyId": "<GUID>",
"usage": "Verify"
}
],
"passwordCredentials": [
{
"endDateTime": "<EXPIRY_DATE>",
"secretText": "<PASSPHRASE_FOR_NEW_CERT>",
"startDateTime": "<START_DATE>",
"keyId": "<KEY_ID_OF_PRIVATE_KEY>",
"customKeyIdentifier": "<HASH_OF_THUMBPRINT_OF_NEW_CERT>"
}
]
}
Note: The $new_keyCredentials and $password_credentials variables are arrays that contain the hashtables of the new keycredentials and password credentials of those keys and are imported from the pull_cert_date.ps1 script. The $Header is coming from GetSecretToken.ps1 script.
A:
PowerShell sends empty JSON payload
This error states that the PowerShell that the command is wanting the Json and the input provided is empty.
I have reproduced your requirement in my environment, and I have faced similar issue as you.
So, when I displayed the body i got the below as output:
And if I send this as the Json in invoke command, I get similar error as you got.
Then I used ConvertTo-Json and I got expected results as below:
Here what I observed is when I converted \n are added and it worked as expected.
References:
*
*"Empty Payload. JSON content expected" when uploading an item to OneDrive from a URL · Issue #745 · OneDrive/onedrive-api-docs · GitHub
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74115081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: combining jackson objectmapper and stream parsing I have an android application, where parsing a json block takes around 250ms. It contains an array, and I only really need the first 6-7 values available immediatly. And I really need to speed up getting to those pieces of the data.
I have a data structure that essentially looks like:
class Data {
List<Map> data = objectmapper_readvalue_data;
public HashMap getItem(int i) {
return data.get(i);
}
}
I was really hoping to do something like this with a JsonParser:
class Data {
List data = new List();
JsonParser p;
public HashMap getItem(int i) {
while (data.length < i) {
data.append(p.parseOneBlockOfData());
}
return data.get(i);
}
}
And only the first 5-6 values will be parsed at the first render, the others I can deal with later. However, I'm missing the "parseOneBlockOfData" function. Of course I can use a StringBuilder to buffer every value in the parse until I find the next entire block, then use a objectParser or that, but I'm not sure what the performance will be like.
Are there any non hackish ways of doing this?
A: incase anyone googles this:
JsonParser parser = objectMapper.getFactory().createJsonParser(inputStream);
// Keep going until we find filters:
String fieldName = null;
JsonToken token = null;
while (!"filters".equals(fieldName)) {
token = parser.nextToken();
while (token != JsonToken.START_ARRAY) {
token = parser.nextToken();
}
fieldName = parser.getCurrentName();
}
// We're at the filters node
while (parser.nextToken() == JsonToken.START_OBJECT) {
Map x = objectMapper.readValue(parser, Map.class);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15688951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to Get file from google drive I want to get file from drive use this code but not working.Some code given below -
public class PinFileActivity extends BaseDemoActivity {
private static final int REQUEST_CODE_OPENER = NEXT_AVAILABLE_REQUEST_CODE;
private static final String TAG = "PinFileActivity";
private DriveId mFileId;
/**
* Starts a file opener intent to pick a file.
*/
@Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
if (mFileId == null) {
IntentSender intentSender = Drive.DriveApi
.newOpenFileActivityBuilder()
.setMimeType(
new String[] { "text/plain", "text/html",
"application/pdf", "audio/mp3",
"video/mp4", "text/plain",
"application/msword", "image/jpeg",
"image/png", "text/html" })
.build(getGoogleApiClient());
try {
startIntentSenderForResult(intentSender, REQUEST_CODE_OPENER,
null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
Log.w(TAG, "Unable to send intent", e);
}
} else {
DriveFile file = Drive.DriveApi.getFile(getGoogleApiClient(),
mFileId);
Log.i("File Name is ", "===========>>>>" + file);
file.getMetadata(getGoogleApiClient()).setResultCallback(
metadataCallback);
}
}
/**
* Handles response from the file picker.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CODE_OPENER:
if (resultCode == RESULT_OK) {
mFileId = (DriveId) data
.getParcelableExtra(OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
} else {
finish();
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
}
}
/**
* Handles the metadata response. If file is pinnable and not already
* pinned, makes a request to pin the file.
*/
final ResultCallback<DriveResource.MetadataResult> metadataCallback = new ResultCallback<DriveResource.MetadataResult>() {
@Override
public void onResult(DriveResource.MetadataResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Problem while trying to retrieve the file metadata");
return;
}
if (result.getMetadata().isPinnable()) {
showMessage("File is not pinnable");
Log.i("==========All Info is here", "mIME tYPE=====>>>"
+ result.getMetadata().getMimeType() + "======>"
+ result.getMetadata().getTitle() + "====="
+ result.getMetadata().getAlternateLink() + "======"
+ result.getMetadata().getWebContentLink() + "======>>"
+ result.getMetadata().getQuotaBytesUsed());
return;
}
if (result.getMetadata().isPinned()) {
showMessage("File is already pinned");
return;
}
Log.i("==========All Info is here", "==========>>>");
DriveFile file = Drive.DriveApi.getFile(getGoogleApiClient(),
mFileId);
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setPinned(true).build();
file.updateMetadata(getGoogleApiClient(), changeSet)
.setResultCallback(pinningCallback);
}
};
/**
* Handles the pinning request's response.
*/
final ResultCallback<DriveResource.MetadataResult> pinningCallback = new ResultCallback<DriveResource.MetadataResult>() {
@Override
public void onResult(DriveResource.MetadataResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Problem while trying to pin the file");
return;
}
showMessage("File successfully pinned to the device");
}
};
}
Here My BaseDemoActivity sample code
public abstract class BaseDemoActivity extends Activity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "BaseDriveActivity";
/**
* DriveId of an existing folder to be used as a parent folder in
* folder operations samples.
*/
public static final String EXISTING_FOLDER_ID = "0B2EEtIjPUdX6MERsWlYxN3J6RU0";
/**
* DriveId of an existing file to be used in file operation samples..
*/
public static final String EXISTING_FILE_ID = "0ByfSjdPVs9MZTHBmMVdSeWxaNTg";
/**
* Extra for account name.
*/
protected static final String EXTRA_ACCOUNT_NAME = "account_name";
/**
* Request code for auto Google Play Services error resolution.
*/
protected static final int REQUEST_CODE_RESOLUTION = 1;
/**
* Next available request code.
*/
protected static final int NEXT_AVAILABLE_REQUEST_CODE = 2;
/**
* Google API client.
*/
private GoogleApiClient mGoogleApiClient;
/**
* Called when activity gets visible. A connection to Drive services need to
* be initiated as soon as the activity is visible. Registers
* {@code ConnectionCallbacks} and {@code OnConnectionFailedListener} on the
* activities itself.
*/
@Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addScope(Drive.SCOPE_APPFOLDER) // required for App Folder sample
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
mGoogleApiClient.connect();
}
/**
* Handles resolution callbacks.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_RESOLUTION && resultCode == RESULT_OK) {
mGoogleApiClient.connect();
}
}
/**
* Called when activity gets invisible. Connection to Drive service needs to
* be disconnected as soon as an activity is invisible.
*/
@Override
protected void onPause() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
/**
* Called when {@code mGoogleApiClient} is connected.
*/
@Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "GoogleApiClient connected");
}
/**
* Called when {@code mGoogleApiClient} is disconnected.
*/
@Override
public void onConnectionSuspended(int cause) {
Log.i(TAG, "GoogleApiClient connection suspended");
}
/**
* Called when {@code mGoogleApiClient} is trying to connect but failed.
* Handle {@code result.getResolution()} if there is a resolution is
* available.
*/
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
// show the localized error dialog.
GoogleApiAvailability.getInstance().getErrorDialog(this, result.getErrorCode(), 0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (IntentSender.SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
/**
* Shows a toast message.
*/
public void showMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
/**
* Getter for the {@code GoogleApiClient}.
*/
public GoogleApiClient getGoogleApiClient() {
return mGoogleApiClient;
}
}
I am getting user select popup only.
select the user after also show this popup how to fix this one.
I get this error:
ConnectionResult{statusCode=SIGN_IN_REQUIRED,
resolution=PendingIntent{2af2f49: android.os.BinderProxy@462504a}}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44673053",
"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.