text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Android: How to change TextView periodically I'm recently working on a ShoutCast radio project. By using streamscrapper library I'm able to get the current song name and the current artist. Here is the problem. Once I open the app, it gets the song name and the artist name, however since then it does not update it. I tried to do it with timer but couldn't figure out.
And here is the method which I get the current song id:
private void initializeMediaPlayer() {
player = new AACPlayer();
scraper = new ShoutCastScraper();
try {
streams = scraper.scrape(new URI("http://sunucu2.radyolarburada.com:5000/"));
String str = "asd";
for (Stream stream: streams) {
str = stream.getCurrentSong();
currPlayView.setText("Now Playing: " + str);
}
} catch (ScrapeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
A: Maybe something like a runnable:
private Handler handler = new Handler();
handler.postAtTime(timeTask, SystemClock.uptimeMillis() + 500);
private Runnable timeTask = new Runnable() {
public void run() {
//do stuff here
//do it again soon
handler.postAtTime(timeTask, SystemClock.uptimeMillis() + 500);
}
};
Before you leave make sure to stop the tasks:
handler.removeCallbacksAndMessages(null);
A: use a Handler to update it ,
Handler handler=new Handler();
int FREQ=5000; // the update frequency
handler.postDelayed(new Runnable()
{
public void run()
{
try
{
String currStr; // get your next song name
currPlayView.setText(currStr);
}
finally
{
handler.postDelayed(this, FREQ);
}
}
}, FREQ);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17785272",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python Big O Determination I'm writing a program where I have to determine the growth rate of some code.
It might be run like this:
python3 my_program.py program_with_code_to_test
Here is where I am stuck:
The executable code accepts one int argument n. I can assume that "N0" (that is N subscript zero), is equal to 2^10 which is = 1024, and that every N is another power of 2.
So I know that the data size doubles every time. I need to determine how the growth rate in time changes.
SO if
some_code 1024 # 1024 being n
Takes 0.5 seconds to execute and
some_code 2048 # = 2^11
Takes 0.5 seconds to execute. Then I know that the growth rate is constant, i.e. the time it takes is irrelevant to the data size. One more example:
if
some_code 1024 # takes 0.5 seconds
some_code 2048 # takes roughly 2.0 seconds
then I need to output that the Big O time is quadratic (because the time it takes for the program to execute roughly quadruples as the data doubles).
So I think I need to do something like this:
before = time.process_time()
# whatever code I am passing in
after = time.process_time()
totalTime = after - before
But then how can I save totalTime so that I can see how totalTime changes as N (or the data size) doubles? How can I compare totalTime with the last totalTime? Or am I thinking about this the wrong way? Thanks for any help.
Note: Now I know I need to use subprocess.call for my code but I will figure that out later.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43580014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: I'm Confused with Java NIO I'm confused with java nio buffers and Files.write if I can write with buffers and channels on file why do I need Files class.
What's difference between both of these working code examples.
String newData = "New String to write to file..." + System.currentTimeMillis();
Path path = Paths.get("C://data/nio-data2.txt");
try {
Files.write(path,newData.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
and
try {
RandomAccessFile aFile = new RandomAccessFile("C://data/nio-data.txt", "rw");
FileChannel channel = aFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes());
buf.flip();
while(buf.hasRemaining()) {
channel.write(buf);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
EDIT
i want to ask one more question, is Channels.newOutputStream interrupt the thread when write to file or worked as a non-blocking
A: Version with Files shorter and easier to understand.
Other version is more flexible. It is not very useful when you have only one file to write, but if you have many files in different storages it can save you some resources.
EDIT
Here is Files.write source code:
public static Path write(Path path, byte[] bytes, OpenOption... options)
throws IOException
{
// ensure bytes is not null before opening file
Objects.requireNonNull(bytes);
try (OutputStream out = Files.newOutputStream(path, options)) {
int len = bytes.length;
int rem = len;
while (rem > 0) {
int n = Math.min(rem, BUFFER_SIZE);
out.write(bytes, (len-rem), n);
rem -= n;
}
}
return path;
}
As you can see it doesn't use NIO inside, only good old OutputStream.
EDIT 2
In fact Files.newOutputStream don't return FileOutputStream as I expected. It returns OutputStream defined in Channels.newOutputStream which use NIO inside.
A: *
*Files.write(...) use OutputStream instead of RandomAccessFile.getChannel(). it some different mechanisms, so better to google it for understand
*Files.write(...) much shorter and incapsulate logic of writting to file
*When you use such 'low' code, you need to look after many things. For example, in your example you didn't close your channel.
So, in conclusion, if you need to just write – better to use Files or another high-level API. If you need some 'additional' features during read/write, you need to use RandomAccessFile or InputStream/OutputStream
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55018607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Print dataframe to console during intermediate steps in dplyr chain While debugging dplyr chains in a function, I often want to be able to print intermediate changes to a data.frame to the console. How would I do this?
For example:
data(cars)
cars %>% group_by(speed) %>%
summarize(dist_mean = mean(dist)) %>%
[insert printing function] %>%
group_by(speed > 10) %>%
summarize(dist_mean = mean(dist_mean)) %>%
[insert printing function]
Is there something I can do to replace [insert printing function] to print the current state of the dataframe to the console, while still continuing the chain uninterrupted?
A: Try the T-pipe: %T>%.
From documentation:
Pipe a value forward into a function- or call expression and return the original value instead of the result. This is useful when an expression is used for its side-effect, say plotting or printing.
There is a good example of it here along with the other two less common pipe commands.
Inserting back into your original context:
data(cars)
cars %>% group_by(speed) %>%
summarize(dist_mean = mean(dist)) %T>%
print() %>%
group_by(speed > 10) %>%
summarize(dist_mean = mean(dist_mean)) %T>%
print()
Edit: As per @Ritchie Sacramento's comment the pipes are part of the magrittr package. They also appear to be re-exported by dplyr. If they don't work after calling library(dplyr) then you will need to call library(magrittr) to access them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70329179",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: how to change the color of an element that is in front of a background image in css? I put a background image in the body. I also have a different color for my menu box. I don't want to see the image in the menu box, how can I do that in CSS? Below is my code.
Thank you,
Avi
body{
font-family: sans-serif;
background-image: url("coffee_beans.jpeg");
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
}
.menu{
position: relative;
border: 2px solid red;
max-width: 613px;
width: 100%;
margin: auto;
background-color: rgba(255, 189, 109, 0.395);
}
A: Maybe you can try to remove the background-color alpha, it will not become transparent background.
.menu{
background-color: rgb(255, 189, 109);
}
If you must keep the background-color for transparent, you may create one more layer on the .menu div
body{
font-family: sans-serif;
background-image: url("https://dl.fujifilm-x.com/global/products/cameras/x-t3/sample-images/ff_x_t3_002.JPG");
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
}
.menub{
position: relative;
border: 2px solid red;
max-width: 613px;
width: 100%;
height:100px;
margin: auto;
background-color: white;
}
.menu{
width: 100%;
height:100px;
background-color: rgba(255, 189, 109,0.382);
}
<html>
<body>
<div class="menub">
<div class="menu"></div>
</div>
</body>
</html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73045853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Printing bits of a byte I am using "lahf" to store the flags in ah. I would like to output these values (1s and 0s) to see my flags, but I have no idea how. My Holder label in the code below outputs a decimal, is there a way to output a binary number instead? or should I go about this in a different way?
lahf ;moves flags to ah
mov [flagg], ah ;moves flags to label "flagg" in .bss (reserved 1 dword)
;later on...
mov eax,[flagg] ;moves the flag values into eax
push eax ;pushes eax onto stack
push Holder ;Holder is a label in .data ( "%d",0 )
call printf ;prints to screen
add esp, 8
A: You can't print binary with printf. You could print hex which is quite easy to relate to its binary representation (with %02X e.g.).
If you insist on printing binary, you would have to write a function for it. The function would be quite simple. If you have n bits, you could loop n times, do a shift by 1 and based on the carry either print 0 or 1. A bit more efficiently, you could store the result in a buffer and then print it all at once with %s.
Depending on how much memory you have (since it's x86 it's unlikely (impossible?) that it's embedded, so you probably do have a lot of memory), you can also store a table with the '0'-'1' representations of the bytes. That table would take 256*(8+1) bytes (one for '\0' if you use %s) for 8-bit values and you would need to hard-code it (perhaps generate with another program).
So far, I told you the two extremes: calculate all vs store all. The first can be slow and the second take a lot of space (and also tedious to generate).
To get the best of both worlds, you can have a table that stores the '0'-'1' representations of nibbles (4 bits). That table would be a mere 16*(8+1) bytes. Printing a byte would then be printing first its most significant and then its least significant nibble.
In C, this would look like this:
const char *bit_rep[16][5] = {
[ 0] = "0000", [ 1] = "0001", [ 2] = "0010", [ 3] = "0011",
[ 4] = "0100", [ 5] = "0101", [ 6] = "0110", [ 7] = "0111",
[ 8] = "1000", [ 9] = "1001", [10] = "1010", [11] = "1011",
[12] = "1100", [13] = "1101", [14] = "1110", [15] = "1111",
};
void print_byte(uint8_t byte)
{
printf("%s%s", bit_rep[byte >> 4], bit_rep[byte & 0x0F]);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19884828",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: XMLHttpRequest works but no response/status back on callback I have an XMLHttpRequest where i am sending an image across to be saved on my Amazon s3 bucket. It works correctly and the file goes to my bucket but i am getting no response back saying it is in process or has successfully uploaded. My code is below:
Javascript code in html page:
var ajax = new XMLHttpRequest();
ajax.open("POST",'http://www.xxxx.php',false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(theImage);
ajax.onreadystatechange=function(){
if (ajax.readyState==4 && ajax.status==200) {
console.log('success');
}
else {
console.log('ongoing...');
}
}
PHP code in xxxx.php:
<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"])){
$imageData = $GLOBALS['HTTP_RAW_POST_DATA'];
$filteredData = substr($imageData, strpos($imageData, ",")+1);
$imgFileString = base64_decode($filteredData);
$s3Filename = time().'.png';
if($s3->putObjectString($imgFileString, $bucket , $s3Filename, S3::ACL_PUBLIC_READ) ){
echo "SUCCESS";
}
else{
echo "ERROR";
}
}
else {
echo "EMPTY";
}
?>
How can i get a callback to say when the upload has successfully been uploaded or if an error has occurred?
A: ajax.open("POST",'http://www.xxxx.php',false);
^^^^^^
You are making a synchronous request, so the request is being made and the response received before you assign your event handler. Don't do that. Remove false (or change it to true).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23657496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to load last on changed Google sheet data and send an email as PDF using script I have written a script function to get google sheet data and send the email as an attached PDF. I have used here pivot tables in the google sheet.
The problem is here. after the filtered pivot table and then if I send an email.it sent only without filter data. That means is default values only export as pdf.
How to send an email pdf with current filtered data?
function sendEmail(){
try {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var getTabsheetName=ss.getSheetByName('report');
var url = 'https://docs.google.com/a/mydomain.org/spreadsheets/d/'
+ ss.getId() //Your File ID
+ '/export?exportFormat=pdf&format=pdf'
+ '&size=LETTER'
+ '&portrait=true'
+ '&fitw=true'
+ '&top_margin=0.50'
+ '&bottom_margin=0.50'
+ '&left_margin=0.50'
+ '&right_margin=0.50'
+ '&sheetnames=false&printtitle=false&pagenumbers=true'
+ '&pagenum=false'
+ '&gridlines=false'
+ '&fzr=FALSE'
+ '&gid='
+ getTabsheetName.getSheetId(); //the sheet's Id
var emailsheet=ss.getSheetByName('Email');
var emailContentsheet=ss.getSheetByName('EmailContent');
var subject = emailContentsheet.getRange(2,1).getValue();
var n=emailsheet.getLastRow();
var params = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var blob = UrlFetchApp.fetch(url, params).getBlob().setName('Report.pdf');
for (var i = 2; i < n+1 ; i++ ) {
// SpreadsheetApp.flush();
var emailAddress = emailsheet.getRange(i,2).getValue();
var name=emailsheet.getRange(i,1).getValue();
var message = emailContentsheet.getRange(2,2).getValue();
var returnData = [name,message];
var templ = HtmlService.createTemplateFromFile('index');
templ.data = returnData;
var htmlboday = templ.evaluate().getContent();
MailApp.sendEmail({
to: emailAddress,
subject: subject,
htmlBody: htmlboday,
attachments:[blob]
});
}
} catch (f) {
Logger.log(f.toString());
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64946000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Parameterization in adf? If we define array type parameters outside all activity then want to apply it in dataset in copy activity in foreach where string type parameters is there then how can we access these parameters ?
A: I'm assuming, you are asking for source dataset. For Sink dataset as well, it will follow same steps but you will have to do the same things in "Sink" tab.
Here, I'm doing it for "Source".
*
*Take array as parameter (outside of all activities that means it is a pipeline parameter).
*Choose "Add dynamic content"
*Choose pipeline array parameter "test_param", for which "ForEach" activity will run and click finish.
*Add New source dataset "test_Parquet" using "+" symbol.
*Go to Source dataset "test_Parquet" -> Parameters and add new parameter,<here I've added "param" with datatype String>
*After adding that, return to "Copy activity" and you will see "param (your parameter)" under "DataSet Properties":
*Click on "add dynamic content" and add "pipeline array parameter element" to the dataset parameter value.
*Click on "ForEach iterator -> current item" and click Finish.
This process will add the pipeline array parameter elements to Copy Activity source dataset.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67616925",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rest Webservices I am developing a file upload service and using org.glassfish.jersey.media.multipart.FormDataContentDisposition .getFilename
but it gives the filename along with the complete path which fails creating the file.
If I change to use the fileName in debug mode it works.
How to get just the uploaded file name rather than the complete path?
I am using the following dependencies:
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey2.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey2.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>${jersey2.version}</version>
</dependency>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40622254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android custom progress bar with .gif file In my app i have a custom progress bar
progress.xml
<ProgressBar
android:id="@+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:progressDrawable="@drawable/loader" />
my gif file
I want to create a progress bar with this image
In other word i want to show this image whenever i download data from server and remove it after downloading the data
or you can say , how to show this image as a progress bar
A: *
*First Conver your Gif image to png Slice image sequence.
*Declare Your Progress bar as Image view.
<ImageView
android:id="@+id/main_progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="visible" />
*Create .xml file in drawable folder using your .png sequence image those are generated from gif. In this case, Loading_web_animation.xml
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
<item
android:drawable="@mipmap/wblod_0"
android:duration="40" />
<item
android:drawable="@mipmap/wblod_1"
android:duration="40" />
<item
android:drawable="@mipmap/wblod_2"
android:duration="40" />
<item
android:drawable="@mipmap/wblod_3"
android:duration="40" />
<item
android:drawable="@mipmap/wblod_4"
android:duration="40" />
<item
android:drawable="@mipmap/wblod_5"
android:duration="40" />
<item
android:drawable="@mipmap/wblod_6"
android:duration="40" />
<item
android:drawable="@mipmap/wblod_7"
android:duration="40" />
<item
android:drawable="@mipmap/wblod_8"
android:duration="40" />
<item
android:drawable="@mipmap/wblod_9"
android:duration="40" />
<item
android:drawable="@mipmap/wblod_10"
android:duration="40" />
<item
android:drawable="@mipmap/wblod_11"
android:duration="40" />
</animation-list>
*In Main Activity set the code like,
private AnimationDrawable animationDrawable;
private ImageView mProgressBar;
mProgressBar.setBackgroundResource(R.drawable.loading_web_animation);
animationDrawable = (AnimationDrawable)mProgressBar.getBackground();
mProgressBar.setVisibility(View.VISIBLE);
animationDrawable.start();
mProgressBar.setVisibility(View.GONE);
animationDrawable.stop();`
A: I think I'm late to answer this, But you can try this also.
XML
<FrameLayout
android:id="@+id/progress_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true">
<ProgressBar
android:id="@+id/circular_progress"
android:layout_width="100dp"
android:layout_height="100dp"
android:indeterminateDrawable="@drawable/my_progress_indeterminate"
/>
<TextView
android:id="@+id/circular_progress_counter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="@dimen/text_size_big"
android:textColor="@color/white"
android:text="10"/>
</FrameLayout>
my_progress_indeterminate.xml
<?xml version="1.0" encoding="utf-8"?>
<animated-rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/process_icon"
android:pivotX="50%"
android:pivotY="50%" />
In Java File login to show Timer. here I used 10 second timer.
private void progressTimer() {
handler = new Handler();
if (maxCount >= 0) {
handler.postDelayed(new Runnable() {
@Override
public void run() {
/*
Logic to set Time inside Progressbar
*/
mCircularProgressCounter.setText(maxCount+"");
maxCount = maxCount - 1;
pickupTimer();
}
}, 1000);
}
}
Result
A: Put your gif image in /res/raw folder
In your class declare mProgressDialog
TransparentProgressDialog mProgressDialog;
then use following code to show progress dialog
if (mProgressDialog == null)
mProgressDialog = new TransparentProgressDialog(this);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
mProgressDialog.setTitle(getResources().getString(R.string.title_progress_dialog));
mProgressDialog.setCancelable(false);
mProgressDialog.show();
Create a class TransparentProgressDialog where .gif can be loaded using Glide library.
public class TransparentProgressDialog extends Dialog {
private ImageView iv;
public TransparentProgressDialog(Context context) {
super(context, R.style.TransparentProgressDialog);
WindowManager.LayoutParams wlmp = getWindow().getAttributes();
wlmp.gravity = Gravity.CENTER_HORIZONTAL;
getWindow().setAttributes(wlmp);
setTitle(null);
setCancelable(false);
setOnCancelListener(null);
LinearLayout layout = new LinearLayout(context);
layout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
iv = new ImageView(context);
GlideDrawableImageViewTarget imageViewTarget = new GlideDrawableImageViewTarget(iv);
Glide.with(context).load(R.raw.gif_loader).into(imageViewTarget);
layout.addView(iv, params);
addContentView(layout, params);
}
@Override
public void show() {
super.show();
}
}
A: I solved it before on this post easily:
Custom progress bar with GIF (animated GIF)
Use an ImageView that shows an Animated GIF and when need to show waiting make it visible and when works all will be done, make it Gone!
A: My solution is to use an Animated icon.
1°) Create an XML "animated" in Drawable :
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/micro_1" android:duration="200" />
<item android:drawable="@drawable/micro_2" android:duration="200" />
<item android:drawable="@drawable/micro_3" android:duration="200" />
<item android:drawable="@drawable/micro_4" android:duration="200" />
<item android:drawable="@drawable/micro_3" android:duration="200" />
<item android:drawable="@drawable/micro_2" android:duration="200" />
</animation-list>
2°) Put an imageview in your layout
3°) Put the following code in your activity :
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
ProgressDialog progressBar;
private int progressBarStatus = 0;
private Handler progressBarHandler = new Handler();
private ImageView micButton;
//-- for testing progress bar
private long fileSize = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//-- declare animation
final AnimationDrawable[] rocketAnimation = new AnimationDrawable[1];
final ImageView micButton = findViewById(R.id.mic_button);
micButton.setBackgroundResource(R.drawable.micro_1);
//-- button listener
micButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//-- init button with animation
micButton.setBackgroundResource(R.drawable.mic_image);
rocketAnimation[0] = (AnimationDrawable) micButton.getBackground();
startprogress(rocketAnimation[0]);
}
});
}
public void startprogress(final AnimationDrawable rocketAnimation) {
rocketAnimation.start();
progressBar = new ProgressDialog(MainActivity.this);
//--reset filesize for demo
fileSize = 0;
//-- thread for demo
new Thread(new Runnable() {
public void run() {
while (progressBarStatus < 100) {
// process some tasks
progressBarStatus = doSomeTasks();
// your computer is too fast, sleep 1 second
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
// ok, file is downloaded,
if (progressBarStatus >= 100) {
// sleep 2 seconds, so that you can see the 100%
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// close the progress bar dialog
progressBar.dismiss();
if(rocketAnimation.isRunning()){
rocketAnimation.stop();
}
}
}
}).start();
}
// file download simulator... a really simple
public int doSomeTasks() {
while (fileSize <= 1000000) { //1000000
fileSize++;
if (fileSize == 100000) {
return 10;
} else if (fileSize == 200000) {
return 20;
} else if (fileSize == 300000) {
return 30;
} else if (fileSize == 400000) {
return 40;
} else if (fileSize == 500000) {
return 50;
} else if (fileSize == 600000) {
return 60;
}
}
return 100;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26302282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: LINQ GroupBy Count I've got table which contains of EmployeeID, ProductID and ProductName. The table is called EmployeeProduct and I'd like to make query (which I'll bind to DataGrid) which will get me a result like this:
Employee ID| ProductID | Name | Count(ProductID)
1 | 2 | XYZ | 3
1 | 5 | ZXY | 2
2 | 2 | XYZ | 1
I tried to get sth like this by this query, but it doesn't take a result...
// UPDATED - Now I try to do this this way, but still have no result... //
(Home.xaml.cs)
public class ProductCount
{
public int ProductNumber { get; set; }
public int EmployeeNumber { get; set; }
public int CountProducts { get; set; }
}
public IQueryable<ProductCount> CountProducts()
{
var data = from b in _employ.EmployeeProduct
group b by new { b.EmployeeID, b.ProductID } int z
select new ProductCount { EmployeeNumber = z.Key.EmployeeID, ProductNumber = z.Key.ProductNumber, CountProducts = z.Count()};
return data.AsQueryable();
}
and later in code I'd like to bind this to my datagrid, but unfortunately it don't causes error but if I do this:
dg.ItemsSource = CountProducts();
it doens't show anything ...
A: Here's a couple of way to do this:
var employeeProducts = new List<EmployeeProduct>();
employeeProducts.Add(new EmployeeProduct(1, 2, "XYZ"));
employeeProducts.Add(new EmployeeProduct(1, 5, "ZXY"));
employeeProducts.Add(new EmployeeProduct(2, 2, "XYZ"));
var way1 = employeeProducts.Select(
ep => new ProductCount
{
ProductNumber = ep.ProductID,
EmployeeNumber = ep.EmployeeID,
CountProducts = employeeProducts.Count(epc => epc.ProductID == ep.ProductID)
});
var way2 = employeeProducts
.GroupBy(ep => ep.ProductID)
.SelectMany(epg => epg.Select(
ep => new ProductCount
{
ProductNumber = ep.ProductID,
EmployeeNumber = ep.EmployeeID,
CountProducts = epg.Count()
}));
A: I'm thinking the query will look something like this
EntityQuery<EmployeeProduct> query = from c in _employ.CountProduct()
group c by new {c.UserId, c.ProductId, c.Name}
into g
select new {
g.UserId,
g.ProductId,
g.Name,
Count = g.Count()
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8919100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: options.remove(); doesn't work, weird behaviour I've got a paypal select, where I have different options. I want to choose just one option and erase the rest of them. To do so I've got this piece of code:
var selectobject=document.getElementById("os0"); //this is the select
for (var i=0; i<selectobject.length; i++){
if (selectobject.options[i].value != <?php echo $people; ?> ){
selectobject.remove(i);
alert(i);
}
}
And here is the select from paypal,
<input type="hidden" name="on0" value="people">people</td></tr><tr><td><select name="os0" id="os0">
<option id="1" value="1">1 €123,97 EUR</option>
<option id="2" value="2">2 €249,94 EUR</option>
<option id="3" value="3">3 €371,91 EUR</option>
<option id="4" value="4">4 €495,88 EUR</option>
<option id="5" value="5">5 €619,85 EUR</option>
<option id="6" value="6">6 €743,82 EUR</option>
<option id="7" value="7">7 €867,79 EUR</option>
<option id="8" value="8">8 €991,76 EUR</option>
<option id="9" value="9">9 €1.115,73 EUR</option>
<option id="10" value="10">10 €1.239,70 EUR</option>
</select>
So what happens is super weird, it erases just tha paar numbers, and just counts until 5 or 6, the result if I send for example 1 persons is:
*
*1 €123,97 EUR
*3 €371,91 EUR
*5 €619,85 EUR
*7 €867,79 EUR
*9 €1.115,73 EUR
and if I choose 2 people:
*
*2 €249,94 EUR
*4 €495,88 EUR
*6 €743,82 EUR
*8 €991,76 EUR
*10 €1.239,70 EUR
I've got also an alert to tell me where is "i" and it just goes up to 5 or 4, don't understand.
A: When you remove the option at i, you're shuffling all the other options down; so now, the next option is at i. But then because you're using a for loop, you're incrementing i — and you never looked at the option after the option you removed.
Instead, use a while loop and only increment i if you don't remove the option.
var selectobject = document.getElementById("os0"); //this is the select
var i = 0;
while (i < selectobject.length) {
if (selectobject.options[i].value != <?php echo $people; ?> ){
selectobject.remove(i);
alert(i);
} else {
++i;
}
}
Live Example using 3 (and without the alert):
var people = 3;
var selectobject = document.getElementById("os0"); //this is the select
var i = 0;
while (i < selectobject.length) {
if (selectobject.options[i].value != people){
selectobject.remove(i);
} else {
++i;
}
}
<select name="os0" id="os0">
<option id="1" value="1">1 €123,97 EUR</option>
<option id="2" value="2">2 €249,94 EUR</option>
<option id="3" value="3">3 €371,91 EUR</option>
<option id="4" value="4">4 €495,88 EUR</option>
<option id="5" value="5">5 €619,85 EUR</option>
<option id="6" value="6">6 €743,82 EUR</option>
<option id="7" value="7">7 €867,79 EUR</option>
<option id="8" value="8">8 €991,76 EUR</option>
<option id="9" value="9">9 €1.115,73 EUR</option>
<option id="10" value="10">10 €1.239,70 EUR</option>
</select>
A: When you remove items while iterating over them, the element currently processed in i will be offset each time an item is removed.
If you remove them in reverse you shouldn't have the issue. See example below if element with value 9 was desired.
document.addEventListener('DOMContentLoaded', function() {
var selectobject = document.getElementById("os0"); //this is the select
for (var i = selectobject.length - 1; i >= 0; i--) {
if (selectobject.options[i].value != 9) {
selectobject.remove(i);
}
}
}, false);
<input type="hidden" name="on0" value="people">people</td>
</tr>
<tr>
<td><select name="os0" id="os0">
<option id="1" value="1">1 €123,97 EUR</option>
<option id="2" value="2">2 €249,94 EUR</option>
<option id="3" value="3">3 €371,91 EUR</option>
<option id="4" value="4">4 €495,88 EUR</option>
<option id="5" value="5">5 €619,85 EUR</option>
<option id="6" value="6">6 €743,82 EUR</option>
<option id="7" value="7">7 €867,79 EUR</option>
<option id="8" value="8">8 €991,76 EUR</option>
<option id="9" value="9">9 €1.115,73 EUR</option>
<option id="10" value="10">10 €1.239,70 EUR</option>
</select>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48947642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: QWidget with doubleclick I want to be able to double click a QPushbutton instead of a single click.
What I tried:
connect(pb, SIGNAL(doubleClicked()), this, SLOT(comBtnPressed()));
Error says "QObject::connect: No such signal QPushButton::doubleClicked()"
I chose QPushButton initially, but for my purpose, you can suggest change to other object if it can make a doubleclick event. Not necessarily be a push button.
Thank you Masters of Qt and C++.
A: A simple solution is to create our own widget so we overwrite the mouseDoubleClickEvent method, and you could overwrite paintEvent to draw the widget:
#ifndef DOUBLECLICKEDWIDGET_H
#define DOUBLECLICKEDWIDGET_H
#include <QWidget>
#include <QPainter>
class DoubleClickedWidget : public QWidget
{
Q_OBJECT
public:
explicit DoubleClickedWidget(QWidget *parent = nullptr):QWidget(parent){
setFixedSize(20, 20);
}
signals:
void doubleClicked();
protected:
void mouseDoubleClickEvent(QMouseEvent *){
emit doubleClicked();
}
void paintEvent(QPaintEvent *){
QPainter painter(this);
painter.fillRect(rect(), Qt::green);
}
};
#endif // DOUBLECLICKEDWIDGET_H
If you want to use it with Qt Designer you can promote as shown in the following link.
and then connect:
//new style
connect(ui->widget, &DoubleClickedWidget::doubleClicked, this, &MainWindow::onDoubleClicked);
//old style
connect(ui->widget, SIGNAL(doubleClicked), this, SLOT(onDoubleClicked));
In the following link there is an example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47383722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I create recipe in calibre to fetch full content from xml instead webpage? I have a xml rss feed like below,
http://www.prajavani.net/rss.xml
where description contains body of news/article and also contains image. when i create recipe in calibre, it fetches content from web page using link in xml, but it doesnt fetch correctly and doesnt read image. But xml contains all content need title, image, body(description), image. How can i make recipe to fetch every thing from xml itself instead downloading from each webpage.
hope understood my situation.
Regards , Abdul
A: Just got answer.
Set
use_embedded_content = True
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41789072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Email template font not working on tablet and phone devices Agency FB font works fine on desktop view on my email template when I send it out but in the device view it reverts back to the PT-sans.
I have applied the Agency FB font anywhere it says font family and I included the url link too. I use MailChimp to send the emails out, any ideas?
A: MailChimp's docs state that support for custom fonts in emails is limited.
Elements to Avoid > Custom Fonts
MailChimp’s Drag and Drop Editor provides web-safe fonts only. Most email clients don’t support CSS properties like @font-face, @import, and that import custom fonts into web pages. For consistent display, use web-safe fonts.
Or use images to display custom-font headlines, and include the body content as text. Without this balance of text and images, spam filters can flag your campaign.
from Limitations of HTML Email
Perhaps they are trying to protect you from seeing a preview different than what most of your users will see. However it does seem you can override this default with a custom template:
Note
If you’re comfortable with coding or if you have access to a developer, you can design custom coded templates that contain HTML elements with limited email client support, but we don’t always recommend it. Keep in mind that MailChimp support agents won’t be able to help you troubleshoot issues with your custom code.
Update: In the custom template docs (see Experimenting with Web Fonts), they do discourage use, but claim <link>, @import, @font-face, etc will work as expected in mail clients whose browsers do support custom fonts.
A: well, I think is more matter of what email client (or browser) you are using on mobile device, unfortunately it's highly possible that on older devices etc, you won't be able to get your font, especially in old mail mobile clients,
here is something what I consider as a quite ok solution ( yep, not the best one probably ), but if your mail looks good in Outlook 2010 on your desktop, then it should be ok in most of the other clients/browsers,
Outlook 2010 is could be such a pain, that if you make things work in it, that should cover the other environments
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38945662",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: UIAlertView with UITextField I was adding UITextfield to the UIAlertView as shown:
UIAlertView *addingBookAlert=[[UIAlertView alloc]initWithTitle:@"Enter Note" message:NULL delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
addingBookAlert.tag=kAddNoteAlertTag;
myTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 45.0, 260.0, 25.0)];
myTextField.placeholder=@"Book Mark";
[myTextField becomeFirstResponder];
[myTextField setBackgroundColor:[UIColor whiteColor]];
myTextField.textAlignment=UITextAlignmentCenter;
myTextField.delegate=self;
CGAffineTransform myTransform = CGAffineTransformMakeTranslation(0, 60);
[addingBookAlert setTransform:myTransform];
[addingBookAlert addSubview:myTextField];
[addingBookAlert show];
I Portrait its showing with textfield,cancel and ok button.But in Landscape its appearing only textfield,cancel and ok button not appearing.
How to resolve this...
Thanks in Advance.
A: Use alertview like this
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Enter Name" message:@"" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Submit", nil];
alert.alertViewStyle=UIAlertViewStylePlainTextInput;
UITextField *textField=[alert textFieldAtIndex:0];
textField.delegate=self;
[alert show];
[alert release];
And access the value of textfield like this
#pragma mark alert button view button
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(buttonIndex==1)
{
UITextField *textField=[alertView textFieldAtIndex:0];
}
}
A: In iOS 8 UIAlertview has been deprecated. UIAlertController is used instead of that.
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Add Fruit" message:@"Type to add a fruit" preferredStyle:UIAlertControllerStyleAlert];
[alert addTextFieldWithConfigurationHandler:^(UITextField *textField){
textField.placeholder = @"Fruit";
}];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
UITextField *textFiel = [alert.textFields firstObject];
[fruits addObject:textFiel.text];
}];
[alert addAction:okAction];
[self presentViewController:alert animated:YES completion:nil];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18014443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP check if today is in between two dates Consider following code:
$today = date("d/m/Y");
$start_date = '20/11/2014';
$time1 = strtotime($start_date1);
$start_date1 = date('d/m/Y',$time1);
$end_date = '20/01/2015';
$time2 = strtotime($end_date1);
$end_date1 = date('d/m/Y',$time2);
if( $start_date1 <= $today && $end_date1 >= $today)
echo "yes";
else
echo 'no';
Even though $today is in between those start and end date, I get "no" in return. What might be the problem here? I just wanna check if today is in between those dates. Start date and end date are saved as string in DB.
A: Try this:
<?php
$now = new DateTime();
$startdate = new DateTime("2014-11-20");
$enddate = new DateTime("2015-01-20");
if($startdate <= $now && $now <= $enddate) {
echo "Yes";
}else{
echo "No";
}
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27863791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to dm all moderators in discord by discord.py, not only one? I have this code:
async def report(ctx, member: discord.Member, *, arg):
role = ctx.guild.get_role(9999999999999) # Imagine that 9999999999999 is moderator role id
members = ctx.guild.members
await ctx.channel.send('Your complaint was sent to moderators!', delete_after=10)
for i in role.members:
await i.send(f'{ctx.author.mention} sent a complaint on {member.mention} with reason:\n**{arg}**')
await ctx.message.delete()
The problem is that when I write $report @user reason, only one moderator receives this report in private messages, not all. There are 3 moderators on the server, and for some reason only one receives a message in the DM, and not all 3 moderators.
How to fix this? I would be very grateful for help.
A: Put the await ctx.message.delete() out of your for loop. If a message is deleted and you're trying to delete it again it will throw an error.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68045502",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Remove next character jQuery (no html elements given) Suppose the following markup:
<body>
<a href=# name="uniqueLink1">link</a> [ some text here
<a href=# name="uniqueLink2">link</a> [ some more text here
</body>
Is there anyway to use jQuery to remove the ' [ ' from the top line but not the bottom one?
Note: I don't have the access to the markup, but I can add elements, divs etc. using jQuery if I wanted to. BUT jQuery does not need to target the string of ' ] ' in particular - it can be something like "remove next 3 characters after uniqueLink1.
A: jQuery doesn't really help much with manipulating text nodes, but here it is:
var tn = $('a[name="uniqueLink1"]')[0].nextSibling;
tn.nodeValue = tn.nodeValue.replace('[', '');
Demo
$()[n] is a shorthand for $().get(n), so [0] will return a reference to the first matched DOM element inside the jQuery object, the uniqueLink1 anchor.
nextSibling, as the name implies, grabs the next sibling node. In this case, the text node that follows the given anchor element.
nodeValue gets and sets the content of the text node.
String.replace() given a string as the first argument replaces only the first occurrence, thus this should be enough enough given the DOM structure is similar to the posted one.
A: This will filter the textnodes, and remove a [ from the first on it finds:
var textNode = $('body').contents().filter(function() {
return this.nodeType == 3;
}).eq(1);
textNode.replaceWith(document.createTextNode(textNode[0].textContent.replace('[','')));
Example fiddle
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17719678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Ordering the results of an file with ArrayList and compareTo I have to order an arrayList that contains lines from a file by account ID and then by salary to get this result:
CuentaAhorro : 11111111A (Alicia) Saldo 111,11
CuentaAhorro : 12345678A (Lucas) Saldo 5100,00
CuentaCorriente: 22222222B (Peio) Saldo 222,22
CuentaAhorro : 33333333C (Isabel) Saldo 4433,33
CuentaCorriente: 33333333C (Isabel) Saldo 3333,33
CuentaAhorro : 87654321A (Asier) Saldo 3000,00
My arrayList calls the compareTo method from Bank.java.
public void ordenarCuentas() {
Collections.sort(cuentas);
}
The call is to the method compareTo in an abstract class called Account with the comparable interface:
@Override
public int compareTo(Cuenta unaCuenta) {
Cliente unTitular = unaCuenta.titular;
if(unTitular.toString().equals(unaCuenta.titular.toString()) == true) {
return 0;
// if(saldo < unaCuenta.saldo) {
// return -1;
// } else if (saldo > unaCuenta.saldo) {
// return 1;
// } else {
// return 0;
// }
}
return -1;
}
I need to check if the object 'Cuenta unaCuenta' passed as a parameter has the same account number as another and then sort by the amount of money in the account, however I am not sure how to get the condition right, as you can see, with the commented if I get the salary in the right descending order but not the account IDs.
The object Cuenta unaCuenta contains titular which contains account number and name.
The object Cliente unTitular contains the account number and name.
Could somebody lend me a hand please?
A: I am not able understand it very clearly because of language barrier
But if you have a arraylist you can call sort method on it an pass a comparator to get the desired sorting , something like below.
It is just to give you an idea
ArrayList<String> list = new ArrayList<>();
list.sort(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if(o1.account.equals(o2.account)) return 0;
return o1.amount - o2.amount;
}
});
as Lambda
ArrayList<String> list = new ArrayList<>();
list.sort((o1,o2) ->
if(o1.account.equals(o2.account)) return 0;
return o1.amount - o2.amount;
});
A: Thank you everyone for the comments. Next time i'll translate the Spanish code to English. I'll post my solution incase someone comes across this question.
(in my case I had to use a comparable interface and a compareTo method).
@Override
public int compareTo(Account anAccount) {
String b = this.title.toString();
Client aTitle = anAccount.title;
String c = aTitle.toString();
if(b.compareTo(c) == 0) {
if(balance == anAccount.balance) {
return 0;
} else if (balance < anAccount.balance) {
return 1;
} else {
return -1;
}
}
return b.compareTo(c);
}
As stated, I had to compare both object values first, if they are the same I then check the condition of the balance to change the order.
-1 = object is less than the parameter.
0 = when both objects are the same.
1 = the object is more than the parameter.
And I called the method from the Bank.java class with:
Collections.sort(cuentas);
Where cuentas is the ArrayList.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60887212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C# Powershell BeginInvoke Completed Event not Fired This is a sample code to test a functionality, it has no use in itself.
I want to fire the completed event of the PSDataCollection object.
I found in Microsoft that the CloseAll method in C++ should be called to let BeginInvoke know that there are no commands left, I'm not sure that this concept applies in C#, I cannot find this method anywhere. The code works because I used the Completed state from InvocationStateChanged. I do not understand why this one is fired and not the other. I searched for days for an answer but there's not much to find.
Thanks
Jean
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
namespace PSAsync
{
public partial class Form1 : Form
{
RunspacePool RSPool;
StringBuilder stringBuilder;
PowerShell Ping1;
IAsyncResult Ping1AsyncResult;
PSDataCollection<PSObject> Output;
public Form1()
{
InitializeComponent();
RSPool = RunspaceFactory.CreateRunspacePool(1, 4);
RSPool.Open();
stringBuilder = new StringBuilder();
}
private void btnPing1_Click(object sender, EventArgs e)
{
Ping1 = PowerShell.Create();
//Instead we rely on the InvocationStateChanged event
lblPing1.Text = "Status:" + Ping1.InvocationStateInfo.State.ToString();
Ping1.InvocationStateChanged += Ping1_InvocationStateChanged;
Ping1.RunspacePool = RSPool;
Ping1.AddCommand("ping").AddArgument("192.168.1.1");
Output = new PSDataCollection<PSObject>();
Output.Completed += Test_Completed;//never gets fired
Output.DataAdded += Output_DataAdded;
Ping1.Streams.Error.DataAdded += Error_DataAdded;
Ping1AsyncResult = Ping1.BeginInvoke<PSObject, PSObject>(null,Output);
}
private void Error_DataAdded(object sender, DataAddedEventArgs e)
{
throw new NotImplementedException();
}
private void Output_DataAdded(object sender, DataAddedEventArgs e)
{
PSDataCollection<PSObject> myp = (PSDataCollection<PSObject>)sender;
Collection<PSObject> results = myp.ReadAll();
foreach (PSObject result in results)
{
this.Invoke((MethodInvoker)delegate
{
// Show the current time in the form's title bar.
this.txtOutput.Text = txtOutput.Text + result.ToString()+Environment.NewLine;
});
}
}
private void Test_Completed(object sender, EventArgs e)
{
throw new NotImplementedException();
}
private void Ping1_InvocationStateChanged(object sender, PSInvocationStateChangedEventArgs e)
{
Console.WriteLine("Invocation State Changed:"+e.InvocationStateInfo.State.ToString());
this.Invoke((MethodInvoker)delegate
{
this.lblPing1.Text = "Status:"+e.InvocationStateInfo.State.ToString();
});
if (e.InvocationStateInfo.State == PSInvocationState.Completed)
{
this.Invoke((MethodInvoker)delegate
{
this.txtOutput.Text = txtOutput.Text +"Status:" + e.InvocationStateInfo.State.ToString();
});
}
}
private void btnQuit_Click(object sender, EventArgs e)
{
RSPool.Close();
this.Close();
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66337708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Custom number to binary? I'm learning C# and im trying to get a custom number to convert to binary. I've looked up several forms here on stack overflow and they have similar code to this, but it doesn't work. Any ideas?
Console.WriteLine("You have chosen binary, input a number then it will be converted to binary.");
string num1input = Console.ReadLine();
double num1 = double.Parse(num1input);
var binary = Convert.ToString(num1, 2);
Console.WriteLine("{0} converted to binary is {1} " ,num1, binary);
A: It's not clear from your question if you are trying to convert an integer or a floating point value to a binary string representation.
For an integer, use this code:
void Main()
{
Console.WriteLine("You have chosen binary, input a number then it will be converted to binary.");
string num1input = Console.ReadLine();
int num1 = int.Parse(num1input);
var binary = Convert.ToString(num1, 2);
Console.WriteLine("{0} converted to binary is {1} ", num1, binary);
}
For a double, this code might be what you want:
void Main()
{
Console.WriteLine("You have chosen binary, input a number then it will be converted to binary.");
string num1input = Console.ReadLine();
double num1 = double.Parse(num1input);
long bits = BitConverter.DoubleToInt64Bits(num1);
var binary = Convert.ToString(bits, 2);
Console.WriteLine("{0} converted to binary is {1} ", num1, binary);
}
A: I found this exercise interesting, so here is what I did :
public IEnumerable<char> ConvertToBase2(int myNumber) {
while(myNumber != 0) {
var returnValue = (myNumber%2 == 0) ? '0' : '1';
myNumber = (myNumber % 2 == 0) ? myNumber / 2 :
(myNumber - 1) / 2;
yield return returnValue;
}
}
Console.Write(String.Concat(
ConvertToBase2(9).Reverse()
));
It works only for integers. I don't remember exactly how floating points numbers are implemented.
By the way, this is a better answer ;-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50472144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Changing main form button visibility from the subform I've been trying to make a button disappear when a new insert is made and one of the fields is empty, problem is the field is on a subform (data sheet view) and the button on the main form I've been trying the following code with no success.
If Me.Produto = "" Then
[Orçamentos]!Comando33.Visible = False
[Orçamentos]!Comando47.Visible = False
Me.Descrição.Visible = False
End If
Any advice?
A: Assuming Me is the sub form, and Orçamentos is the main form:
If Me.Produto = "" Then
Me.Parent!Comando33.Visible = False
Me.Parent!Comando47.Visible = False
Me.Descrição.Visible = False
End If
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37164938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: dynamically load images from server in jtinder i am using jtinder for creating tinder like effect. here is the library.
https://github.com/do-web/jTinder
i want to add images dynamically when users are on 4th image out of 5 images loaded when page was called first time.
here is the javascript someone used to make dynamic call but i am not getting how to call data from server as pattern and name of all images will be different everytime.
$.fn[ pluginName ] = function (options) {
this.each(function () {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName, new Plugin(this, options));
}
else {
$.data(this, "plugin_" + pluginName).bindNew(this);
}
});
return this;
};
any help to make jquery/ajax call to server after 4th image is swiped will be great help
A: Add a destroy method to the plugin prototype in jTinder.js:
destroy: function(element){
$(element).unbind();
$(this.element).removeData();
}
like so:
init: function (element) {
container = $(">ul", element);
panes = $(">ul>li", element);
pane_width = container.width();
pane_count = panes.length;
current_pane = panes.length - 1;
$that = this;
$(element).bind('touchstart mousedown', this.handler);
$(element).bind('touchmove mousemove', this.handler);
$(element).bind('touchend mouseup', this.handler);
},
destroy: function(element){
$(element).unbind();
$(this.element).removeData();
}
showPane: function (index) {
panes.eq(current_pane).hide();
current_pane = index;
},
And then create a function, addcard() where you first fetch the data you want from a JSON source, add it to the main under the tinderslide, delete and then reinitialize the jTinder event.
function addcard(){
$.getJSON("example.json",function(data){
//assign the data
var elem="<li>"+data+"</li>";
//delete existing jTinder event
$("#tinderslide").data('plugin_jTinder').destroy();
//reinitialize new jTinder event
$("#tinderslide").jTinder({
onDislike:function(){
doSomething();
}
onLike:function(){
doSomethingElse();
}
});
});
}
And call addcard() whenever you need to add a new card.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44015769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to debug django web application using specific port & localhost in visual studio code? I want to debug django web application using visual code for that I have found solution that I have to edit launch.json for debugging django web application.
launch.json
"name": "Python: Django",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}\\web_app_test\\manage.py",
"port": "8005",
"address" : "192.168.1.195",
I have implemented above code in launch.json but still I am not able to start my web application on above port it automatically running on default port & localhost.
A: Have you tried using 0.0.0.0? that will map it to your local IP, and you will be able to access it within your network if you know your IP.
A: Yes I am able to debug it finally using below code after lots of search on google.
we have to define them into args using ipaddress & port.
"args": [
"runserver",
"--noreload",
"192.168.1.195:8005",
],
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58096897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Connecting Hyperledger Composer to Fabric: Error trying install composer runtime While following the tutorial on this link, I encontered the following error under the section "Deploy to the running Hyperledger Fabric". My Hyperledger Fabric is not running and I do not know why. The error I get is shown below:
tom@tom:~/hyperledger/my-network/dist$ composer network deploy -a my-network.bna -p hlfv1 -i PeerAdmin -s randomString
Deploying business network from archive: my-network.bna
Business network definition:
Identifier: [email protected]
Description: My Commodity Trading network
✖ Deploying business network definition. This may take a minute...
Error: Error trying deploy. Error: Error trying install composer runtime. Error: Connect Failed
Command failed
When I use docker ps -a, no hyperledger containers are shown to have run. Where could I have gone wrong?
A: I just realized I needed to install docker-compose which deals with running multiple docker containers instead of just using docker client.
For docker-compose installation, I consulted the manual
A: I think you did not start your fabric, if you are developing locally. Please look at https://hyperledger.github.io/composer/installing/development-tools.html for the environment setup and the scripts you need to run inorder to have a local fabric.
When you run docker ps you should see something like this docker list of containers
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46588275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Get id of element on button and auto click using jquery I need to autosubmit a single button on a page that may have a selection of multiple buttons. The challenge is that the buttons do not have a name or ID reference, and rather, each input element uses a "tabindex=n" ID. The quick and easy would have been to add a unique Name or ID to the form, but we do not have access to the server side code so it must all be done client side.
I've tried various approaches but none seem to help so here's the form code...
<div tabindex="1" class="dp" onkeypress="if (event && (event.keyCode == 32 || event.keyCode == 13)) RD.selection('http://node.blankplanet.com');" onclick="RD.selection('http://node.blankplanet.com/'); return false;">
<img class="largeIcon float" alt="Node..." src="/images/local.png?id=3B194F1192F038FFF32BF9C4AFF16AA1859EC1D2462FB845BC9813C490A994BB">
<div class="Description float">
<span class="largeTextNoWrap indentNonCollapsible">Node..</span>
</div>
</div>
<div tabindex="2" class="dp" onkeypress="if (event && (event.keyCode == 32 || event.keyCode == 13)) RD.selection('http://node2.blankplanet.com/');" onclick="RD.selection('http://node2.blankplanet.com/'); return false;">
<img class="largeIcon float" alt="Node2..." src="/images/dp.png?id=D29E7325C0DB2C8C6DE5B6632374C52A6975B90CA5FCB6F05F801496191334AF">
<div class="dpDescription float">
<span class="largeTextNoWrap indentNonCollapsible">Node2...</span>
</div>
</div>
<div tabindex="3" class="dp" onkeypress="if (event && (event.keyCode == 32 || event.keyCode == 13)) RD.selection('http://node3.blankplanet.com');" onclick="RD.selection('http://node3.blankplanet.com/'); return false;">
<img class="largeIcon float" alt="Node3..." src="/images/dp.png?id=D29E7325C0DB2C8C6DE5B6632374C52A6975B90CA5FCB6F05F801496191334AF">
<div class="dpDescription float">
<span class="largeTextNoWrap indentNonCollapsible">Node3...</span>
</div>
</div>
A: if you want to autosubmit say button 2 then you would want to use following selector:
$('div[tabindex=2]').click();
try around here:
http://jsfiddle.net/85h3gtnj/1/
actually to make sure you hit no other divs you should add the class selector
$('div.dp[tabindex=2]').click();
as fiddled here:
http://jsfiddle.net/85h3gtnj/3/
A: If the tabindex is the attribute that is set reliably on the page, you can use that to call the click() event:
$.each('div', function() {
if ($(this).attr('tablindex') == 4) {
$(this).click(); //makes it submit
}
});
you can also call the div using the nth-child selector:
$('#container div:nth-child(4)').click();
Info on nth-child can be found here: https://api.jquery.com/nth-child-selector/
Hope that helps!
A: is that what u need? FIddle: https://jsfiddle.net/288er5td/
CODE:
<div tabindex="1" class="dp" >
<img class="largeIcon float" alt="Node..." src="/images/local.png?id=3B194F1192F038FFF32BF9C4AFF16AA1859EC1D2462FB845BC9813C490A994BB" />
<div class="Description float">
<input data-input-field='' type='text' val ='val1' />
<span class="largeTextNoWrap indentNonCollapsible">Node..</span>
</div>
</div>
<div tabindex="2" class="dp">
<img class="largeIcon float" alt="Node2..." src="/images/dp.png?id=D29E7325C0DB2C8C6DE5B6632374C52A6975B90CA5FCB6F05F801496191334AF" />
<div class="dpDescription float">
<input data-input-field='' type='text' val ='val2' />
<span class="largeTextNoWrap indentNonCollapsible">Node2...</span>
</div>
</div>
<div tabindex="3" class="dp">
<img class="largeIcon float" alt="Node3..." src="/images/dp.png?id=D29E7325C0DB2C8C6DE5B6632374C52A6975B90CA5FCB6F05F801496191334AF" />
<div class="dpDescription float">
<input data-input-field='' type='text' val ='val3' />
<span class="largeTextNoWrap indentNonCollapsible">Node3...</span>
</div>
</div>
$(document).ready(function(){
t = function(elem){
var $this = elem;
var $tab = $this.closest('.dp');
var tabindex = $tab.attr('tabindex');
var i_val = $this.val();
alert(tabindex);
alert(i_val);
}
$(document).on('click', '[data-input-field]', function(){
t($(this));
});
$(document).on('keypress', '[data-input-field]', function(event){
if ((event.keyCode == 32) || (event.keyCode == 13)){
t($(this));
}
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29373347",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Remove duplicate lines with 1 command There is any Linux command that deletes duplicates of lines in a file but not the first appearance of the line that is duplicate.
For example, we have a file that has the following lines:
Test Line
Another line
Test
4th line
Test
Test Line
And I want after I run the command, the lines that should remain in the file are:
Test Line
Another Line
Test
4th line
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60605119",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PPT Text x,y,width,height - openxml I tried following this Presentation ML inheritance chain:
Slide <-- SlideLayout <-- SlideMaster <-- default styles in SlideMaster
to obtain x,y,width,height properties of text content in a PPT Slide but I am not sure whether I am getting correct value. Can you please tell if I am doing the right thing ? Can you also please tell me how to uniquely identify this text object in Slide, SlideLayout & SlideMaster ?
-Thank you
A: Refer to the following Answer to determine the Height and Width of Text properties.
For determining if you have the right text, Enter unique text into your slide and use the Open XML Productivity Tool to find it. You can use the tool to search for your unique string in your slide and reflect the code to generate it.
Lastly, to understand the Presentation Slide XML, I recommend reading the free e-book Open XML Explained to give an explanation of how a correct Presentation document is formed to help you better understand where things should be.
A: If you have powerpoint installed from Microsoft office. You can do the following, though this is not programmatic, but can help you to get the job done.
Steps:
*
*Open ppt
*Click on your chart or whatever object you like.
*Right click and select or use shortcut CMD + SHIFT + 1
*Click on 3rd icons select Size Position, and you can see the following
Note:
I'm demoing with Microsoft Powerpoint for Mac Version 2018.
Hope it helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9602384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Vuetify v-chip in v-data-table array I am new to vuetify, and I would like to know how to make a v-chip to a specific value in my table.
example :
<v-data-table
class="page__table"
:headers="headers"
:items="references"
>
<v-chip
v-for="reference in references"
:key="reference.id"
:color="color"
> {{reference.department}}
</v-chip>
and my code (composition api)
const mappedCatalog: ComputedRef<Record<string, any>> = computed(() => catalogStore.fullCatalog.map(reference => {
return {
...reference,
departments: reference.departments
return {
references: ref(mappedCatalog),
can you help me please
A: Check this codesanbox I made: https://codesandbox.io/s/stack-71649799-v-chip-data-table-item-slow-z7p2db?file=/src/components/Example.vue
You can use the item slot of the data table. Some vuetify components comes with special sections for easier customization called slots, in this case the item slot of the data table let you customize individual colums content like this:
<v-data-table
:headers="headers"
:items="desserts"
:items-per-page="5"
class="elevation-1"
>
<template #item.calories="{ item }">
<v-chip dark color="red darken-2">{{ item.calories }}</v-chip>
</template>
<template #item.fat="{ item }">
<v-chip dark color="orange darken-2">{{ item.fat }}</v-chip>
</template>
</v-data-table>
If you're using es-lint you might encounter a warning mention something about the valid-v-slot rule, this is a known false positive that you can read more about in this GitHub issue thread, I personally just turn that es-lint rule off.
For more info about data table slots, check the vuetify documentation page.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71649799",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get different count of key php array to table and $array[1] = array("Name1"=> array("2"=>"1460","3"=>"1868","4"=>"2158","5"=>"2537","6"=>"2915","8"=>"3673"));
$array[2] = array("Prod2"=> array("3"=>"3079","4"=>"3625","5"=>"4172","6"=>"4718","8"=>"5811"));
$cnt = 0;
for ($x = 0; $x < 100; $x++) {
$product = $array[$x]; // dynamic all product`s - $name
foreach ($product as $good =>$massiv) {
$name = key($product); // prod name
$proklkadok = array_keys($massiv); // prod prokladok
foreach ($massiv as $inner_key =>$price) {
echo "<tr><td>". $name. "</td>";
$pr_val = array_keys($massiv);
echo "<td>".$pr_val[0]. "</td>";
echo "<td>".$price."</td></tr>\r\n"; // product price
}
}
}
how to print $pr_val unique in table td cell ?
This code is wrong, bad table prints the output:
Name1 2 1138 or wrong output too ... Name1 2,3,4,5,6,8 1138
Name1 2 1868 or wrong output too ... Name1 2,3,4,5,6,8 1868
Name1 2 2158 or wrong output too ... Name1 2,3,4,5,6,8 2158
Prod2 3 3079 or wrong output too ... Prod2 2,3,4,5,6,8 3079
Prod2 3 3625 or wrong output too ... Prod2 2,3,4,5,6,8 3625
Prod2 3 4718 or wrong output too ... Prod2 2,3,4,5,6,8 4718
Prod2 3 5811 or wrong output too ... Prod2 2,3,4,5,6,8 5811
Correct output must be in HTML TABLE
Name1 2 1138
Name1 3 1868
Name1 4 2158
Name1 5 2537
Name1 6 2915
Name1 8 3673
Prod2 3 3079
Prod2 4 3079
Prod2 5 3625
Prod2 6 4718
Prod2 8 5811
pls help me, I can't count and output different count of array keys in the table output
A: The bug is at
$pr_val = array_keys($massiv);
echo "<td>".$pr_val[0]. "</td>";
array_key($massiv) returns all keys of massiv and $pr_val[0]always returns the first of them (which happens to be the smallest of them).
Try
foreach($product as $good =>$massiv) {
foreach($massiv as $inner_key =>$price) {
echo "<tr><td>". $good. "</td>";
echo "<td>".$inner_key. "</td>";
echo "<td>".$price."</td></tr>\r\n"; // product price
}
}
That should output exactly what you desire.
A: This code will output what you desire as the correct output in an HTML table
$array[1]=array("Name1"=> array("2"=>"1460","3"=>"1868","4"=>"2158","5"=>"2537","6"=>"2915","8"=>"3673"));
$array[2] =array("Prod2"=> array("3"=>"3079","4"=>"3625","5"=>"4172","6"=>"4718","8"=>"5811"));
echo "<table>" . PHP_EOL;
foreach($array as $product) {
foreach($product as $name =>$massiv) {
foreach($massiv as $inner_key => $price) {
echo "<tr><td>". $name. "</td>";
echo "<td>".$inner_key. "</td>";
echo "<td>".$price."</td></tr>" . PHP_EOL; // product price
}
}
}
echo "</table>" . PHP_EOL;
A: $array = array();
$array[0] = array("Name1"=> array("2"=>"1460","3"=>"1868","4"=>"2158","5"=>"2537","6"=>"2915","8"=>"3673"));
$array[1] = array("Prod2"=> array("3"=>"3079","4"=>"3625","5"=>"4172","6"=>"4718","8"=>"5811"));
echo '<table rules="all" border="1">';
foreach($array as $v) {
foreach($v as $name => $ar) {
foreach($ar as $v1 => $v2) {
echo sprintf('<tr><td>%s</td><td>%s</td><td>%s</td></tr>'."\r\n",
$name, $v1, $v2);
}
}
}
echo '</table>';
by Prizma
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35095372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: BootStrap Modal: Multiple modal open, and when last modal cancelled it hangs the page Sorry I don't get this but I have 2 modals
<!-- Upload Document Modal 1 -->
<div class="modal fade" id="uploadFileModal" tabindex="-1" role="dialog" aria-labelledby="uploadFileModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="uploadFileModalLabel">@lang('pagetexts.client_view_models.upload_file')</h5>
<button type="button" id="closeUploadModal" class="close" data-target="#uploadFileModal" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-12">
<form action="/initial-document-upload" class="dropzone" id="dropzoneUpload" method="POST" enctype="multipart/form-data">
@csrf
<input type="hidden" value="{{$client_data->id}}" id="clientid" name="clientid"/>
</form>
<!-- <div class="col-12 text-center d-flex upload-holder" data-toggle="modal" data-target="#uploadFileModal2" data-dismiss="modal">
<div class="align-self-center text-center col-12 d-block">@lang('pagetexts.client_view_models.drag_and_drop_here') <a href="JavaScript:Void(0);">browse</a></div>
</div> -->
</div>
</div>
<div class="row">
<div class="col-12"> <em style="word-wrap: break-word;">@lang('pagetexts.client_view_models.file_accept_are')</em> </div>
</div>
</div>
<div class="modal-footer">
<button type="button" id="can-upl-btn" data-target="#uploadFileModal1" data-dismiss="modal" class="btn btn-secondary">@lang('pagetexts.client_view_models.cancel')</button>
</div>
</div>
</div>
</div>
Modal 2
<!-- Update Document Modal 2 -->
<div class="modal fade" id="uploadFileModal2" tabindex="-1" role="dialog" aria-labelledby="uploadFileModal2Label" aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="uploadFileModal2Label">@lang('pagetexts.client_view_models.upload_file')</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-12">
<div class="form-group">
<label for="">@lang('pagetexts.client_view_models.document_title')</label>
<input type="text" class="form-control" id="Titlex" value="">
</div>
<div class="form-group">
<label for="">@lang('pagetexts.client_view_models.notes')</label>
<textarea class="form-control" id="Notesx" rows="3"></textarea>
</div>
<a href="" class="btn btn-secondary" data-toggle="modal" data-target="#tagModal">@lang('pagetexts.client_view_models.apply_tags')</a>
<div class="custom-control custom-checkbox mt-3">
<input type="checkbox" class="custom-control-input" id="customCheck1x">
<label class="custom-control-label" for="customCheck1x">@lang('pagetexts.client_view_models.share_with_client')</label>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="hidden" value="" id=documentid" name="documentid"/>
<button type="button" id="can-file-upd" data-target="#uploadFileModal2" data-dismiss="modal" class="btn btn-secondary" >@lang('pagetexts.client_view_models.cancel')</button>
<button type="button" class="btn btn-primary">@lang('pagetexts.client_view_models.save_changes')</button>
</div>
</div>
</div>
</div>
The action is when the first modal successfully uploads a file it should open modal 2 , and then should submit the form to update the details for the upload in the 1st one. This is how I trigger the transition
this.on('success', function(event, response) {
$('#uploadFileModal').modal('hide');
$('#uploadFileModal2').modal('show');
})
When I submit the modal 2 to the form it successfully updates the data, HOWEVER, when I cancel MODAL 2, nothing in the page is usable, I can't click anywhere, any idea as to why ?
A: Multiple open modals are not supported by Bootstrap. You have to remember that .modal() is asynchronous, so the next .modal() is going to run before the previous completes. So, you probably have an overlay covering your page, even though the styles it's given prevent you from seeing it.
This might work:
this.on('success', function(event, response) {
$('#uploadFileModal')
.on('hidden.bs.modal', function(){
$('#uploadFileModal2').modal('show');
})
.modal('hide');
});
This will delay the second modal from being triggered until the first modal has completed it's hide transition.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62057703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: WARN Test results in Robot Framework I have multiple test cases that need to be tested. With every release, I get some new test cases as well as some old ones.
My problem is for old test cases which are failed I have already created a problem ticket in JIRA and in the next release this ticket number is added in [Documentation] Field of the .robot
Now what I want is next time on a new release if the bug is already raised in Jira meaning the documentation section of the robot will contain the ticket number, If the test fails I will label it as WARN in Yellow instead of marking it as Failure.
I have searched a lot and found this thread but according to it I can't do it- Github Issue is there any other way?
A: You will need to process the Documentation of the test to see if it has a JIRA issue number, if so, then add a Tag (for example TagName) to it. When launching tests with robotframework version 4.0, you call them by passing the option --skiponfailure TagName. You will have those tests marked as SKIPPED.
The parsing of Documentation would be needed to parse before running the actual tests (in a helper test run).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64460160",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Milliseconds to HH:MM:SS time format I'm trying to add the timestamp of a video frame to its own frame name like "frame2 00:00:01:05", using CAP_PROP_POS_MSEC I'm getting the current position of the video file in milliseconds, what I want is to change those milliseconds to the time format "00:00:00:00:".
My code currently assigns the name like: "frame2 1.05" but ideally I would have the name like: "frame2 00:00:01:05".
Is there a library that can help me achieve this milliseconds to HH:MM:SS conversion?
import cv2
vidcap = cv2.VideoCapture('video.mp4')
success,frame = vidcap.read()
cont = 0
while success:
frame_timestamp = (vidcap.get(cv2.CAP_PROP_POS_MSEC))/(1000)
cv2.imwrite(f'frame{cont} '+str((format(frame_timestamp,'.2f')))+'.jpg',frame)
success,frame = vidcap.read()
cont+=1
Thanks!
A: Just use divmod. It does a division and modulo at the same time. It's more convenient than doing that separately.
seconds = 1.05 # or whatever
(hours, seconds) = divmod(seconds, 3600)
(minutes, seconds) = divmod(seconds, 60)
formatted = f"{hours:02.0f}:{minutes:02.0f}:{seconds:05.2f}"
# >>> formatted
# '00:00:01.05'
And if you need the fraction of seconds to be separated by :, which nobody will understand, you can use (seconds, fraction) = divmod(seconds, 1) and multiply fraction * 100 to get hundredth of a second.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72975483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: grouping foreign objects (javascript merge) I'm writing a small userscript to recieve an object from a xhr request and send parts of it to another website. The recieved json looks like this
{"result": [
{"id":"1234","title":"Gartenzwerg","description":"Strom unter Kunst","lat":153.558356,"lng":50.205637,"city":"Citü","state":"XY","day":"1970-01-01","order":0,"imageUrl":"https://cool.page","nextUpgrade":false,"upgraded":false,"status":"WITHDRAWN"},
{"id":"56789","title":"Weizenähre","description":"Strom unter Kunst","lat":153.590972,"lng":50.235216,"city":"Citü","state":"XY","day":"1971-01-01","order":1,"imageUrl":"https://cooler.page","nextUpgrade":true,"upgraded":true,"status":"NOMINATED"},
{...}],
"message":null,
"code":"OK",
"errorsWithIcon":null,
"fieldErrors":null,
"errorDetails":null,
"version":"4.0.10",
"captcha":false}
I use Add a "hook" to all AJAX requests on a page to get the informations and then send each result-part by it's own to my page with a fetch-function
var data = JSON.parse(this.responseText).result;
for (let i=0; i<Object.keys(data).length; i++) {
sendDataToPage(data[Object.keys(data)[i]]);
await sleep(500);
}
Now it's very ineffective to send each by it's own, so i'd like to groupe f.e. 10 elements before I send them. With Object.assign I only get the last element. Do I have to use another function to merge or how do I use it the right way?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68909666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Remove line number option from grep I use an alias for grep, that adds line numbers to the output:
alias grep="grep -n -I --color"
For a certain command I'd like to remove the -n from the grep command. I could not find a "Do not add line numbers"-flag. Is something like this available or do I have to add an extra alias without linenumbers?
A: Just use a backslash, as it will revert to the default grep command and not your alias:
\grep -I --color
A: You could use command to remove all arguments.
command grep -I --color
A: I realize this is an older question, but I've been running up against the same problem. This solution works, but isn't the most elegant:
# Not part of your original question, but I learned that if an alias
# contains a trailing space, it will use alias expansion. For the case
# of 'xargs', it allows you to use the below grep aliases, such as the
# 'chgrep' alias defined below:
# grep -l 'something' file1 file2 ... | xargs chgrep 'something else'
alias xargs='xargs '
export GREP_OPT='-n'
# Note the $(...) INSIDE the 'single quotes'
alias grep_='\grep --color=auto -I $(echo "$GREP_OPT")'
# Due to alias expansion, the below aliases benefit from the 'GREP_OPT' value:
alias cgrep='grep_ -r --include=\*.{c,cc,cpp}'
alias hgrep='grep_ -r --include=\*.{h,hh,hpp}'
alias chgrep=cgrep_ --include=\*.{h,hh,hpp}' # Not sure if there's a way to combine cgrep+hgrep
...
alias pygrep='grep_ -r --include=\*.py'
In the situations where you want a non-numbered output, unset GREP_OPT (or remove -n from it, like if you're using it to include other flags).
I've used grep_ instead of grep in the above example just to show that aliases will happily chain/use alias expansion as needed all the way back to the original command. Feel free to name them grep instead. You'll note that the original grep_ uses the command \grep so the alias expansion stops at that point.
I'm totally open to suggestions if there is a better way of doing this (since setting/unsetting the GREP_OPT isn't always the most elegant).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42138844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: When are ready the new feature "cards" in the API? Youtube has a new feature called "Cards", but i can't find information in the API about of this, i need to know when are ready to be able to be used like programmer, thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29501272",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to Backup a Meteor Mongo Database? To create a backup of my mongo database, I am trying mongodump from my meteor console. The command successfully completes, but creates an empty folder under the dump folder. I use the command
mongodump -h 127.0.0.1 --port 3001 -d meteor
So basically I am trying to backup my database for reactionecommerce. My question is how to backup a meteor mongodb that is running locally? Thanks for any guidance of help.
A: The issue was with the mongo version 2.6.10. I installed the latest 3.4.4 in my Ubuntu 64 machine following the instructions https://docs.mongodb.com/master/tutorial/install-mongodb-on-ubuntu/ Now I am able to dump the data without any problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43539440",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Overwrite postgresql onupdate with sqlalchemy Original problem
I'm using sqlalchemy in our project. I registered few event listeners for my model like so.
@event.listens_for(Post, 'after_update')
@event.listens_for(Post, 'after_insert')
Somewhere else in the code I update the view_counter property of my model.
post.view_counter += 1
DBSession.flush()
Now, since view_counter is not something I regard as content update, I want to supress firing of after_update event in sqlalchemy for this specific update. Is there a way to do it via ORM or is the only way to just do raw SQL update bypassing ORM entirely?
EDIT
After some poking around I realized there is another problem, the property is set by Postgresql itself
date_last_updated = Column(SA_DateTime, default=DateTime.now, onupdate=DateTime.now, nullable=False, index=True)
Problem
So the question is, how to update a sqlalchemy model without triggering Postgresql update.
A: If you're able to make changes to the decorated function, it should be possible to use the passed arguments to determine which fields were modified, albeit through a little bit of a workaround. I'm afraid I haven't been able to test this yet, but I hope it helps!
@event.listens_for(Post, 'after_update', raw=True)
@event.listens_for(Post, 'after_insert', raw=True)
def myfunc(mapper, connection, target):
# Values have been modified
if target.session.is_modified(target, include_collections=False):
# view_counter is the only modified value, the hook can be aborted
if set(target.dict.keys()) - target.unmodified == {'view_counter'}:
return
<...the rest of the function...>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57222721",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Test rig exited abnormally with code 134 with OCMock verify on iOS 4 I'm trying to add OCMock to my iOS 4 project. To test it out, I have a class Person with one method, -hello. When I run this test:
- (void) testMock {
id mock = [OCMockObject mockForClass:[Person class]];
[[mock expect] hello];
[mock hello];
[mock verify];
}
Everything is fine, and the build succeeds. If I take away the hello call, like this:
- (void) testMock {
id mock = [OCMockObject mockForClass:[Person class]];
[[mock expect] hello];
[mock verify];
}
I'd expect to get an error message telling me that my expected method wasn't called on the mock. Instead I get a cryptic message about the test rig crashing:
/Developer/Tools/RunPlatformUnitTests.include:451:0 Test rig '/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.0.sdk/Developer/usr/bin/otest' exited abnormally with code 134 (it may have crashed).
Is this crash normal when an expected method isn't called? Do I have a bad configuration?
A: You don't have a bad configuration, it's a bug that Apple introduced in the simulator SDK when they released iOS4. Basically, if code invoked using an NSInvocation object throws an exception, then that exception is uncatchable. I wrote about the issue when it first appeared here:
http://pivotallabs.com/users/adam/blog/articles/1302-objective-c-exceptions-thrown-inside-methods-invoked-via-nsinvocation-are-uncatchable
Unfortunately, this bug affects OCMock and Apple hasn't show much interest in fixing it. Many people have filed bug reports, but to no avail.
I realize this is little comfort, but you will get slightly better error messages when using Cedar for testing (I believe the same is true for GTM).
A: I'd say it's a bug. Verify should report a useable result, even if it fails.
A: I have found that this bug is still around with Xcode 4/SDK 4.3 in April of 2011. For example, Test A passes, Test B crashes the test rig.
Test A:
- (void)testAcceptsAndVerifiesExpectedMethods
{
id mock = [OCMockObject mockForClass:[NSString class]];
[[mock expect] lowercaseString];
[mock lowercaseString];
[mock verify];
}
Test B:
- (void)testAcceptsAndVerifiesExpectedMethods
{
id mock = [OCMockObject mockForClass:[NSString class]];
[[mock expect] lowercaseString];
//[mock lowercaseString];
[mock verify];
}
A: A workaround I've found is to wrap the [mockObject expect] and [mockObject verify] calls with XCTAssertNoThrow, e.g.:
XCTAssertNoThrow([[mockTaskVC expect] showAlertWithTitle:containsString(@"Error") message:OCMOCK_ANY completion:OCMOCK_ANY], @"threw up exception");
This will catch the exception and fail the text rather than crashing.
Credit to author here: http://www.mulle-kybernetik.com/forum/viewtopic.php?f=4&t=315&p=710&hilit=unexpected+method+was+not+invoked+exception#p710
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3400767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Limiting resultset from Magento SOAP query How can you specify a max result set for Magento SOAP queries?
I am querying Magento via SOAP API for a list of orders matching a given status. We have some remote hosts who are taking too long to return the list so I'd like to limit the result set however I don't see a parameter for this.
$orderListRaw = $proxy -> call ( $sessionId, 'sales_order.list', array ( array ( 'status' => array ( 'in' => $orderstatusarray ) ) ) );
I was able to see that we do get data back (6 minutes later) and have been able to deal with timeouts, etc. but would prefer to just force a max result set.
A: It doesn't seem like it can be done using limit, (plus you would have to do some complex pagination logic to get all records, because you would need know the total number of records and the api does not have a method for that) See api call list @ http://www.magentocommerce.com/api/soap/sales/salesOrder/sales_order.list.html
But what you could do as a work around is use complex filters, to limit the result set base on creation date. (adjust to ever hour, day or week base on order volume).
Also, since you are using status type (assuming that you are excluding more that just cancel order), you may want to think about getting all order and keep track of the order_id/status locally (only process the ones with the above status) and the remainder that wasn't proceed would be a list of order id that may need your attention later on
Pseudo Code Example
$params = array(array(
'filter' => array(
array(
'key' => 'status',
'value' => array(
'key' => 'in',
'value' => $orderstatusarray,
),
),
),
'complex_filter' => array(
array(
'key' => 'created_at',
'value' => array(
'key' => 'gteq',
'value' => '2012-11-25 12:00:00'
),
),
array(
'key' => 'created_at',
'value' => array(
'key' => 'lteq',
'value' => '2012-11-26 11:59:59'
),
),
)
));
$orderListRaw = $proxy -> call ( $sessionId, 'sales_order.list', $params);
Read more about filtering @ http://www.magentocommerce.com/knowledge-base/entry/magento-for-dev-part-8-varien-data-collections
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13088231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Numpy hybrid type Matrix astype I'm trying to cast a numpy matrix that I have already defined:
matrix = numpy.array([['name','23','45','1'],
['name2','223','43','5'],
['name3','12','33','2']])
resulting in this:
array([['name1', '23', '45', '1'],
['name2', '223', '43', '5'],
['name3', '12', '33', '2']],
dtype='|S5')
I would like to name and cast each column of my matrix to the following types:
dt = numpy.dtype({'names':['name','x','y','n'],'formats': ['S10', 'S10', 'S10', 'S10']})
For now, I will consider matrix all strings because it doesn't work, but what was expected a format like this 'formats': ['S10', 'f3', 'f3', 'i']
and do something like this:
matrix.astype(dtype=dt,casting='safe')
Result:
array([[('name', 'name', 'name', 'name'), ('23', '23', '23', '23'),
('45', '45', '45', '45'), ('1', '1', '1', '1')],
[('name2', 'name2', 'name2', 'name2'), ('223', '223', '223', '223'),
('43', '43', '43', '43'), ('5', '5', '5', '5')],
[('name3', 'name3', 'name3', 'name3'), ('12', '12', '12', '12'),
('33', '33', '33', '33'), ('2', '2', '2', '2')]],
dtype=[('name', 'S10'), ('x', 'S10'), ('y', 'S10'), ('n', 'S10')])
What am I missing? How can I define types for each matrix columns using numpy module?
A: Creating/filling a structured array is a little tricky. There are various ways, but I think the simplest to remember is to use a list of tuples:
In [11]: np.array([tuple(row) for row in matrix], dtype=dt)
Out[11]:
array([('name', '23', '45', '1'),
('name2', '223', '43', '5'),
('name3', '12', '33', '2')],
dtype=[('name', 'S10'), ('x', 'S10'), ('y', 'S10'), ('n', 'S10')])
The result is 1d array, with the dtype fields replacing the columns of the original 2d array. Each element of the new array has the same type - as specified by dt.
Or you can create an empty array of the desired dtype, and fill it, row by row or field by field:
In [14]: arr = np.zeros((3,),dt)
In [16]: arr[0]=tuple(matrix[0,:]) # tuple of row
In [17]: arr['name']=matrix[:,0] # field
In [18]: arr
Out[18]:
array([('name', '23', '45', '1'),
('name2', '', '', ''),
('name3', '', '', '')],
dtype=[('name', 'S10'), ('x', 'S10'), ('y', 'S10'), ('n', 'S10')])
With a compatible dt1, view would also work
dt1 = numpy.dtype({'names':['name','x','y','n'],'formats': ['S5', 'S5', 'S5', 'S5']})
matrix.view(dt1)
This doesn't change the data; it just interprets the bytes differently.
converting the strings to numbers is easy with the list of tuples
In [40]: dt2 = numpy.dtype({'names':['name','x','y','n'],'formats': ['S5', 'f', 'f', 'i']})
In [41]: np.array([tuple(row) for row in matrix], dtype=dt2)Out[41]:
array([('name', 23.0, 45.0, 1),
('name2', 223.0, 43.0, 5),
('name3', 12.0, 33.0, 2)],
dtype=[('name', 'S5'), ('x', '<f4'), ('y', '<f4'), ('n', '<i4')])
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30141778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to find the second lowest value in a tensorflow array I am writing a clustering algorithm and for part of it I calculate a euclidean distance matrix for each cluster of points. (FYI all of this is in Tensorflow). each cluster is a list of 8 dimensional vectors, which I then turn into one M*8 matrix. For each point in each cluster, I want to find the distance between it and its closest neighbor. I believe the most efficient way to do this would be to do compute pairwise distance between points for each cluster, and then find the second smallest value in each row of the resulting M*M matrix (because the smallest value in each row will always be 0, the distance between a given point and itself).
Here is the code I use to create the euclidean distance matrix for each cluster:
partitionedData = tf.dynamic_partition(inputs, pred, num_classes)
for partition in partitionedData:
N = tf.to_int32(partition.get_shape()[0])
qexpand = tf.expand_dims(partition,1)
qTexpand = tf.expand_dims(partition,0)
qtile = tf.tile(qexpand,[1,N,1])
qTtile = tf.tile(qTexpand,[N,1,1])
deltaQ = qtile - qTtile
deltaQ2 = deltaQ*deltaQ
d2Q = tf.reduce_sum(deltaQ2,2)
The resulting matrix might look something like this (Note: this is a matrix of squares of distances):
[[ 0. 8. 2. 18.]
[ 8. 0. 10. 2.]
[ 2. 10. 0. 20.]
[ 18. 2. 20. 0.]]
for an input matrix of:
[[2,3],[4,5],[1,4],[5,6]]
What I would like to get in the end is the second smallest value in each row, in this case 2,2,2, and 2. Additionally, if there is a better way to find the distance to the nearest neighbor in tensorflow for every point in a cluster that is computationally efficient, that would be extremely helpful.
A: To find k-th element in TF you need tf.nn.top_k. If you need smallest you search not in X, but in -X.
In your case you do not even need it. If your matrix is a distance, the diagonal is always 0 and this screws things up for you. So just create change the diagonal of your matrix with tf.matrix_set_diag, where your diagonal is a vector of size of your X, where each value is tf.reduce_max.
Writing a code for this is trivial.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45126061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Agent in JADE behaviour not working I'm trying to create a game where JADE Agents are the 'enemies' and they chase a player around a maze.
So far I have:
MazeView.java (uses Swing to paint various things on the screen, and lets the user interact through button presses)
Enemy.java (a JADE agent that will have behaviours like search, pursue, etc.)
And a few other classes doing things like generating the actual maze data structure etc.
My problem is that, while I can instantiate an Agent and paint it on the screen, for some reason I can't add any behaviours. For example, if I wanted something like this (in Enemy.java):
protected void setup() {
// Add a TickerBehaviour that does things every 5 seconds
addBehaviour(new TickerBehaviour(this, 5000) {
protected void onTick() {
// This doesn't seem to be happening?
System.out.println("5 second tick... Start new patrol/do something?");
myAgent.addBehaviour(new DoThings());
}
}); // end of addBehaviour
System.out.println("End of setup()...");
} // end of setup
When I run the code, no errors are thrown, and I can see "End of setup()..." displayed in console. So for some reason it's just not going into the addBehaviour() method at all. Even if the DoThings() behaviour didn't work (right now it just prints a message), it should at least display the "5 second tick" message before throwing an error. What is going wrong here?
I think it could be something to do with the fact that currently there is no concept of 'time' in my maze. The user presses a key, and THEN processing happens. So having an agent that does things every 5 seconds might not work when there is no real way to facilitate that in the maze? But I'm still confused as to why it just skips addBehaviour() and I don't get an error.
A possible solution might be to re-implement my maze as a constant loop that waits for input. Would that allow a concept of 'time'? Basically I'm not sure how to link the two together. I am a complete beginner with JADE.
Any ideas would be appreciated. Thanks!
A: I've never used Jade, but my first thought was that you are adding behaviors and then assuming that Jade will decide to run them at some point. When you say that you never see your behaviors activate, it strengthened that hypothesis.
I looked at the source and sure enough, addBehaviour() and removeBehaviour() simply add and remove from a collection called myScheduler. Looking at the usages, I found a private method called activateAllBehaviours() that looked like it ran the Behaviours. That method is called from the public doWake() on the Agent class.
I would guess that you simply have to call doWake() on your Agent. This is not very apparent from the JavaDoc or the examples. The examples assume that you use the jade.Boot class and simply pass the class name of your agent to that Boot class. This results in the Agent getting added to a container that manages the "waking" and running of your Agents. Since you are running Swing for your GUI, I think that you will have to run your Agents manually, rather than the way that the examples show.
I got more curious, so I wrote my own code to create and run the Jade container. This worked for me:
Properties containerProps = new jade.util.leap.Properties();
containerProps.setProperty(Profile.AGENTS, "annoyer:myTest.MyAgent");
Profile containerProfile = new ProfileImpl(containerProps);
Runtime.instance().setCloseVM(false);
Runtime.instance().createMainContainer(containerProfile);
This automatically creates my agent of type myTest.MyAgent and starts running it. I implemented it similar to your code snippet, and I saw messages every 5 seconds.
I think you'll want to use setCloseVM(false) since your UI can handle closing down the JVM, not the Jade container.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33173268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP Laravel are DB function results cached? Noob question. I'm working on a project which involves interacting with some legacy software and the database is not compatible with regular Laravel Relationships.
If I'm defining things in a constructor like this:
public function __construct(array $attributes = array())
{
parent::__construct($attributes);
$this->vatpercentage = $this->customer()->vatpercentage;
$this->vatcode = $this->customer()->vatcode;
$this->partrevision = $this->part()->revision;
$this->unitprice = $this->part()->unitprice;
}
public function part(){
return Part::findOrFail($this->partnum);
}
public function customer(){
$traderid = Order::where('id', $this->orderid)->value('traderid');
return Customer::where('id', $traderid)->where('tradertype', 'C')->first();
}
I need to reference customer(), part() and other similar functions many times in the constructor. Is the DB getting queried every time I reference $this->customer(), etc or is the result cached the first time I reference it and then used for all the other times following? Basically am I doing a lot of unnecessary DB calls by coding in this way rather than setting $this->customer = $this->customer() and grabbing the values like $this->customer->example?
A: No database query or method call is going to be cached automatically in your application, nor should it. Laravel and PHP aren't going to know how you want to use queries or methods.
Everytime you call customer(), you're building up and executing a new query. You could easily cache the result in a property if that's what you want, but you'd have watch the value of the $orderid property:
protected $customerCache;
public function customer()
{
if ($customerCache) return $customerCache;
$traderid = Order::where('id', $this->orderid)->value('traderid');
return $customerCache = Customer::where('id', $traderid)->where('tradertype', 'C')->first();
}
You're also performing too much in your constructor. I would highly recommend not performing queries in any constructors, constructors should be used to pass dependencies. The way you have it designed would make it very hard to unit test.
A: In Laravel 4.* there was a remember() method handling the cache in queries. It was removed from 5.1 with a valid reason that it's not the responsibility of Eloquent neither the query Builder to handle cache. A very very simplified version of a decorator class that could handle the caching of your queries:
final class CacheableQueryDecorator
{
private $remember = 60; //time in minutes, switch to load from config or add a setter
private $query = null;
public function __construct(Builder $builder)
{
$this->query = $builder;
}
private function getCacheKey(string $prefix = ''):string
{
return md5($prefix . $this->query->toSql() . implode(',', $this->query->getBindings()));
}
public function __call($name, $arguments)
{
$cache = Cache::get($this->getCacheKey($name), null);
if ($cache) {
return $cache;
}
$res = call_user_func_array([$this->query, $name], $arguments);
Cache::put($this->getCacheKey($name), $res, $this->remember);
return $res;
}
}
Using it:
$results = (new CacheableQueryDecorator($query))->get()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53834062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: QT4 get base char without diacritics I am trying to create an index from a list of QString, getting the first char for each word in the list. I would like to remove all diacritics from this first char, fe: á -> a, ü -> u, 木 -> 木. I mean, the index for abeja, ala, árbol should be the same: 'a'.
EDIT:
I have found the QString normalized ( NormalizationForm mode ) const method:
QString s = "á";
QString sWithoutDiacritic = s.normalized(QString::NormalizationForm_D).at(0);
Maybe this will do the trick, I'll try later.
A: Collation (sorting order according to natural language) might be what you're looking for
The ICU Library provides such:
http://userguide.icu-project.org/collation/api
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12456061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to add class to block under position: sticky I have a block with position: sticky and a block under it. Is there any way to track the moment when the sticky block sticks to the top and add a class to the bottom block?
I think I should use $(window).scroll() but don't know how.
A: There is no "official" way of telling an element is being stuck with sticky positioning as I know of right now. But you could use a IntersectionObserver.
It works by observing changes in an elements position related for example to a viewport, in the case of this code sample it checks for at least a 1px difference (threshold: 1).
const el = document.querySelector(".stickyElement")
const observer = new IntersectionObserver(
([e]) => document.querySelector(".elementThatShouldUpdate").classList.toggle("desired-class", e.intersectionRatio < 1),
{ threshold: [1] }
);
observer.observe(el);
You should also update your CSS for the sticky element to account for the 1px difference:
top: -1px;
And also account for this extra offset, so you should add either a border or a padding to this element:
padding-top: 1px;
Let me know if this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70928700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ChoiceBox with custom Item in a TableView I have a
private TableView<Indicators> tableviewIndicators;
with column
private TableColumn<Indicators, WindowsItem> tablecolumnFrame;
public static class WindowsItem {
CustomInternalWindow chrt;
private WindowsItem(CustomInternalWindow _chrt) {
chrt = _chrt;
}
public String toString() {
return chrt.getTitle();
}
}
private Indicators(String tl, WindowsItem chrt, String pne, Boolean sel) {
this.tool_col = new SimpleStringProperty(tl);
if (chrt == null) {
this.chart_col = new SimpleStringProperty("");
} else {
this.chart_col = new SimpleStringProperty(chrt.toString());
}
this.pane_col = new SimpleStringProperty(pne);
this.on_col = new SimpleBooleanProperty(sel);
this.chrt = chrt;
}
public String getTool() {
return tool_col.get();
}
public void setTool(String tl) {
tool_col.set(tl);
}
public WindowsItem getChart() {
return chrt;
}
public void setChart(WindowsItem _chrt) {
System.out.println("Indicators::setChart "+chrt.toString());
chrt = _chrt;
}
public String getPane() {
return pane_col.get();
}
public void setPane(String pne) {
pane_col.set(pne);
}
public Boolean getOn() {
return on_col.get();
}
public void setOn(boolean sel) {
on_col.set(sel);
}
public SimpleBooleanProperty onProperty() {
return on_col;
}
public SimpleStringProperty toolProperty() {
return tool_col;
}
public SimpleStringProperty chartProperty() {
return chart_col;
}
public SimpleStringProperty paneProperty() {
return pane_col;
}
}
tablecolumnFrame.setCellValueFactory(new PropertyValueFactory<Indicators, WindowsItem>("chart"));
How can I add a combobox or choicebox in tablecolumnFrame?
The following code
tablecolumnFrame.setCellFactory(new Callback<TableColumn<Indicators, WindowsItem>, TableCell<Indicators, WindowsItem>>() {
@Override
public TableCell<Indicators, WindowsItem> call(TableColumn<Indicators, WindowsItem> param) {
TableCell<Indicators, WindowsItem> cell = new TableCell<Indicators, WindowsItem>() {
@Override
public void updateItem(WindowsItem item, boolean empty) {
super.updateItem(item, empty);
if(empty){
return;
}
if (item != null) {
//final ChoiceBox<WindowsItem> choice = new ChoiceBox<>();
final ComboBox<WindowsItem> choice = new ComboBox<>();
int itemsInTab = chartsInTab.getChildren().size();// dimensione del contenuto del tab, compreso il pane
CustomInternalWindow winItem;
//
for (int i = 0; i < itemsInTab; i++) {
if (chartsInTab.getChildren().get(i) instanceof CustomInternalWindow) {
winItem = (CustomInternalWindow) chartsInTab.getChildren().get(i);
choice.getItems().add(new WindowsItem(winItem));
//choice.getItems().add(winItem.toString());
System.out.println("winItem.toString() "+winItem.toString());
}
}
return this error
SEVERE: javafx.scene.control.Control loadSkinClass Failed to load skin 'StringProperty [bean: TableRow[id=null, styleClass=cell indexed-cell table-row-cell], name: skinClassName, value: com.sun.javafx.scene.control.skin.TableRowSkin]' for control TableRow[id=null, styleClass=cell indexed-cell table-row-cell]
A: Why do you need special property? You can create ListView with ComboBox quite easily:
ObservableList<WindowsItem> windowsItems = FXCollections.observableArrayList();
ObservableList<WindowsItem> data = FXCollections.observableArrayList();
final ListView<WindowsItem> listView = new ListView<>(data);
listView.setEditable(true);
listView.setItems(data);
listView.setCellFactory(ComboBoxListCell.forListView(windowsItems));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21635694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to determine if variable is undefined in another question on SO, I was determining how to toggle off a function, and the working solution is this:
I place var disabledFlag = true; in the head section of my page and before calling shell.js, then in shell.js I have:
/*******************************/
/* TOGGLE BUTTON
/*******************************/
var toggleBlock = function() {
console.log(disabledFlag);
if(!disabledFlag){
var windowsize = $(window).width(),
isDesktop = windowsize > 765;
$("#quicksearch").toggleClass("collapse in", isDesktop);
$("#quicksearch").toggleClass("collapse out", !isDesktop);
$("#sidebar").toggleClass("collapse in", isDesktop);
$("#sidebar").toggleClass("collapse out", !isDesktop);
}
else {
$("#quicksearch").addClass("collapse out");
$("#sidebar").addClass("collapse out");
}
}
$(document).ready(toggleBlock);
$(window).on("resize.showContent", toggleBlock);
toggleBlock();
shell.js is an common file that is shared with other sites and may not have the variable defined. how do I check if the variable is defined, and if not assign it to false and then execute the code above?
A: try
if (typeof disabledFlag === 'undefined')
disabledFlag = false;
A: There are easier ways to do it than using ternaries or if else statements.
As far as your specific function goes, you could do something like this:
var toggleBlock = function() {
var disabledFlag = disabledFlag||false;
if(!disabledFlag){
//etc.
undefined is falsy, so it works with the logical || operator. That || operator makes the new var disabledFlag be set to disabledFlag (if it exists), and if not, it will set the var to false
This same concept is used in many different contexts. For example:
Situation 1 -
var obj = {hello: 'world'};
function fn(object) {
var object = object || {foo: 'bar'};
return object;
}
fn(obj) // ==> {hello: 'world'}
Situation 2 -
function fn(object) {
var object = object || {foo: 'bar'};
return object;
}
fn(objectThatDoesntExist); // ==> {foo: 'bar'}
In JavaScript libraries and module-pattern projects, this concept is used quite frequently in many different ways.
A: You don't need typeof
if (window.disabledFlag === undefined) window.disabledFlag = false;
A: you can check if a variable is undefined with the typeof keyword, like this:
if(typeof neverDeclared == "undefined") //no errors
if(neverDeclared == null) //throws ReferenceError: neverDeclared is not defined
take a look here for more info on typeof
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21805507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Clang undefined behavior checker link error Upon trying to compile a C++ source file with clang 3.5 with the undefined behavior checker
clang++-3.5 -std=c++11 -fsanitize=undefined main.cpp
I am getting the following error upon linking:
Undefined symbols for architecture x86_64:
"typeinfo for __cxxabiv1::__class_type_info", referenced from:
__ubsan::checkDynamicType(void*, void*, unsigned long) in libclang_rt.ubsan_osx.a(ubsan_type_hash.o)
isDerivedFromAtOffset(__cxxabiv1::__class_type_info const*, __cxxabiv1::__class_type_info const*, long) in libclang_rt.ubsan_osx.a(ubsan_type_hash.o)
findBaseAtOffset(__cxxabiv1::__class_type_info const*, long) in libclang_rt.ubsan_osx.a(ubsan_type_hash.o)
"typeinfo for __cxxabiv1::__si_class_type_info", referenced from:
isDerivedFromAtOffset(__cxxabiv1::__class_type_info const*, __cxxabiv1::__class_type_info const*, long) in libclang_rt.ubsan_osx.a(ubsan_type_hash.o)
findBaseAtOffset(__cxxabiv1::__class_type_info const*, long) in libclang_rt.ubsan_osx.a(ubsan_type_hash.o)
"typeinfo for __cxxabiv1::__vmi_class_type_info", referenced from:
isDerivedFromAtOffset(__cxxabiv1::__class_type_info const*, __cxxabiv1::__class_type_info const*, long) in libclang_rt.ubsan_osx.a(ubsan_type_hash.o)
findBaseAtOffset(__cxxabiv1::__class_type_info const*, long) in libclang_rt.ubsan_osx.a(ubsan_type_hash.o)
ld: symbol(s) not found for architecture x86_64
Do I need to link with an additional library?
A: It seems you are missing libc++abi. Try adding
-lc++abi
to your link command.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26774999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to check open ports using powershell? I would like to write a script to check radom IP or hostname to see if ports are open. Here is what I have so far. The scripts name is checkports.
foreach ($xhost in $computername){
Write-Host $xhost
foreach ($port in $ports) {
$Socket = New-Object System.Net.Sockets.TCPClient
$Connection = $Socket.BeginConnect($xhost,$port,$null,$null)
$Connection.AsyncWaitHandle.WaitOne(5000,$false) | out-null
if ($Connection -eq $true)
{ write-host = "$xhost port $port is open" }
else
{ write-host = "port $port is closed" }
$Socket.EndConnect($Connection)
$Socket.Close()
}
}
I would like to input values in the following way:
.\checkport '192.186.1.5'
or
'192.168.1.5', '192.168.1.105', 192.168.1.110' | checkport
It doesn't seem to be reading IP address or displaying results.
I was wondering if anyone could point out there could show me what I am doing wrong in with this script?
A: I've been able to use the 'Test-Port' function from Boe Prox for similar scan/ reporting functions, the code is available on PoshCode:
http://poshcode.org/2514
When I needed to test ports for Directory health, I built a csv with 'port' and 'protocol' columns, then added the port number/ protocol for each port to check. This was used in the following script:
. .\test-port.ps1
$computersToCheck = get-content .\computers.txt
$portList = Import-CSV .\portList.csv
foreach($entry in $portList)
{
$testPortParams = @{
port = $($entry.port)
}
if( $($entry.protocol) -eq "tcp")
{ $testPortParams += @{ TCP = $true } }
else
{ $testPortParams += @{ UDP = $true } }
$outLog = "portTest-$($entry.port)-$($entry.protocol).txt"
$computersToCheck |
Test-Port @testPortParams |
Sort-Object -Property open,name -descending |
format-table -auto -outVariable status
Add-Content -path $outLog -value $status
}
You could certainly build a feeder script to build the range of IP addresses and ports to scan.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19213830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Why does my code not iterate over each line? There is a key error "\n" despite stripping off(.txt input fed in using .read()) I have a .txt file of DNA sequences in the format shown below:
>seq1
ATATAT
>seq2
GGGGG
>seq3
TTTTT
Using re.sub, I have removed the lines with ">seq" numbers like this, to have an input of just lines of DNA bases A, G, C and T like this, and then stripped the "\n" as follows:
ATATAT
GGGGG
TTTTT
import re
test = re.sub('\ |1|2|3|4|5|6|7|8|9|0|>|s|e|q|:', "", holder)
newone = test.rstrip("\n")
I would then like to use this as input into my one hot encoder, which is encased within an if statement (there is an if statement to check if any unexpected letters are present in the DNA sequence). So far it looks like this:
for line in newone:
#if undesirable letters are present in sequence, an error message is displayed
if (bool(result)) == True:
print("The input sequence is invalid.")
#if sequence is in the correct format, proceed with one hot encoding
else:
#mapping of bases to integers as a dictionary
bases = "ATCG"
base_to_integer = dict((i, c) for c, i in enumerate(bases))
#encoding input sequence as integers
integer_encoded = [base_to_integer[y] for y in newone]
#one hot encoding
onehot_encoded = list()
for value in integer_encoded:
base = [0 for x in range(len(bases))]
base[value] = 1
onehot_encoded.extend(base)
print(onehot_encoded)
I can see this error in the shell, but I am not sure why, because I think I have indicated in my code that "\n" needs to be stripped:
Traceback (most recent call last):
File "C:\Users\Agatha\Documents\testtt.py", line 38, in <module>
integer_encoded = [base_to_integer[y] for y in newone]
File "C:\Users\Agatha\Documents\testtt.py", line 38, in <listcomp>
integer_encoded = [base_to_integer[y] for y in newone]
KeyError: '\n'
I would like my program to iterate the code over each line of my input file, but I am not sure if my for loop ("for line in newone") will achieve this if the \n is stripped, and I cannot work out how I could rearrange this to make it work.
I am aiming to have my output in this kind of format, where each one-hot-encoded sequence is displayed on a separate line, e.g:
[1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0
0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1]
I would appreciate any advice on what the source of this error is and how I could go about fixing it.
A: If I were you, I would use the .split() method to create a list from the text you read.
test = re.sub('\ |1|2|3|4|5|6|7|8|9|0|>|s|e|q|:', "", holder)
newone = test.split("\n")
at this point newone will look like ['', 'ATATAT', '', 'GGGGG', '', 'TTTTT', ''] so to strip out the extra spaces:
newone = [x for x in newone if x != '']
Now to the error you are receiving, it is because you in your list comprehension (line 38 of your code) you are using newone instead of line. Each letter of line is an key of your dictionary base_to_integer but the KeyError you get is because \n is not a Key in the dictionary. Even after making the change I suggest above you will get an error:
KeyError: 'ATATAT'
So you should change this line to:
integer_encoded = [base_to_integer[y] for y in line]
Fixing this gives me:
[1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0]
[0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1]
[0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0]
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57075481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Mod_python error: ImportError: Could not import settings Trying to get Django to work with Apache, and I'm getting the following error:
ImportError: Could not import settings 'MyDjangoApp.settings' (Is it on sys.path? Does it have syntax errors?): No module named MyDjangoApp.settings
My Django app is located in /home/user/django/MyDjangoApp/
My httpd.conf Location section looks like:
<Location "/MyDjangoApp/">
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE MKSearch.settings
PythonOption django.root /MyDjangoApp
PythonPath "['/home/user/django/MyDjangoApp/','/var/www'] + sys.path"
PythonDebug On
</Location>
Please tell me how to correct the location section to make Django work?
A: Giving this answer for completeness - even though your case was different.
I've once named my django project test. Well, django was importing python module test - which is a module for regression testing and has nothing to do with my project.
This error will occur if python finds another module with the same name as your django project. Name your project in a distinct way, or prepend the path of the parent directory of your application to sys.path.
A: I think mod_python is looking for settings in the MKSearch module which doesn't exist in side the /home/user/django/MyDjangoApp directory. Try adding the parent dir to the PythonPath directive as below:
<Location "/MyDjangoApp/">
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE MKSearch.settings
PythonOption django.root /MyDjangoApp
PythonPath "['/home/user/django/', '/home/user/django/MyDjangoApp,'/var/www'] + sys.path"
PythonDebug On
</Location>
Or remove the module name from the DJANGO_SETTINGS_MODULE env var as below:
<Location "/MyDjangoApp/">
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE settings
PythonOption django.root /MyDjangoApp
PythonPath "['/home/user/django/MyDjangoApp,'/var/www'] + sys.path"
PythonDebug On
</Location>
A: The following example, located in my Apache configuration file, works. I found it very hard to get mod_python to work despite good answers from folks. For the most part, the comments I received all said to use mod_wsgi, instead of mod_python.
Comments I've seen including from the Boston Python Meetup all concur mod_wsgi is easier to use. In my case on Red Hat EL 5 WS, changing from mod_python is not practical.
<Location />
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE settings
PythonOption django.root /home/amr/django/amr
PythonPath "['/home/amr/django', '/home/amr/django/amr', '/usr/local/lib
/site-packages/django'] + sys.path"
PythonDebug On
</Location>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/962533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Why keyboard event function of "Enter" button is not working; I have the following very simple HTML
AND at the if statement at js script I am just trying to insert an additional functionality when someone enters the "Enter" button - but Idk WHY it's not working!
document.querySelector(".subText").addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
let x = document.querySelector("#fname").value;
console.log(x);
}
});
<body>
<div class="wrapper">
<div class="container">
<div class="toDo">
<!-- <svg xmlns="http://www.w3.org/2000/svg" class="ionicon" viewBox="0 0 512 512">
<path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M224 184h128m-128 72h128m-128 71h128"/>
<path d="M448 258c0-106-86-192-192-192S64 152 64 258s86 192 192 192 192-86 192-192z" fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="32"/>
<circle cx="168" cy="184" r="8" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"/>
<circle cx="168" cy="257" r="8" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"/>
<circle cx="168" cy="328" r="8" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"/>
</svg> -->
<p class="toDoText">To-do List</p>
</div>
<div>
<input type="text" id="fname" name="fname" placeholder="I need to..." class="inputText">
<input type="submit" value="Submit" class="subText" onclick="addNote()">
</div>
</div>
<div class="test">
<!-- <div class="notesList">
<p class="notesInput">ddbd</p>
<button class="deleteBut" onclick="deleFunc()">
</button>
</div> -->
</div>
</div>
</body>
A: The function is called and the if statement executed correctly.
Here, I've edited the console.log lines.
Run the snippet.
Click the text box, use the tab key to select the button, then hit the enter key.
Et voila! 3 console.log statements run.
Perhaps you need to refine your understanding of what's happening and from that, your question. :)
document.querySelector(".subText").addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
let x = document.querySelector("#fname").value;
// console.log(x);
console.log("console.log(x); (1)");
}
});
function addNote() {
let x = document.querySelector("#fname").value;
// console.log(x);
console.log("console.log(x); (2)");
let divN = document.createElement("div");
divN.classList.add("notesList");
let para = document.createElement("p");
para.classList.add("notesInput");
divN.appendChild(para);
let paraText = document.createTextNode(x);
// console.log(paraText);
console.log("console.log(paraText); (3)");
para.appendChild(paraText);
let but = document.createElement("button");
but.classList.add("deleteBut");
but.setAttribute("onclick", "deleFunc()")
divN.appendChild(but);
let y = document.querySelector(".test");
y.appendChild(divN);
}
<body>
<div class="wrapper">
<div class="container">
<div class="toDo">
<!-- <svg xmlns="http://www.w3.org/2000/svg" class="ionicon" viewBox="0 0 512 512">
<path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M224 184h128m-128 72h128m-128 71h128"/>
<path d="M448 258c0-106-86-192-192-192S64 152 64 258s86 192 192 192 192-86 192-192z" fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="32"/>
<circle cx="168" cy="184" r="8" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"/>
<circle cx="168" cy="257" r="8" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"/>
<circle cx="168" cy="328" r="8" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"/>
</svg> -->
<p class="toDoText">To-do List</p>
</div>
<div>
<input type="text" id="fname" name="fname" placeholder="I need to..." class="inputText">
<input type="submit" value="Submit" class="subText" onclick="addNote()">
</div>
</div>
<div class="test">
<!-- <div class="notesList">
<p class="notesInput">ddbd</p>
<button class="deleteBut" onclick="deleFunc()">
</button>
</div> -->
</div>
</div>
</body>
A:
With the if statement I am just trying to insert an additional functionality when someone enters the "Enter" button - Idk WHY it's not working!
You added the listener on the button, instead of adding a listener to the input field.
and with the rest of the code inside addNote() function, I am trying to create an element every time the user inserts a new input -similar to that, which is commented out at HTML code. However, it seems that styling from the element generated from JS just breaks in contrary with the div I have commented out in HTML...
I rearranged your code, so it's more readable. I would suggest to refactor each creation and attribute changes for each element to methods of their own, to make the code even more readable.
During my rearrangement, I automatically solved your problem, by putting the code in the right order. Now the generated code looks like your commented code.
I also added an event listener to your button. If you remove the button, you need to remove the event listener too, otherwise there will be a memory leak.
I would also like to suggest that you start using id and getElementByID instead of querySelect and class, just to create a pattern where id on an element indirectly says that it's used together with javascript.
document.getElementById("fname").addEventListener("keyup", function(event) {
if (event.key === "Enter") {
addNote();
}
});
function addNote() {
let x = document.querySelector("#fname");
let divN = document.createElement("div");
let para = document.createElement("p");
let paraText = document.createTextNode(x.value);
let but = document.createElement("button");
let y = document.querySelector(".test");
x.value = '';
divN.classList.add("notesList");
para.classList.add("notesInput");
but.classList.add("deleteBut");
but.addEventListener('click', (event) =>
{ console.log('clicked removed') }
);
divN.appendChild(para);
para.appendChild(paraText);
divN.appendChild(but);
y.appendChild(divN);
}
<body>
<div class="wrapper">
<div class="container">
<div class="toDo">
<!-- <svg xmlns="http://www.w3.org/2000/svg" class="ionicon" viewBox="0 0 512 512">
<path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M224 184h128m-128 72h128m-128 71h128"/>
<path d="M448 258c0-106-86-192-192-192S64 152 64 258s86 192 192 192 192-86 192-192z" fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="32"/>
<circle cx="168" cy="184" r="8" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"/>
<circle cx="168" cy="257" r="8" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"/>
<circle cx="168" cy="328" r="8" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"/>
</svg> -->
<p class="toDoText">To-do List</p>
</div>
<div>
<input type="text" id="fname" name="fname" placeholder="I need to..." class="inputText">
<input type="submit" value="Submit" class="subText" onclick="addNote()">
</div>
</div>
<div class="test">
<!-- <div class="notesList">
<p class="notesInput">ddbd</p>
<button class="deleteBut" onclick="deleFunc()">
</button>
</div> -->
</div>
</div>
</body>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70257627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unable to delete page in Magnolia CMS I'm trying to delete a page from Pages application and I'm receiving success message
But the page is still there.
It's the same when I try to delete a page from JCR, I'm receiving success message, but the node is still there.
I have no info, warning or error messages in the logs.
What I've tried is to turn off the public instance from the Configuration app, but still I'm not able to delete a page.
It's happening only on my author instance.
Any idea, where I can look to find some info why I'm unable to delete a page, or why I have that problem?
Thanks.
Edit:
I don't get the trash bin icon on the page like this:
Just nothing is happening.
Solution:
Ok, I kinda solve it.
This is happening only on macOS Mojave in Safari 12.1.1
It works fine on Windows under Chrome, Firefox, Edge.
A: You need to publish the deleted page. The activation/deactivation of pages does not happen automatically, so if the node disappears immediately after deletion, you won't be able afterwards to publish the "deletion" to public instances, to keep them in sync.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60430471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: XML validation against self-made schema I need to define an interchange format via xsd. I created an example xml file as i intended it to be and want to test that it conforms to the local xsd i created so i tried to validate it via IntelliJIDEA and got following errors. Please point me to what i did wrong.
<?xml version="1.0" encoding="UTF-8"?>
<dictionaryResponse
xmlns="http://dictionaries.persistence.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://dictionaries.persistence.com dictionaries.xsd">
<entry>
<dictionaryCode>2</dictionaryCode>
<id>1</id>
<code>C</code>
</entry>
<entry>
<dictionaryCode>2</dictionaryCode>
<id>2</id>
<code>V</code>
</entry>
<entry>
<dictionaryCode>2</dictionaryCode>
<id>3</id>
<code>R2</code>
</entry>
<entry>
<dictionaryCode>2</dictionaryCode>
<id>4</id>
<code>TM</code>
</entry>
<entry>
<dictionaryCode>2</dictionaryCode>
<id>5</id>
<code>SN</code>
</entry>
<entry>
<dictionaryCode>2</dictionaryCode>
<id>6</id>
<code>SA</code>
</entry>
</dictionaryResponse>
dictionaries.xsd
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0" targetNamespace="http://dictionaries.persistence.com" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:complexType name="dictionaryRequest">
<xs:sequence>
<xs:element name="dictionaryCode" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="dictionaryResponse">
<xs:sequence>
<xs:element name="entry" type="entry" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="entry">
<xs:sequence>
<xs:element name="dictionaryCode" type="xs:string"/>
<xs:element name="id" type="xs:string"/>
<xs:element name="code" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
Errors:
Error:(12, 74) src-resolve.4.1: Error resolving component 'entry'. It was detected that 'entry' has no namespace, but components with no target namespace are not referenceable from schema document 'file:///opt/idea-IC-141.1532.4/dictionaries.xsd'. If 'entry' is intended to have a namespace, perhaps a prefix needs to be provided. If it is intended that 'entry' has no namespace, then an 'import' without a "namespace" attribute should be added to 'file:///opt/idea-IC-141.1532.4/dictionaries.xsd'.
Error:(5, 83) cvc-elt.1: Cannot find the declaration of element 'dictionaryResponse'.
Entry is defined in the same xsd. I can't understand what's the source of he problem
Thanks for help.
A: Your XML document is a valid instance of the schema below. I have changed the following:
*
*added an xs:element declaration for the outermost element, dictionaryResponse. It is not enough to declare a type of that name, you also have to use this type in an element declaration.
*Added elementFormDefault="qualified" to your schema, because the target namespace should apply to all elements in your document instances. Without it, your schema expects elements that are in no namespace.
*Made http://dictionaries.persistence.com the default namespace of the schema document
*Changed type of entry element to entryType: Do not use the same name for the element name and the name of the type, this can cause a lot of confusion.
XML Schema
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0" targetNamespace="http://dictionaries.persistence.com" xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified" xmlns="http://dictionaries.persistence.com">
<xs:element name="dictionaryResponse" type="dictionaryResponseType"/>
<xs:complexType name="dictionaryRequest">
<xs:sequence>
<xs:element name="dictionaryCode" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="dictionaryResponseType">
<xs:sequence>
<xs:element name="entry" type="entryType" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="entryType">
<xs:sequence>
<xs:element name="dictionaryCode" type="xs:string"/>
<xs:element name="id" type="xs:string"/>
<xs:element name="code" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
There is no dictionaryRequest element in your sample document - are you sure you need a type definition for it?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32425906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Foreach or While -- Best for processing array? So what I am trying to do is process an array. The array contains one thing: photo urls.
When I use foreach()I get a limit error (500 internal error). It seems that it started happening after I rewrote the script. But that doesnt make any sense as there are no errors in the script and it was working perfectly before. The script still works, it can only process about 30 photos before the error pops up. Is it possible to use while() to process the array? Would it get rid of my 500 error for some reason?
Thanks for the input!
Brandon
A: For performance is better foreach cycle.
Visit this site with some benchmark of php and see which cycle is better for you:
http://www.phpbench.com/
A: If you're getting timeout (infinite loops) errors, neither while or foreach will do. You're better off looking at limiting how much your array is processed, and do it step by step (Pagination..?).
for ($i = 0; $i < 100; $i++)
{
//Do your thing. Don't use for each, use $array[$i]
}
if it's not numeric, use a while with two statements:
while ($test = current($array) && $i < 50)
{
//xxxx
next($array);
$i++;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11122527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ansible handling password change on first login I am creating a playbook that login to a Virtual Machine and perform initial configuration. The image used to create the VM has a default user name that need change of password on initial login. I am looking for a way how to handle this in Ansible?
A: I found solution for my problem as follow using ansible module "expect" https://docs.ansible.com/ansible/latest/collections/ansible/builtin/expect_module.html
- name: Change password on initial login
delegate_to: 127.0.0.1
become: no
expect:
command: ssh {{ ansible_ssh_common_args }} {{ user_expert }}@{{ inventory_hostname }}
timeout: 20
responses:
Password: "{{ user_expert_password }}"
UNIX password: "{{ user_expert_password }}"
New password: "{{ user_expert_password_new }}"
new password: "{{ user_expert_password_new }}"
"\\~\\]\\$": exit
register: status
A: You are looking for the user module, especially the password option.
Keep in mind, that the password option needs the hash of the actual password. Check here how to get that it. (It needs to be hashed, otherwise you would have a cleartext password in your playbook or inventory which would be a security risk.)
Example:
- name: ensure password of default user is changed
user:
name: yourdefaultuser
password: '$6$QkjC8ur2WfMfYGA$ZNUxTGoe5./F0b4GJGrcEA.ff9An473wmPsmU4xv00nSrN4D/Nxk8aKro/E/LlQVkUJLbLL6qk2/Lxw5Oxs2m.'
Note that the password hash was generated with mkpasswd --method=sha-512 for the password somerandompassword.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64456955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: PHP convert html to space, > to > etc I want to convert all html tags(  > < etc) to text format;
I have try
html_entity_decode()
but it will return ? if  .
A: Use html_entity_decode() instead of html_entity_encode()
A: If you check the html_entity_decode() manual:
You might wonder why trim(html_entity_decode(' ')); doesn't
reduce the string to an empty string, that's because the ' '
entity is not ASCII code 32 (which is stripped by trim()) but ASCII
code 160 (0xa0) in the default ISO 8859-1 characterset.
You can nest your html_entity_decode() function inside a str_replace() to ASCII #160 to a space:
<?php
echo str_replace("\xA0", ' ', html_entity_decode('ABC XYZ') );
?>
A: Use htmlspecialchars_decode is the opposite of htmlspecialchars.
Example from the PHP documentation page:
$str = '<p>this -> "</p>';
echo htmlspecialchars_decode($str);
//Output: <p>this -> "</p>
A: html_entity_decode() is the opposite of htmlentities() in that it converts all HTML entities in the string to their applicable characters.
$orig = "I'll \"walk\" the <b>dog</b> now";
$a = htmlentities($orig);
$b = html_entity_decode($a);
echo $a; // I'll "walk" the <b>dog</b> now
echo $b; // I'll "walk" the <b>dog</b> now
A: I know my answer is coming in really late but thought it might help someone else. I find that the best way to extract all special characters is to use utf8_decode() in php. Even for dealing with or any other special character representing blank space use utf8_decode().
After using utf8_decode() one can manipulate these characters directly in the code. For example, in the following code, the function clean() replaces with a blank. Then it replaces all extra white spaces with a single white space using preg_replace(). Leading and trailing white spaces are removed using trim().
function clean($str)
{
$str = utf8_decode($str);
$str = str_replace(" ", "", $str);
$str = preg_replace("/\s+/", " ", $str);
$str = trim($str);
return $str;
}
$html = " Hello world! lorem ipsum.";
$output = clean($html);
echo $output;
Hello world! lorem ipsum.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15289772",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: Identify special characters in Excel based on column names I found a code that uses RegEx to determine if there are any special characters in a column. I have just found out about RegEx today and I tried editing this code but I have encountered 3 problems:
*
*It uses "ActiveSheet" but I have read that it might cause problems. I would like it to only check the worksheet named "Consolidated." I tried Worksheets.("Consolidated").Range in the For Each line but it doesn't accept it.
*This applies to the whole worksheet. I would like to know if it's possible to apply it to a column based on it's name (ex: First Name) and not on it's range because the columns are not fixed in the consolidated worksheet.
*It also highlights the 1st row where the column names are located (which should not happen). I do get the logic or the workflow of this but I'm new to vba so I would really like to ask guidance on this.
Dim strPattern As String: strPattern = "[^a-z0-9-]"
Dim regEx As Object
Dim Cell As Range
Set regEx = CreateObject("VBScript.RegExp")
regEx.Global = True
regEx.IgnoreCase = True
regEx.Pattern = strPattern
For Each Cell In ActiveSheet.Range("A:Z") ' Define your own range here
If strPattern <> "" Then ' If the cell is not empty
If regEx.Test(Cell.Value) Then ' Check if there is a match
Cell.Interior.ColorIndex = 6 ' If yes, change the background color
End If
End If
Next
A: I have made the Changes.
*
*Use Find function to locate the column. used cnum for that
*Use Worksheets("Consolidated") without the .
*Pass the column number found to the loop range
Dim strPattern As String: strPattern = "[^a-z0-9-]"
Dim regEx As Object
Dim Cell As Range
Dim cnum As Integer
Set regEx = CreateObject("VBScript.RegExp")
regEx.Global = True
regEx.IgnoreCase = True
regEx.Pattern = strPattern
cnum = Worksheets("Consolidated").Range("A1:Z1").Find("First Name").Column 'column number to search in
For Each Cell In Worksheets("Consolidated").Range(Cells(2, cnum), Cells(1000, cnum))
If strPattern <> "" Then ' If the cell is not empty
If regEx.Test(Cell.Value) Then ' Check if there is a match
Cell.Interior.ColorIndex = 6 ' If yes, change the background color
End If
End If
Next
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56980404",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: IOError: File not open for reading I'm new to programming and I am trying to teach myself Python through http://learnpythonthehardway.org/.
In exercise 20, we are told to make a script like this:
from sys import argv
script, input_file = argv
def print_all(f):
print f.read()
def rewind(f):
f.seek(0)
def print_a_line(line_count, f):
print line_count, f.readline()
current_file = open(input_file)
print "First let's print the whole file:\n"
print_all(current_file)
print "Now let's rewind, kind of like a tape."
rewind(current_file)
print "Let's print three lines:"
current_line = 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
However, when I run it through the Terminal, it returned, "IOError: File not open for reading." I'm really confused and not sure about what it meant by "not open." Here's the full account of the traceback message:
Traceback (most recent call last):
File "ex20.py", line 18, in <module>
print_all(current_file)
File "ex20.py", line 6, in print_all
print f.read()
IOError: File not open for reading
I checked that the file exists. Can someone please help? Thanks a lot!
Update:
I solved the problem by creating a separate folder, thus isolating the new .py and .txt files to a new folder by themselves. I'm wondering if the previous .py files played a role in this? I wrote a truncating script before as well, but it wouldn't make sense because I only executed the new python file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12546361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to declare RDF containers in RDF Schema? When writing an RDF schema, I can do the following to declare that a committee consists of a number of persons:
<rdfs:Class rdf:ID="Committee" />
<rdf:Property rdf:ID="members">
<rdfs:domain rdf:resource="#Committee" />
<rdfs:range rdf:resource="#Person" />
</rdf:Property>
However, I have read that there is a fine semantic difference between defining individual persons as committee members as I did above, and the fact that only the whole group of given persons forms the committee. Hence, in such cases, one should consider using the RDF containers such as rdf:Bag.
My question is: How to declare such a "bag of Persons" in the RDF schema?
Any help is appreciated.
A: If you want to declare that ONLY these people form the commitee, you should use Collection, not rdf:Bag. The RDF tutorial at w3schools.com gives an example:
https://www.w3.org/TR/rdf-schema/#ch_collectionvocab
In the RDF schema you need to declate a property "hasMember" or "member". Its domain is a commitee, and its range is a member. Then, the RDF file can describe an unlimited number of members for a given commitee. If in the commitee resource you want to specify that these are the ONLY memebrs, you use a collection. If you allow more members, use a rdf:Bag.
Note: This does not mean it's impossible to define a "bag of members" or "collection of members" as the range of a property. You can take a look at existing simple ontologies on the web (there are hundreds of them written in RDFS) and compare how they define a similar concept.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12638607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: implementing DFS or recursion and printing the traversed path in python Creating absolute path from XML.
I have created a xml
from lxml import etree
root = etree.Element("root1")
child1 = etree.SubElement(root, "child1")
child2 = etree.SubElement(root, "child2")
child21 = etree.SubElement(child2, "child21")
child201 = etree.SubElement(child21, "child221")
child3 = etree.SubElement(root, "child3")
print(etree.tostring(root, pretty_print=True))
and now i have to print the traversed path like
/root1/child1
/root1/child2
util child has no more child
So far i have came a solution
xpathlist = []
if len(root):
print(len(root))
for child in root:
print(child)
xpath_1 = "/" + root.tag + "/" + child.tag
xpathlist.append("".join(xpath_1.split()))
if len(child):
for minichild in child:
print(minichild)
xpath_1 = "/" + root.tag + "/" + child.tag + "/" + minichild.tag
xpathlist.append("".join(xpath_1.split()))
for xx in xpathlist:
print(xx)
which gives a following out put
/root1/child1
/root1/child2
/root1/child2/child21
/root1/child3
but as you see there is one path missing
/root1/child2/child21/child221
because it is in much deeper depth that my code can not handle and further more depth can be created.
Need a solution which can work with N number of depths and print the traversed path.
A: You can simplify this a lot by using lxml's getpath() method.
This is input.xml:
<root1>
<child1/>
<child2>
<child21>
<child221/>
</child21>
</child2>
<child3/>
</root1>
Here is how you can generate an absolute XPath expression for each element in the XML document:
from lxml import etree
tree = etree.parse("input.xml")
for elem in tree.iter():
print(tree.getpath(elem))
Output:
/root1
/root1/child1
/root1/child2
/root1/child2/child21
/root1/child2/child21/child221
/root1/child3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48959744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Is adding a bot to a Telegram channel broken after update to version 4.1? I can't seem to add a bot to a channel after the latest update to Telegram (to version 4.1).
I can only select administrators from the channel members and I can only add a channel member from my phone contacts. Search for the bot (in this case: @vote) gives empty results.
A: Telegram has intoduced levels of access for Channel admins in the version 4.1.
If you are creator of the channel, you can do everything with your channel, otherwise tell the creator of the channel to give you the required permissions. In your case, the title of permission is: "can add admins"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44871666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Mongodb Spring MVC Does someone know how spring mvc handle nested arrays in mongodb please?
Each time I add an arraylist to my model, at the first hit I got an error and then I press F5 to refresh my page and it works.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36073219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Click Listeners in Loop - Array and Closure I realise I'm treading on thin ice opening another closure issue, but I have searched and can't find an answer to my issue. I have a Google Maps API v3 page which generates two maps from one block of code - a small map centered on the user's current location and a larger map showing the whole area with the user's location marked where it is, center or not. On top of the map is a rectangle layer consisting of 14 rectangles. In order to generate the two maps, I have had to put the rectangles in a 2 dimensional array, rectangles[1] for 'map', and rectangles[2] for 'map2':
var rectangles = [0,1,2,3,4,5,6,7,8,9,10,11,12,13];
rectangles[1][0]=new google.maps.Rectangle({
bounds:new google.maps.LatLngBounds(new google.maps.LatLng(a, b), new google.maps.LatLng(x, y)),
map:map,
fillColor:'red',
fillOpacity: 0.3,
strokeOpacity: 0,
url: 'http://example.com',
clickable: true
});
rectangles[2][0]=new google.maps.Rectangle({
bounds:new google.maps.LatLngBounds(new google.maps.LatLng(a, b), new google.maps.LatLng(x, y)),
map:map2,
fillColor:'red',
fillOpacity: 0.3,
strokeOpacity: 0,
url: 'http://example.com',
clickable: true
});
...and so on. It all works fine and the two maps are displayed and the geolocation works. Now I want to add a click listener for each rectangle but I'm not sure who to reference the array. This is what I have now:
for ( i = 0; i < rectangles[1].length; i++ ){
google.maps.event.addListener(rectangles[1][i], 'click', function() {
window.location.href = this.url;
});
}
for ( x = 0; x < rectangles[2].length; x++ ){
google.maps.event.addListener(rectangles[2][x], 'click', function() {
window.location.href = this.url;
});
}
Which obviously won't work. I have seen various solutions to the closure issue, but I'm not sure I'm even heading in the right direction in referencing the two arrays of rectangles - or if I even need to define two different sets of click listeners. I'd be really grateful if someone could point me in the right direction - and sorry if this is just going over old ground that appears obvious. There's always a new learner coming along who is trying hard to catch up.
Thanks.
A: //First, set up `rectangles` as an array containing two arrays.
var rectangles = [];
rectangles[0] = [];
rectangles[1] = [];
//As `google.maps.Rectangle` doesn't accept a `url` option,
//its url needs to be defined separately from the rectangle itself,
//but in such a way that the two are associated with each other.
//For this we can use a javascript plain object.
rectangles[0][0] = {
rect: new google.maps.Rectangle({
bounds: new google.maps.LatLngBounds(new google.maps.LatLng(a, b), new google.maps.LatLng(x, y)),
map: map,
fillColor: 'red',
fillOpacity: 0.3,
strokeOpacity: 0,
clickable: true
}),
url: 'http://example.com'
};
rectangles[1][0] = new google.maps.Rectangle({
...
});
rectangles[0][1] = new google.maps.Rectangle({
...
});
rectangles[1][1] = new google.maps.Rectangle({
...
});
rectangles[0][2] = new google.maps.Rectangle({
...
});
rectangles[1][2] = new google.maps.Rectangle({
...
});
//Now to attach the click listeners.
//First we define a function that adds a click listener.
//By doing this in its own function, a closure is formed,
//trapping the formal variable `rectObj` and making `rectObj.url`
//accessible to the listener when it is called in response to future clicks.
function addClickListener(rectObj) {
google.maps.event.addListener(rectObj.rect, 'click', function() {
window.location.href = rectObj.url;
});
}
//Now, we can loop through the `rectangles` arrays, adding listeners.
for ( i = 0; i < 2; i++ ) {
for ( j = 0; j < 14; j++ ) {
if(rectangles[i][j]) {//safety
addClickListener(rectangles[i][j]);
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13907103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: UIImageView not displaying image - iPhone SDK I am using AVFramework to capture camera frames and I would like to process and display them in a UIImageView but am having some trouble. I have the code:
// Delegate routine that is called when a sample buffer was written
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
{
//NSLog(@"Capturing\n");
// Create a UIImage from the sample buffer data
UIImage *image = [self imageFromSampleBuffer:sampleBuffer];
NSLog(@"Image: %f %f\n", image.size.height, image.size.width);
[imageView setImage:image];
}
However, it won't display. The correct size shows up in the NSLog, and when I put:
[imageView setImage:[UIImage imageNamed:@"SomethingElse.png"]];
in viewDidLoad, an image is displayed correctly (so I know the UIImageView is connected correctly).
Is there any reason this shouldn't work??? I am at a loss right now.
Cheers,
Brett
A: Are you doing this on the main thread? You can either use the main queue for the delegate (undesirable, because you're doing processing first) or:
dispatch_async(dispatch_get_main_queue(), ^{
imageView.image = ...;
});
A: Is imageView set correctly? If imageView is actually nil, your call to [imageView setImage:image]; will silently do nothing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3408542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: OR filter in neo4j I am a Neo4j newbie.
I have a Neo4j graph with 3 entities: Person, FirstName, Postcode - they are related to each other as follows:
Person -> [:HasFirstName] -> FirstName
Person -> [:HasPostcode] -> Postcode
I have a person in the database:
Tom with Postcode: LA2 0RN
I have this query:
"MATCH(p:Person), (pc:Postcode), (f:FirstName)
WHERE (p)-[:HAS_POSTCODE] -> (pc{value:'LA2 0RN'}) OR (p)-[:HAS_FIRST_NAME]->(f:FirstName {value: "Jerry"})
return DISTINCT p, pc"
It does not return any records even if there is a match for Tom based on his postcode. How do I execute an OR statement so that I can return Tom based on his postcode.
Thanks,
A: With your current code, you are trying to filter patterns with patterns.
Using the WHERE Clause with variables would be the best approach.
Match the pattern first and then filter on the desired property.
You could use the following Query to match users based on their postcode:
MATCH (p:Person)-[:HasPostcode]->(pc:Postcode)
WHERE pc.value='LA2 0RN'
RETURN p, pc
If you want to use an OR condition and find matches for Postcode or Name:
MATCH (f)<-[:HAS_FIRST_NAME]-(p:Person)-[:HasPostcode]->(pc)
WHERE pc.value='LA2 0RN' OR f.value='Jerry' OR f.value='Tom'
RETURN f, p, pc
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72573781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Scikit-learn not being built properly This is my first time trying to install python on any system.
I have followed the guide on:
http://scikit-learn.org/stable/developers/advanced_installation.html
and installed all build dependencies. I then installed using pip:
pip install scikit-learn
I had no errors when installing with pip.
When I try to run my prediction program, which works fine on my environment on cloud9, I get this error:
root@ubuntu-512mb-sfo1-01-PredictionAPI:~/api-for-ml-requests/api# Traceback (most recent call last):
from sklearn.feature_extraction.text import CountVectorizer
File "/usr/local/lib/python2.7/dist-packages/sklearn/__init__.py", line 56, in <module>
from . import __check_build
File "/usr/local/lib/python2.7/dist-packages/sklearn/__check_build/__init__.py", line 46, in <module>
raise_build_error(e)
File "/usr/local/lib/python2.7/dist-packages/sklearn/__check_build/__init__.py", line 41, in raise_build_error
-bash: syntax error near unexpected token `most'
root@ubuntu-512mb-sfo1-01-PredictionAPI:~/api-for-ml-requests/api# File "Backend-Rest-Alpha.1.py", line 9, in <module>
-bash: syntax error near unexpected token `newline'
root@ubuntu-512mb-sfo1-01-PredictionAPI:~/api-for-ml-requests/api# from backend.Predictions import predict
from: can't read /var/mail/backend.Predictions
root@ubuntu-512mb-sfo1-01-PredictionAPI:~/api-for-ml-requests/api# File "/root/api-for-ml-requests/api/backend/Predictions.py", line 1, in <module>
-bash: syntax error near unexpected token `newline'
root@ubuntu-512mb-sfo1-01-PredictionAPI:~/api-for-ml-requests/api# from sklearn.feature_extraction.text import CountVectorizer
from: can't read /var/mail/sklearn.feature_extraction.text
root@ubuntu-512mb-sfo1-01-PredictionAPI:~/api-for-ml-requests/api# File "/usr/local/lib/python2.7/dist-packages/sklearn/__init__.py", line 56, in <module>
-bash: syntax error near unexpected token `newline'
root@ubuntu-512mb-sfo1-01-PredictionAPI:~/api-for-ml-requests/api# from . import __check_build
root@ubuntu-512mb-sfo1-01-PredictionAPI:~/api-for-ml-requests/api# File "/usr/local/lib/python2.7/dist-packages/sklearn/__check_build/__init__.py", line 46, in <module>
-bash: syntax error near unexpected token `newline'
root@ubuntu-512mb-sfo1-01-PredictionAPI:~/api-for-ml-requests/api# raise_build_error(e)
-bash: syntax error near unexpected token `e'
root@ubuntu-512mb-sfo1-01-PredictionAPI:~/api-for-ml-requests/api# File "/usr/local/lib/python2.7/dist-packages/sklearn/__check_build/__init__.py", line 41, in raise_build_error
%s""" % (e, local_dir, ''.join(dir_content).strip(), msg))
ImportError: /usr/local/lib/python2.7/dist-packages/sklearn/__check_build/_check_build.so: undefined symbol: PyUnicodeUCS4_DecodeUTF8
___________________________________________________________________________
Contents of /usr/local/lib/python2.7/dist-packages/sklearn/__check_build:
__init__.py setup.py setup.pyc
_check_build.so __init__.pyc
___________________________________________________________________________
It seems that scikit-learn has not been built correctly.
Does anyone have an idea as to what could be causing this?
A: It seems like your module was built on a python using USC4 encoding, while your python is using USC2.
From the python documentation:
Python was built using 2-byte Unicode characters, and the extension module was compiled using a Python with 4-byte Unicode characters.
This can easily occur when using pre-built extension packages.
The only way to solve this problem is to use extension modules
compiled with a Python binary built using the same size for Unicode
characters.
You should try to install the packages from source. The how-to for sklearn is described in the link you provided with your question - and for the scipy suite you can find instruction here. If you're not using a mac, the links on the top-right menu on that page show the guides for windows and linux as well.
A: As you are new to this, I suggest you to install https://www.continuum.io/downloads#linux
It will solve you problem as it contains scikit-learn and python and all dependencies and also a long list libraries which are used in Python for various task. Also i suggest you to use PyCharm Community Edition as IDE where you can add easily any kind of library you needed without feeling any worry.
https://www.jetbrains.com/pycharm/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41822302",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sign in with curl I tried but I cannot sign in with below code. After execution i show the login page again. Can anybody help me?
$tmp_fname = tempnam("/tmp", "COOKIE");
$curl_handle = curl_init ("https://accessmanager.thy.com/amserver/UI/Login?goto=http%3A%2F%2Fwww2.thy.com%3A80%2Fuhkm");
curl_setopt ($curl_handle, CURLOPT_COOKIEJAR, $tmp_fname);
curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, true);
$post_array = array('gx_charset' => 'UTF-8','encoded' => 'true', 'goto' => 'aHR0cDovL3d3dzIudGh5LmNvbTo4MC91aGtt','IDToken1' => 'XXXXXXXX', 'IDToken2' => 'XXXXXXXX');
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $post_array);
$output = curl_exec ($curl_handle);
$curl_handle = curl_init ("https://accessmanager.thy.com/amserver/UI/Login");
curl_setopt ($curl_handle, CURLOPT_COOKIEFILE, $tmp_fname);
curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
$output = curl_exec ($curl_handle);
echo $output;
A: You need to follow redirects too:
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28128144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: How to install DateTimePicker in Yii2 I have creating form fields. Here, i want to add DateTimePicker.
I have referred in google about some date time picker. i got so many.
DateTimePicker jQuery plugin
Bootstrap DateTimePicker.
My question is which plugin is best among them. and
How can i install that plugin?
*
*Download directory and place where?
*Install via cmd.?
A: You don't need to use jquery plugin for that. Yii2 has several widgets which you can use: Some of them are:
1) Yii2 Jui DatePicker
2) Kartik yii2-widget-datepicker
3) 2amigos yii2-date-picker-widget
You can use anyone of these.
A: You need to install or update your composer.
If you are using Ubuntu or Linux Operating System, open command prompt and run this command:
composer require --prefer-dist yiisoft/yii2-jui
This will create the jui folder which contains all the required plugins such as datepicker or any other you want to use in your website.
Now you just have to place this code in your form.php in views folder
use yii\jui\DatePicker;
<?= $form->field($model, 'from_date')->widget(\yii\jui\DatePicker::classname(), [
//'language' => 'ru',
'dateFormat' => 'MM-dd-yyyy',
]) ?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30679506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ASP.net merge with an existing database? I have a database that's been populated with data on a server. I've made some
changes to the database models and I wish to merge the existing data with the new data without losing everything.
Do you know of an appropriate and no-nonsense method to achieve this?
A: Well one method would be to set up replication from each of them to a single database. But that seems pretty time intensive. I think you might have to write a program to do it (either .net or SQL) because how would it know which record to take if you have two records with the same primary key?
If you know that there will never be any duplicates, you could just write sql statements to do it. But that's a pretty big if.
You might try something like http://www.red-gate.com/products/sql-development/sql-data-compare/ which will synchronize data and I believe it will also figure out what to do when there are two records. I've had very good luck with Red-Gate products.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15810702",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How fix in libgdx blinks screen in Desktop Mode? when i run emulator and start application i see blinks screen, but on a PC in DesktopLauncher screen is normal.
I can not understand where I made mistakes.
render method override but it does not help.
class starter:
public class Drop extends Game {
Camera cam;
Game game;
SpriteBatch batch;
int tempGameScore = 0;
int dropsGatchered = 0;
Preferences preferences;//сохраняем игру
@Override
public void create() {
batch = new SpriteBatch();
this.setScreen(new MainMenuScreen(this));
}
@Override
public void render() {
super.render();
}
@Override
public void dispose() {
batch.dispose();
}
MainMenu:
I think I'm working wrong with the scene tool.
Can it is necessary as otherwise to draw a scene?
public class MainMenuScreen implements Screen {
Sprite texture;
final Drop game;
Skin skin;
Stage stage;
OrthographicCamera camera;
ImageButton newGameButton, exit, highScore;
Table table;
ImageButton.ImageButtonStyle btnplayStyle, btnscoreStyle, btnexitStyle;
private static TextureAtlas atlas, backAtlas;
public MainMenuScreen(final Drop gam) {
this.game = gam;
atlas = new TextureAtlas(Gdx.files.internal("texture/texture.pack"), true);
backAtlas = new TextureAtlas(Gdx.files.internal("texture/background.pack"), true);
texture = new Sprite(backAtlas.findRegion("background"));
skin = new Skin();
skin.addRegions(atlas);
table = new Table();
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
stage = new Stage();
stage.addActor(table);
Gdx.input.setInputProcessor(stage);// Make the stage consume events
table();
}
private void table() {
btnplayStyle = new ImageButton.ImageButtonStyle();
btnplayStyle.up = skin.getDrawable("play");//кнопка не нажата
btnplayStyle.over = skin.getDrawable("play");
btnplayStyle.down = skin.getDrawable("play"); // кнопка нажата
newGameButton = new ImageButton(btnplayStyle);
newGameButton.setSize(300, 200);
stage.addActor(newGameButton);
newGameButton.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
game.setScreen(new GameScreen(game));
}
});
//Button score
btnscoreStyle = new ImageButton.ImageButtonStyle();
btnscoreStyle.up = skin.getDrawable("records");//кнопка не нажата
btnscoreStyle.over = skin.getDrawable("records");
btnscoreStyle.down = skin.getDrawable("records"); // кнопка нажата
highScore = new ImageButton(btnscoreStyle);
highScore.setSize(300, 200);
stage.addActor(highScore);
highScore.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
game.setScreen(new Score(game) {
});
}
});
//Button EXIT
btnexitStyle = new ImageButton.ImageButtonStyle();
btnexitStyle.up = skin.getDrawable("exit");//кнопка не нажата
btnexitStyle.over = skin.getDrawable("exit");
btnexitStyle.down = skin.getDrawable("exit"); // кнопка нажата
exit = new ImageButton(btnexitStyle);
exit.setSize(300, 200);
stage.addActor(exit);
exit.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
Gdx.app.exit();
}
});
table.setBounds(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
game.batch.begin();
game.batch.draw(texture, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
table.add(newGameButton).width(400).height(120);
table.getCell(newGameButton).spaceBottom(30);
table.row();
table.add(highScore).width(400).height(120);
table.getCell(highScore).spaceBottom(30);
table.row();
table.add(exit).width(400).height(120);
table.getCell(exit).spaceBottom(30);
table.row();
game.batch.end();
}
@Override
public void render(float delta) {
stage.act();
stage.draw();
}
@Override
public void resize(int width, int height) {
}
@Override
public void show() {
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void hide() {
}
@Override
public void dispose() {
stage.dispose();
skin.dispose();
}
}
I think I'm working wrong with the scene tool
A: In MainMenuScreen you have to draw things in the render() method, not in the show() method. Like this:
@Override
public void render() {
stage.draw();
// ... possibly more drawing code
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38540384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: nginx rewrite two url segments I have it almost working, just cant get it the last inch.
What I'm trying to do is
https://example.com/ap/variable1/variable2/
and have it go to
https://example.com/ap/index.php?server=$1&guild=$2
where the variables are optional. What I have now is
location /ap/ {
rewrite "^/ap/(.*)/(.*)$" "/ap/index.php?server=$1&guild=$2" last;
}
This mostly works, if I go to the url with the end slash it makes both the variable into one without it, it loads just fine.
if I change the rule to
location /ap/ {
rewrite "^/ap/(.*)/(.*)/$" "/ap/index.php?server=$1&guild=$2" last;
}
I get a 404 when trying to goto the first variable, is there a way to have my cake and eat it too, what am I missing here
A: The first capture is greedy, which means that it will capture everything up to the last / (rather than the first / as you intended). You could make the capture non-greedy by using *? instead of *.
But if the captures are not intended to capture /, you should use the [^/] character class instead. For example:
rewrite ^/ap/([^/]*)/([^/]*)/?$ /ap/index.php?server=$1&guild=$2 last;
The trailing / has also been made optional. See this useful resource on regular expressions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44490588",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Undercomittment in Scrum I have a team of 5 developers working a 10 day sprint schedule. After I deduct the scrum meeting times from their total capacity (300 hrs) I end up with 247.5 hrs.
The breakdown is -
Total - planning - daily scrum * 10 - review - retrospective - backlog grooming
300(5*6*10) - 10 - 12.5 - 5 - 5 - 20
The velocity is currently 25pts/sprint.
However, when the team goes in to the second half of sprint planning, they almost always end up with about 80-85 hours of work planned. That equates to about 35% commitment.
Obviously there are a few possibilities here. Either the team is severely underestimating task hours or there is a lot of hidden work getting in to the sprint or parkinsons law is coming in to effect, and the work is expanding to fill the time allotted. My gut feeling tells me it's all three.
My question really is if the team finds that they are under-committed in the second part of sprint planning, what is a good course of action?
*
*Call the Product Owner back in and take on more work?
*Revisit the task estimates, perhaps using a 3 point method to weed out the critical path?
*Track actuals and make hidden work obvious so we know where the time goes?
*Something else?
I'm not keen on my first 3 suggestions so the 'Something else' is perhaps what I'm looking for. Any advice would be super helpful.
Thanks in advance.
EDIT: I asked this years ago. I was very naive. Don't do this kind of thing,..Ever. Leaving here for others to laugh at :-)
A: The biggest problem that you are facing is that your team is (on purpose or in ignorance) obscuring their work, and hiding what they are doing. You need to improve visibility.
You say always, so I take it that you have some statistics.
Assuming that your team isn't spending the remainder of their capacity being unproductive (working on unplanned tasks, browsing social media sites, daydreaming), it seems that your team is under-planning. If this is the case, you should work to expose the unplanned tasks that are being carried out, and then add them, account for them, or if necessary, have the team stop doing them.
On the other hand, it is possible that your team is purposefully being unproductive, and there is no easy way to handle that. If this is what you are facing, I'd try to figure out why this is happening. Perhaps they are feeling overwhelmed and need an outlet, or they feel that they are doomed regardless of the effort and might as well have fun. This needs to be approached very delicately, though possibly quite forcefully, if nothing changes their mind.
The important thing to remember, is that the numbers and accounting are not the problem - they are only the symptom and indicator of a deeper one, which the Scrum Master should strive to solve.
A: I was pretty much in the same boat a few years back, except we would often end up with overcommitment instead, essentially due to the fractal nature of estimates.
In my current team we decided to take a different approach and just rely on Story Points and velocity to determine sprint commitment. We do break down stories into tasks and give tasks a rough man hours estimate, however we do it essentially as a pretext for discussion/exploration and to lift technical uncertainties. We don't try to sum up estimates and relate it to planned velocity in any way afterwards.
What we do as a team to prevent the (theoretical) Parkinson effect you describe is we always set ourselves an ambitious goal for the coming sprint. This typically means taking one or two "bonus" user stories more than what our velocity would typically allow us to do. This way we're always pushing things forward, challenging ourselves and, even assuming we at some point had a 35% commitment (which I'm not sure how you'd arrive at), the gap would quickly be filled to attain full team speed.
Through that experience, I came to the realization that not tracking task times (especially not getting into complex calculations involving Scrum ceremony times, external activities or meeting durations) and not living under the constant fear of failing to "correctly estimate" is liberating - it allows you to concentrate on what's really important : delivering business value. Shipping quality features is the first priority. Estimating is only a byproduct. Let average velocity be your guide to determine the rough amount of work you can commit to. Embrace potential failure, you'll never get it exactly right anyway.
With starting velocities being equal, I'd pick a team that is bad at estimating because of its surprising repeated productivity improvements over a team that is only improving its estimates (even eventually getting them close to perfectness) any day.
A: For our new team, we "forced" them to plan for the total number of available hours. I didn't force them to add hours to stories, we just took on more stories since there was more time left (and how do you justify to your PO what they will be doing for the other remaining hours?). We did however tell the PO about this strategy and that they wouldn't succeed.
So of course, they end up over-commiting the first few sprints. But then, they realize they need to estimate tasks much better. It took about 3 sprints to get much closer to the reality. Each retrospective was focused on finding out where stories were being underestimated (wrong tasks, missing tasks, underestimated tasks, unknown, etc.). From sprint to sprint, I could see the tasks being refined.
A: Sprint Capacity Planning consists of more than simply subtracting meetings from the Sprint duration. I usually use this calculation:
For a 2 week sprint, consider that you have only 9 working days (one day is lost to Scrum meetings). Multiply this number by the number of people on the team (let's say 7 in my example). So we now have 63 days.
For each person, subtract planned time out of the office (holidays, medical appointments, off-site meetings etc). Let's assume that we have no planned absences. So we still have 63 days.
For each person, consider that they can only be "In the zone" (ie: coding) for a certain number of hours per day. For a new team, I'll use 4 hours per day for the calculation. So we now have 4 * 63 = 252 hours. Compare this to the more simple 63 man days * 8 hours per day = 504 hours and you can see it's almost half.
Finally, I apply a 'mitigation factor' to allow for those distractions that always happen. I subtract 10%. So now, we have 227 hours and that's what we use for planning purposes.
The calculation is not massively scientific but, it seems to work out most of the time.
One final thing. I only use Sprint Capacity Planning when the team are new. Once we have an established velocity, we use that instead. It's faster and usually more accurate.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18079998",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sorting a MultiDecimal Array in PHP I am trying to sort an array with multiDecimal
What I have so far is an array:
Array (
[0] => Array ( [0] => 2, [1] => 20 )
[1] => Array ( [0] => 3, [1] => 30 )
)
What I want to do is sort them like:
Array (
[0] => Array ( [0] => 3, [1] => 30 )
[1] => Array ( [0] => 2, [1] => 20 )
)
I was looking on stackOverflow and it has alot of examples of using usort or uasort but I find the example exact to that problem and not enough commenting to explain the use.
If anyone can help me I would be very grateful.
A: The usort function is the best for you.
Just pass this function as Callback:
$sorter = function($leftArray, $rightArray) {
if ($leftArray[1] == $rightArray[1]) {
return 0;
}
if ($leftArray[1] > $rightArray[1]) {
return 1;
}
return -1;
}
I assumed you want to sort by the value with index 1. If not just change the Index.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28346767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: two identical graphs considered not equal using networkx,
The MultiGraph and MultiDiGraph classes allow you to add the same
edge twice
So I guess it implies the basic class Graph() ignores multiple edges.
I did a test, and found it does ignore multiply edges, however adding same edge twice makes the graph object different. Can somebody explain why? Thanks
import networkx as nx
G1 = nx.Graph()
G1.add_edge(1, 2)
G1.edges() # [(1, 2)]
G1.degree(1) # 1
G2 = nx.Graph()
G2.add_edges_from([(1, 2), (1, 2)])
G2.edges() # [(1, 2)]
G2.degree(1) # 1
G1==G2 # False
A: Your graphs are isomorphic (have the same structure) but are different Python objects. You can test isomorphism with nx.is_ismorphic
import networkx as nx
G1 = nx.Graph()
G1.add_edge(1, 2)
G1.edges() # [(1, 2)]
G1.degree(1) # 1
G2 = nx.Graph()
G2.add_edges_from([(1, 2), (1, 2)])
G2.edges() # [(1, 2)]
G2.degree(1) # 1
print G1==G2 # False
print repr(G1),repr(G2)
print nx.is_isomorphic(G1,G2)
#OUTPUT
# False
#<networkx.classes.graph.Graph object at 0x7fda3174c050> <networkx.classes.graph.Graph object at 0x7fda3463e890>
#True
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36411129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to collect all nodes of a Tree structure, grouped by depth level? I have a classic Tree-structure with childs and parent node. Now, i would like to collect all nodes grouped by depth starting from the lowest level (i.e. in reverse order), like this:
nodes[
["A4"],
["A3","B3"],
["A2","B2","C2"],
["A1","B1","C1"],
["ROOT"]
];
While getting the depth level by using the recursive traversal approach is very easy, i'm wonder if there is any method to get immediately the depth level during the Tree traversal in a BFS or DFS search.
I'am aware that i could store the depth level during the node insertion, but as i'm doing a lot of insertion and removals, i would prefer to collect the whole structure grouped by level just in one shot.
Also, i haven't any preference to use BDS or DFS at all, both are just fine. Here is my actual code:
function Node(code, parent) {
this.code = code;
this.children = [];
this.parentNode = parent;
}
Node.prototype.addNode = function (code) {
var l = this.children.push(new Node(code, this));
return this.children[l-1];
};
Node.prototype.dfs = function (leafCallback) {
var stack=[this], n, depth = 0;
while(stack.length > 0) {
n = stack.pop();
if(n.children.length == 0) {
if(leafCallback) leafCallback(n, this);
continue;
}
for(var i=n.children.length-1; i>=0; i--) {
stack.push(n.children[i]);
}
depth++; // ???
}
};
var tree = new Node("ROOT");
tree.addNode("A1").addNode("A2").addNode("A3").addNode("A4");
tree.addNode("B1").addNode("B2").addNode("B3");
tree.addNode("C1").addNode("C2");
A: You can use recursion and passing node and depth as parameters
function Node(code, parent) {
this.code = code;
this.children = [];
this.parentNode = parent;
}
Node.prototype.addNode = function (code) {
var l = this.children.push(new Node(code, this));
return this.children[l-1];
};
let result = [], depth = {};
function dfs(node){
node.depth = 0;
let stack = [node];
while(stack.length > 0){
let root = stack[stack.length - 1];
let d = root.depth;
result[d] = result[d] || [];
result[d].push(root.code);
stack.length--;
for(let element of root.children){
element.depth = root.depth + 1;
stack.push(element);
}
}
}
var tree = new Node("ROOT");
tree.addNode("A1").addNode("A2").addNode("A3").addNode("A4");
tree.addNode("B1").addNode("B2").addNode("B3");
tree.addNode("C1").addNode("C2");
dfs(tree);
console.log(result.reverse());
A: It is possible to write this in a recursive way which would benefit from tail optimisation
function reduceTree(tree) {
const getCode = n => n.code;
const _reduce = (level = [tree], acc = [[getCode(tree)]], depth = 1) => {
const children = level.reduce((a, e) => a.concat(e.children), []);
if (!children.length) {
return acc;
}
acc[depth] = children.map(getCode);
return _reduce(children, acc, depth + 1);
};
return _reduce().reverse();
}
reduceTree(tree);
/*
[
["A4"],
["A3", "B3"],
["A2", "B2", "C2"],
["A1", "B1", "C1"],
["ROOT"]
]
*/
A: That's it - thanks to marvel308 for pointing out that there is required an additional helper node.depth
function Node(code, parent) {
this.code = code;
this.depth = -1;
this.children = [];
this.parentNode = parent;
}
Node.prototype.dfs= function() {
var result = [], stack = [];
this.depth = 0;
stack.push(this);
while(stack.length > 0) {
var n = stack[stack.length - 1], i = n.depth;
if(!result[i]) result.push([]);
result[i].push(n); /* get node or node.code, doesn't matter */
stack.length--;
var children = n.children;
/* keep the original node insertion order, by looping backward */
for(var j = n.children.length - 1; j >= 0; j--) {
var c = children[j];
c.depth = n.depth + 1;
stack.push(c);
}
}
return result.reverse(); /* return an array */
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46388163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Bootstrap navigationbar right align I'm learning bootstrap and I'm trying to make a navigation bar with a logo on the left side and nav-links on the right side and I don't understand why ml-auto is not working in my code.
<html lang="en">
<head>
<title>Bootstrap</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-md navbar-light bg-light sticky-top">
<div class="container-fluid">
<a class="navbar-brand" href="#">SmoothieBar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact</a>
</li>
</ul>
</div>
</div>
</nav>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65593687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Laravel join three tables with relationships How can I join three tables where the foreign ID of each table are part of another,
In the below code, I am trying to get all payments from PaymentsTable which have invoice_id, and InvoiceTables which have customer_id,
Here is DB relationships
Table : Customers
customer_id; Primary Key
Table: Invoices
invoice_id: Primary key
customer_id: Foreign Key, Customers
Table : Payments
payment_id: Primary Key
invoice_id: Foreign Key, Payments
$payments = SalesPayments::where('payment_amount', '!=' , NULL)
->join('sales_invoices', 'sales_invoices.invoice_id', '=', 'sales_payments.invoice_id')
->join('payment_options', 'payment_options.paymentoption_id', '=', 'sales_payments.paymentoption_id')
//->join('customers', 'customers.customer_id', '=', 'sales_payments.invoice_id')
->get();
Below Relationship has been tried in Payments model,
public function customers()
{
return $this->hasManyThrough(Customers::class, SalesInvoices::class, 'payment_id' ,'invoice_id', 'payment_id', 'customer_id' );
}
Now with each payment row, I want to get customer information as well, So How can I get it?
A: Lets assume that you need all payment information with its invoices and customer details related to that payment.
If you are Looking for the above Response then You can Simply Retrieve Data with Nested Eager Loading
Like
$payments=SalesPayments::with('salesInvoice.customer')->where(Your condition)->get();
In Payments Model
public function SalesInvoice(){
return $this->BelongsTo(Your sales model class)
}
In SalesInvoice Model
public function customer(){
return $this->BelongsTo(Your user model class)
}
A: As you have not defined relationships, we have to go with Query builder, Update your joins as below
$payments = DB::table('sales_payments')
->join('sales_invoices', 'sales_invoices.invoice_id', '=', 'sales_payments.invoice_id')
->join('customers', 'sales_invoices.customer_id', '=', 'customers.customer_id')
->join('payment_options', 'payment_options.paymentoption_id', '=', 'sales_payments.paymentoption_id')
->select('sales_payments.*', 'sales_invoices.*', 'customers.*', 'payment_options.*')
->get();
Then you can add where clause.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67331164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Angular js convert string property to boolean inside json object i'm working with angular js and i have the following array that contains many json object , each objects has the property "isSingle" which contains "true" or "false" , my issue is how to convert this property to boolean true or false :
[
{
"noFolder": "AW343",
"type": "T7",
"creationDate": "22/05/2017",
"isSingle": "true"
},
{
"noFolder": "AW35",
"type": "T34",
"creationDate": "09/05/2017",
"isSingle": "false"
},
{
"noFolder": "ASW3",
"type": "T3",
"creationDate": "05/07/2017",
"isSingle": "true"
},
{
"noFolder": "BG5",
"type": "T1",
"creationDate": "22/12/2018",
"isSingle": "false"
}
]
my desired result is to have objects like :
{
"noFolder": "ASW3",
"type": "T3",
"creationDate": "05/07/2017",
"isSingle": true
}
do you have any idea about how to change the type of the property isSingle to bbolean. i'm using angularjs...
A: Simple loop through the objects to convert string to bool:
yourArray.forEach(x => x.isSingle = x.isSingle === 'true');
A: Just Iterate over the array and replace the value as per your requirement like this -
var obj = [
{
"noFolder": "AW343",
"type": "T7",
"creationDate": "22/05/2017",
"isSingle": "true"
},
{
"noFolder": "AW35",
"type": "T34",
"creationDate": "09/05/2017",
"isSingle": "false"
},
{
"noFolder": "ASW3",
"type": "T3",
"creationDate": "05/07/2017",
"isSingle": "true"
},
{
"noFolder": "BG5",
"type": "T1",
"creationDate": "22/12/2018",
"isSingle": "false"
}
]
obj.map((e) => {
e.isSingle == "true" ? e.isSingle = true : e.isSingle = false
});
A: Using reduce method.
let updated_array = array.reduce(function(acc, elem) {
acc.push(Object.assign({}, elem, { isSingle: (elem['isSingle'] == true ? true : false) }));
return acc;
}, []);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50625443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: app.js code comparison because ejs not working I'm using express.js and ejs.
I will post below two codes for the app.js file. The thing is that ejs and layout.ejs do not work with the one of those two codes, but it works perfectly with the other
Here are the two codes:
The first one, which ejs is working:
const express = require('express');
const expressLayouts = require('express-ejs-layouts');
const path = require('path')
const app = express();
// Bodyparser
app.use(express.urlencoded({extended:false}));
/// EJS
app.use(expressLayouts);
app.set('view engine', 'ejs');
//PUBLIC FOLDER(css and js)
app.use(express.static(path.join(__dirname,'/public')));
// Express body parser
app.use(express.urlencoded({ extended: true }));
// Routes
app.use('/', require('./routes/index.js'));
app.use('/users', require('./routes/users.js'));
const PORT = process.env.PORT || 5000;
app.listen(PORT, console.log(`Server started on port ${PORT}`));
and the second one, which ejs is not working:
const express = require('express');
const app = express();
const PORT = process.env.PORT || 5000;
const expressLayouts = require('express-ejs-layouts');
const mongoose = require('mongoose');
const path = require('path')
// Bodyparser
app.use(express.urlencoded({extended:false}));
//ROUTES
app.use('/', require('./routes/index'))
app.use('/users', require('./routes/users'))
// EJS
app.use(expressLayouts);
app.set('view engine', 'ejs');
app.set('view options', { layout:'layout.ejs' });
//PUBLIC FOLDER(css and js)
app.use(express.static(path.join(__dirname,'/public')));
//DB CONFIG
const db = require('./config/keys').MongoURI;
// //Connect to mongo
mongoose.connect(db, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then( () => console.log('MongoDB Connected...'))
.catch( err => console.log(err));
app.listen(PORT, console.log(`Server started on PORT ${PORT}`));
I'm trying to figure out what's the issue with the second code and doesn't make the ejs work. Can anyone have a quick glimpse and compare these two and tell me what's the problem? Thank you for your time
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61252430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it safe to use startActivityForResult() for sensitive data? I'm looking into starting an Activity (different app) with some parameters (sensitive session) and was wondering what's the safest way here. For instance, startActivityForResult() may be used on Android and I was wondering if any other app can see this request or if it requires root rights to intercept such a request? So basically, is it safe to use it or not? By default, we assume users don't have root rights.
A:
I was wondering if any other app can see this request
The app that responds to your startActivityForResult() call can see the request. That could be:
*
*The real unmodified app that you wish to send the data to
*A hacked version of that app
*A completely independent app that happens to match your Intent, particularly if you are using an implicit Intent
You can try to check signatures to confirm whether the other app is indeed the real unmodified app, so you avoid the latter two scenarios.
On older versions of Android, the Intent would be visible to other apps as part of the data backing the overview screen (recent-tasks list). That was cleared up somewhere in the 4.x series IIRC.
Those are the only two attacks that I know of for non-rooted devices.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57058231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to create a new dataframe column with shifted values from another column? I am returning data from a database query and want to create a new column in the resulting dataframe. I need to shift the results of one column forward one month to create a new column.
I have a dataframe that is populated from a sql query and has the format:
df.dtypes
ACTIVITY_MONTH datetime64[ns]
PRODUCT_KEY object
COUNT float64
When I run:
df['NEW_COUNT'] = df.groupby('PRODUCT_KEY')['COUNT'].shift(+1)
I get this error:
ValueError: cannot reindex from a duplicate axis
This error doesn't make sense to me and I am not sure what to do to fix it. Any help is appreciated.
A: The error ValueError: cannot reindex from a duplicate axis indicates in this case that you have duplicate entries in your index (and for this reason, it cannot assign to a new column, as pandas cannot know where to place the values for the duplicate entries).
To check for duplicate values in the index, you can do:
df.index.get_duplicates()
And then to get rid of the duplicate values (if you don't need to keep the original index), you can eg do df.reset_index(drop=True), or you can use ignore_index=True in append or concat.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24053576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: AWK - Compare Two Files - If Field1 is Same, Compare Lines There are two files. When field1 is the same in both files, compare the corresponding lines. If they are exactly the same, then next. If there are more or less line or if the contents are different, then echo field1.
In the example below, LSP1 and LSP2 have differences. The differences are the total number of lines but it could also have been the contents of field2 and/or field3. LSP3 is the same. The desired output is below.
File1
LSP1 3.3.3.3 ae3.0
LSP1 5.5.5.5 ae2.0
LSP1 4.4.4.4 ae4.0
LSP1 7.7.7.7 ae1.0
LSP2 7.7.7.7 ae6.0
LSP2 3.3.3.3 ae4.0
LSP2 5.5.5.5 ae6.0
LSP2 4.4.4.4 ae1.0
LSP2 2.2.2.2 ae2.0
LSP3 5.5.5.5 ae4.0
LSP3 4.4.4.4 ae5.0
LSP3 7.7.7.7 ae3.0
File2
LSP1 3.3.3.3 ae3.0
LSP1 8.8.8.8 ae2.0
LSP1 4.4.4.4 ae4.0
LSP1 7.7.7.7 ae1.0
LSP1 2.2.2.2 ae2.0
LSP2 7.7.7.7 ae6.0
LSP2 3.3.3.3 ae1.0
LSP2 2.2.2.2 ae2.0
LSP3 5.5.5.5 ae4.0
LSP3 4.4.4.4 ae5.0
LSP3 7.7.7.7 ae3.0
Output
LSP1
LSP2
A: With single awk:
awk '{ k=$1 FS $2 FS $3 }NR==FNR && NF{ a[k]=$1; next }
NF{ if(k in a) delete a[k]; else if(!b[$1]++) print $1 }
END{ for(i in a) if(!(a[i] in b)) print a[i] }' file1 file2
The output:
LSP1
LSP2
A: $ comm -3 file1 file2 | awk '$1 { print $1 }' | uniq
LSP1
LSP2
comm -3 will output the lines that are only in file1 xor in file2.
The awk script will extract column 1 from non-empty lines (whitespace-separated) and uniq will remove duplicates.
Note that comm assumes sorted input.
A: $ awk -v RS= 'NR==FNR{a[$1]=$0;next} $0!=a[$1]{print $1}' file1 file2
LSP1
LSP2
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46061929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: passing children or css attribute to component style config chakra ui Is there a possibility to pass a children prop or atleast css attribute like title to component style config in chakra ui?
A: When using "attr" just pass the variable as a plain string instead of wrapping it with template literals. Using children is not possible there i guess.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73260434",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sort Hierarchical table in SQL Server? I have a table Address and I want to sort rows like parent-1 => all-child-parent-1, parent-2 => all-child-parent-2 so on ....
Address Table
ID Caption Parent
---------------------
1 A NULL
2 B NULL
3 a 1
4 b 2
5 bb 4
6 C NULL
7 aa 3
8 c 6
NULL Parent is is mean Root
Desired output
ID Sort Caption Parent
---------------------------
1 1 A NULL
3 2 a 1
7 3 aaa 3
2 4 B NULL
4 5 b 2
5 6 bb 4
6 7 C NULL
8 8 c 6
A: Yet one more option is to use the hierarcyid data type
Example
Declare @YourTable Table ([ID] int,[Caption] varchar(50),[Parent] int) Insert Into @YourTable Values
(1,'A',NULL)
,(2,'B',NULL)
,(3,'a',1)
,(4,'b',2)
,(5,'bb',4)
,(6,'C',NULL)
,(7,'aa',3)
,(8,'c',6)
;with cteP as (
Select ID
,Parent
,Caption
,HierID = convert(hierarchyid,concat('/',ID,'/'))
From @YourTable
Where Parent is null
Union All
Select ID = r.ID
,Parent = r.Parent
,Caption = r.Caption
,HierID = convert(hierarchyid,concat(p.HierID.ToString(),r.ID,'/'))
From @YourTable r
Join cteP p on r.Parent = p.ID)
Select Lvl = HierID.GetLevel()
,ID
,Parent
,Caption
From cteP A
Order By A.HierID
Returns
Lvl ID Parent Caption
1 1 NULL A
2 3 1 a
3 7 3 aa
1 2 NULL B
2 4 2 b
3 5 4 bb
1 6 NULL C
2 8 6 c
A: Such sort requires somehow traversing the hierarchy to compute the path of each node.
You can do this with a recursive query:
with cte as (
select id, caption, parent, caption addr
from mytable
where parent is null
union all
select t.id, t.caption, t.parent, c.addr + '/' + t.caption
from cte c
inner join mytable t on t.parent = c.id
)
select
id,
row_number() over(order by addr) sort,
caption,
parent
from c
order by addr
A: You can construct the path to each row and then use that for sorting. The construction uses a recursive CTE:
with cte as (
select id, caption, parent, convert(varchar(max), format(id, '0000')) as path, 1 as lev
from t
where parent is null
union all
select t.id, t.caption, t.parent, convert(varchar(max), concat(path, '->', format(t.id, '0000'))), lev + 1
from cte join
t
on cte.id = t.parent
)
select id, caption, parent
from cte
order by path;
Here is a db<>fiddle.
A: No need for recursion, just use some clever sorting!
SELECT
ID,
ROW_NUMBER() over(order by Caption) as Sort,
Caption,
Parent
FROM Address
ORDER BY Caption, Parent
SQL Fiddle: http://sqlfiddle.com/#!18/bbbbe/9
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60857506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Jquery: Stripping certain Wordpress paragraphs Since Wordpress adds paragraph tags on everything, I need to strip paragraph tags under certain conditions. In this case, I want them off the images. I got that part working:
$(".scroller img").unwrap();
But I think that Wordpress might not add paragraph tags around images forever, so then my code would break, and it would strip the parent instead, which I don't want.
How can I make a check on this, that says "if parent tag is p on the image, then strip it"?
Or how to tell Wordpress not to wrap paragraph tags around solo images would be ok too. :)
Thanks!
A: $(".scroller p>img").unwrap();
This will select and unwrap only img tags with p parents(inside of .scroller)
A: use this as the test for every image
image.parent().get(0).tagName == "P"
It gets the parent block, gets the first element in the block and checks whether its tagname is P
Good luck!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11488851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can't create Workbook failed to use package 'xlsx' to createWorkbook()
R--3.4.4 Windows 7
wb<-createWorkbook()
Error in .jnew("org/apache/poi/xssf/usermodel/XSSFWorkbook") :
Java Exception
(no description because toString() failed).jnew("org/apache/poi/xssf/usermodel/XSSFWorkbook")<S4 object of class "jobjRef">
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56430467",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Concatenate & Trim String Can anyone help me, I have a problem regarding on how can I get the below result of data. refer to below sample data. So the logic for this is first I want delete the letters before the number and if i get that same thing goes on , I will delete the numbers before the letter so I can get my desired result.
Table:
SALV3000640PIX32BLU
SALV3334470A9CARBONGRY
TP3000620PIXL128BLK
Desired Output:
PIX32BLU
A9CARBONGRY
PIXL128BLK
A: You need to use a combination of the SUBSTRING and PATINDEX Functions
SELECT
SUBSTRING(SUBSTRING(fielda,PATINDEX('%[^a-z]%',fielda),99),PATINDEX('%[^0-9]%',SUBSTRING(fielda,PATINDEX('%[^a-z]%',fielda),99)),99) AS youroutput
FROM yourtable
Input
yourtable
fielda
SALV3000640PIX32BLU
SALV3334470A9CARBONGRY
TP3000620PIXL128BLK
Output
youroutput
PIX32BLU
A9CARBONGRY
PIXL128BLK
SQL Fiddle:http://sqlfiddle.com/#!6/5722b6/29/0
A: To do this you can use
PATINDEX('%[0-9]%',FieldName)
which will give you the position of the first number, then trim off any letters before this using SUBSTRING or other string functions. (You need to trim away the first letters before continuing with the next step because unlike CHARINDEX there is no starting point parameter in the PATINDEX function).
Then on the remaining string use
PATINDEX('%[a-z]%',FieldName)
to find the position of the first letter in the remaining string. Now trim off the numbers in front using SUBSTRING etc.
You may find this other solution helpful
SQL to find first non-numeric character in a string
A: Try this it may helps you
;With cte (Data)
AS
(
SELECT 'SALV3000640PIX32BLU' UNION ALL
SELECT 'SALV3334470A9CARBONGRY' UNION ALL
SELECT 'SALV3334470A9CARBONGRY' UNION ALL
SELECT 'SALV3334470B9CARBONGRY' UNION ALL
SELECT 'SALV3334470D9CARBONGRY' UNION ALL
SELECT 'TP3000620PIXL128BLK'
)
SELECT * , CASE WHEN CHARINDEX('PIX',Data)>0 THEN SUBSTRING(Data,CHARINDEX('PIX',Data),LEN(Data))
WHEN CHARINDEX('A9C',Data)>0 THEN SUBSTRING(Data,CHARINDEX('A9C',Data),LEN(Data))
ELSE NULL END AS DesiredResult FROM cte
Result
Data DesiredResult
-------------------------------------
SALV3000640PIX32BLU PIX32BLU
SALV3334470A9CARBONGRY A9CARBONGRY
SALV3334470A9CARBONGRY A9CARBONGRY
SALV3334470B9CARBONGRY NULL
SALV3334470D9CARBONGRY NULL
TP3000620PIXL128BLK PIXL128BLK
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45323064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: cannot set valid itemto QTableWidgetItem I'm trying to populate two different QTableWidgets. For the first one it works find, but for the second one, it won't actaully set the items to the QTableWidget.
In the second, failing attempt, it does successfully create the item (both type(item) and item.text() work fine and return the correct values). However, when I try to add the item to the table, it says that table2.item(row, col) is NoneType. The rows and columns are created correctly before setting the item though.
working attempt:
item = QTableWidgetItem(self.fields[j].name())
item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
table1.setItem(j,i,item)
failing attempt:
item = QTableWidgetItem(typ)
item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
table2.setItem(row, col, item)
Neither can I see the difference between the two blocks, nor do I understand why it won't set the item to the TableWidget. Is there a geneal misunderstandng about how this works?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15339959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Eclipse IDE Sidebar (navigation) missing I'm trying to use Eclipse for my Computer Science class, except the bar on the left is missing. Does anyone know the fix?
A: In menu bar, you can select "Window" -> "Show View", and then select "Project Explorer" (or other components you want to open).
A: Do you mean the package explorer ? You can toggle it here
A: I guess the bar on the left which OP is searching for is Package Explorer.
And it can be found at
Windows > Show View > Package Explorer
Refer the image below.
A: You might be in the Debug option. Click on Java instead. It is on the top right. If you reset Perspective, it won't show you the Navigator.
A: Try going Window > Reset Perspective to go to the default view which should contain the project explorer
A: are you referring to the package explorer view?
Window -> show view -> package explorer
A: If you're missing the Package Explorer, just go to "Window" -> "Show View" and click "Package Explorer"
A: It is known as Navigator, You can find it in Window -> Show View -> Navigator.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18604217",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: BadgeValue not working on moreTableView of TabBarController for iOS 5 (works fine on iOS 6) I have a badgeValue for a ViewController thats shown inside MORE tableview. It works fine on iOS 6 but doesnt work at al with iOS 5 or below.
I am setting the badgeValue of the tabBarItem to set the value to be shown.
Can anyone kindly suggest what to do ?
Thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13465738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: which one of these permissions in manifest says I'm reading phone call information? I have a few permissions in my manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
When I go to install my application, it says it has access to: "Phone calls - read phone state and identity." Which of these permissions is triggering that warning? I never read phone call information. Is it my use of PowerManager.isScreenOn() ?
A: By a process of elimination, I would suggest it was: ACCESS_NETWORK_STATE as none of the others are specifically to do with the phone.
A: It turned out to be an issue with a bug where you need to at least specify a minimum SDK of 4:
Android permissions: Phone Calls: read phone state and identity
A: none of these are related to read phone call info. As it should be like .READ_PHONE_STATE(read phone call). I think it must be because of ACCESS_NETWORK_STATE.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11376364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Omniauth with pow port issue in Rails I'm using Omniauth in my Rails app (which is launched locally using POW). After my providers return to the callback action, I get redirect back in port 19999. I don't want to hard code the port into the redirect_to (e.g.: redirect_to root_url, :port => PORT).
I want either to get the port dynamically or understand why the port is 19999.
If I launch my app normally (rails s -p 3000), the port doesn't change to 19999.
A: You can setup callback url's host with OmniAuth.config.full_host like:
OmniAuth.config.full_host = "http://yourapp.dev"
This must be placed before omniauth is called. I think config/initializes/omniauth.rb is good.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16302709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: building an M3UA association with SCTP I would like to develop an M3UA association using Lksctp linux also I thought it could be possible using openSS7 M3UA but I do not know how to do it. Any more ideas???
Thanks for any help.
A: I think it is better to use Mobicents jSS7
A: You can use lk-sctp in combination with Netty framework over jdk-7 (and above) to implement M3UA (RFC 4666).
Netty-4.0.25-FINAL is stable version for SCTP support.
So the combination is:
*
*SCTP stack : lk-sctp-1.0.16 (over Red Hat Enterprise Linux Server release 6.5 (Santiago))
*JDK-7 or above
*Netty-4.0.25-FINAL
And your application on top of it.
A sample code for SCTPClientHandler can be:
public class SctpClientHandler extends ChannelDuplexHandler {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
throws Exception {
SctpChannel sctpChannel = (SctpChannel) ctx.channel();
if (evt instanceof AssociationChangeNotification) {
AssociationChangeNotification associationChangeNotification = (AssociationChangeNotification) evt;
switch (associationChangeNotification.event()) {
case CANT_START:
//Do something
break;
case COMM_LOST:
//
case COMM_UP:
} else if (evt instanceof PeerAddressChangeNotification) {
PeerAddressChangeNotification peerAddressChangeNotification = (PeerAddressChangeNotification) evt;
int associationId = sctpChannel.association().associationID();
switch (peerAddressChangeNotification.event()) {
case ADDR_ADDED:
}
} else if (evt instanceof SendFailedNotification) {
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
SctpMessage sctpMessage = (SctpMessage) msg;
// Check if this is a M3UA message
if (sctpMessage.protocolIdentifier() == 3) {
// Send upstream - to M3UA
ctx.fireChannelRead(sctpMessage);
}
}
public void send(ByteBuf buffer, int streamId) {
SctpMessage message = new SctpMessage(3, streamId, buffer);
ctx.writeAndFlush(message);
}
public void send(ByteBuf buffer, int streamId, SocketAddress remoteAddress) {
MessageInfo msgInfo = MessageInfo.createOutgoing(remoteAddress,
streamId);
SctpMessage message = new SctpMessage(msgInfo, buffer);
ctx.writeAndFlush(message);
}
public void send(ByteBuf buffer, int streamId, boolean unOrderedFlag) {
SctpMessage message = new SctpMessage(3, streamId, buffer);
message.messageInfo().unordered(unOrderedFlag);
ctx.writeAndFlush(message);
}
public void send(ByteBuf buffer, int streamId, SocketAddress remoteAddress,
boolean unOrderedFlag) {
MessageInfo msgInfo = MessageInfo.createOutgoing(remoteAddress,
streamId);
msgInfo.unordered(unOrderedFlag);
SctpMessage message = new SctpMessage(msgInfo, buffer);
ctx.writeAndFlush(message);
}
}
SCTPServerHandler can also be created as above.
For initializing Bootstrap:
bootstrap.group(worker)
.channel(NioSctpChannel.class)
.option(SctpChannelOption.SCTP_NODELAY,true)
.handler(new ChannelInitializer<SctpChannel>() {
@Override
public void initChannel(SctpChannel ch) throws Exception {
ch.pipeline().addLast(
new SctpClientHandler());
ch.pipeline().addLast(new M3UAAspHandler());
}
});
This combination scales a lot as well. Happy coding.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29622638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Script created in Spyder but not found in normal folder I've donwloaded Spyder IDE(inside Anaconda) in order to do a data science 101 course and started to create some simple scripts
the cwd is C://python/ and in normal folder, they aren't showed
As you can see, in spyder explorer view, the script exist, but with CMD or normal folder browser, it does not see anything, like they were never created(but they exist somehow).
Checked rights and users in windows, but I'm the admin, so there should be no problem.
Why I can't see my scripts in normal folder?
OS : win 8 with Python 3.7, Anaconda Navigator 1.9.2 Spyder 3.3.1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52726459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to fix PyQt5 GUI freezing I've created a simple GUI for my python app with QtDesigner. When i try to run my code it works properly but my problem now is that when i try to run my code using the convert button on my GUI the interface freeze or unresponsive and it will only be responsive after it finishes executing the code. Now my question is how can i fix this?
Heres my code:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'GUI.ui'
#
# Created by: PyQt5 UI code generator 5.13.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QFileDialog, QMessageBox
import sys
import excel2img
import openpyxl as xl
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(361, 303)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.btn_exit = QtWidgets.QPushButton(self.centralwidget)
self.btn_exit.setGeometry(QtCore.QRect(270, 240, 75, 23))
self.btn_exit.setObjectName("btn_exit")
self.btn_openfile = QtWidgets.QPushButton(self.centralwidget)
self.btn_openfile.setGeometry(QtCore.QRect(40, 30, 75, 23))
self.btn_openfile.setObjectName("btn_openfile")
self.btn_convert = QtWidgets.QPushButton(self.centralwidget)
self.btn_convert.setGeometry(QtCore.QRect(40, 60, 75, 23))
self.btn_convert.setObjectName("btn_convert")
#self.btn_send = QtWidgets.QPushButton(self.centralwidget)
#self.btn_send.setGeometry(QtCore.QRect(40, 90, 75, 23))
#self.btn_send.setObjectName("btn_send")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 361, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
#Widgets
self.btn_openfile.clicked.connect(self.openfile)
self.btn_exit.clicked.connect(self.exit)
self.btn_convert.clicked.connect(self.convert)
#Widgets
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.btn_exit.setText(_translate("MainWindow", "Exit"))
self.btn_openfile.setText(_translate("MainWindow", "Open File"))
self.btn_convert.setText(_translate("MainWindow", "Convert File"))
#self.btn_send.setText(_translate("MainWindow", "Send Payroll"))
#My Functons
fileName = ''
@classmethod
def openfile(cls):
fname = QFileDialog.getOpenFileName(None, "Open File", "", "Excel files (*.xlsx *xls)")
cls.fileName = fname[0]
def exit(self):
quit_msg = "Are you sure you want to exit the program?"
reply = QMessageBox.question(None, 'Prompt',
quit_msg, QMessageBox.Yes | QMessageBox.No)
if reply == QMessageBox.Yes:
sys.exit()
def convert(self):
wb = xl.load_workbook(self.fileName, read_only=True)
ws = wb.active
a, b = 2, 2
x, y = 1, 44
z, w = 1, 44
max_row = ws.max_row
temp = 0
loop_num = 0
while temp < max_row:
temp += 52
loop_num += 1
print(loop_num)
for i in range(loop_num * 2):
if i % 2 == 0:
cell = "Sheet1!A{}:F{}".format(x,y)
ccell = 'B{}'.format(a)
var = ws[ccell].value
a += 52
x += 52
y += 52
else:
cell = "Sheet1!H{}:M{}".format(z,w)
ccell = 'I{}'.format(b)
var = ws[ccell].value
b += 52
z += 52
w += 52
name = '{}.png'.format(var)
excel2img.export_img(self.fileName, name, "", cell )
print('generating image {}'.format(i + 1))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
A: First of all you should not modify the class generated by Qt Designer so before applying my solution you must regenerate the .py so you must use pyuic again:
pyuic5 your_ui.ui -o design.py -x
onsidering the above, the problem is that you have a time consuming task blocking the eventloop preventing it from doing its jobs like reacting to user events. A possible solution for this is to use threads:
import sys
import threading
from PyQt5 import QtCore, QtGui, QtWidgets
import excel2img
import openpyxl as xl
from design import Ui_MainWindow
def task(fileName):
wb = xl.load_workbook(fileName, read_only=True)
ws = wb.active
a, b = 2, 2
x, y = 1, 44
z, w = 1, 44
max_row = ws.max_row
temp = 0
loop_num = 0
while temp < max_row:
temp += 52
loop_num += 1
print(loop_num)
for i in range(loop_num * 2):
if i % 2 == 0:
cell = "Sheet1!A{}:F{}".format(x, y)
ccell = "B{}".format(a)
var = ws[ccell].value
a += 52
x += 52
y += 52
else:
cell = "Sheet1!H{}:M{}".format(z, w)
ccell = "I{}".format(b)
var = ws[ccell].value
b += 52
z += 52
w += 52
name = "{}.png".format(var)
excel2img.export_img(fileName, name, "", cell)
print("generating image {}".format(i + 1))
class MainWindow(QtWidgets.Ui_MainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
# Widgets
self.btn_openfile.clicked.connect(self.openfile)
self.btn_exit.clicked.connect(self.exit)
self.btn_convert.clicked.connect(self.convert)
fileName = ""
@classmethod
def openfile(cls):
cls.fileName, _ = QtWidgets.QFileDialog.getOpenFileName(
None, "Open File", "", "Excel files (*.xlsx *xls)"
)
def exit(self):
quit_msg = "Are you sure you want to exit the program?"
reply = QtWidgets.QMessageBox.question(
None,
"Prompt",
quit_msg,
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
)
if reply == QtWidgets.QMessageBox.Yes:
sys.exit()
def convert(self):
threading.Thread(target=task, args=(self.fileName,), daemon=True).start()
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
A: You should call QtCore.QCoreApplication.processEvents() within your for loop to make the Qt's event loop proceed the incoming event (from keyboard or mouse)
Hope i have helped
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61851868",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Facebook Ads Api Getting Leadgen Form Values How can i get LeadgenForm values with in time range.
LeadgenForm form = new LeadgenForm(FormID);
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("date_preset", "today");
object x = form.GetLeads(null, parameters);
I 'am using Facebook Ads API SDK for C-sharp but
i cannot find correct parameter name for getting today's form values.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49152356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits