text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: How to use custom highlight in Jupyterlab extension? I am building a server extension for Jupiter Lab. I am using cookie-cutter template as an entry point for my extension.
I want to override the default highlighting for .ipynb files and highlight only some custom words.
How can I achieve this?
I am using typescript & python for developing my extension.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71915950",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: While executing the "yarn start" command "error Command failed with exit code 1." I tried the command yarn start for my react project
I am getting this error
yarn run v1.22.10
warning ..\..\package.json: No license field
$ react-scripts start
internal/modules/cjs/loader.js:583
throw err;
^
Error: Cannot find module '@babel/code-frame'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
at Function.Module._load (internal/modules/cjs/loader.js:507:25)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object.<anonymous> (D:\2021\Procare_UI\node_modules\react-dev-utils\typescriptFormatter.js:11:19)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
How can I resolve this issue?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67900134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: AndroidRuntime: FATAL EXCEPTION, java.lang.OutOfMemoryError when sending multiple images I am trying to send a lot of images to an API using okHttp3 and retrofit2. I have tried sending the images from one device (5 images at a time) and it worked well. Then I tried sending 5 images from 5 devices at the same time and it worked well, but when I tried to send 30 images from 5 devices, I got the following error:
2020-01-17 14:57:07.416 32244-32264/my.example.com.puri W/zygote: Throwing OutOfMemoryError "Failed to allocate a 102554120 byte allocation with 8388608 free bytes and 97MB until OOM, max allowed footprint 174912000, growth limit 268435456"
2020-01-17 14:57:07.422 32244-32264/my.example.com.puri E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
Process: my.example.com.puri, PID: 32244
java.lang.OutOfMemoryError: Failed to allocate a 102554120 byte allocation with 8388608 free bytes and 97MB until OOM, max allowed footprint 174912000, growth limit 268435456
at java.lang.StringFactory.newStringFromBytes(StringFactory.java:178)
at java.lang.StringFactory.newStringFromBytes(StringFactory.java:209)
at okio.Buffer.readString(Buffer.java:620)
at okio.Buffer.readString(Buffer.java:603)
at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java:198)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:185)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:135)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
This error does not come on the first device that sends request, rather it comes to the one that is 3rd or last. The device where I click the send button first always succeeds.
I also made these changes to the Manifest.
<application
android:hardwareAccelerated="false"
android:largeHeap="true"
>
And here is how I make the request.
@Multipart
@POST("installationdocument")
Call<Void> createNewDocument(@Header(AUTH_HEADER) String authorization, @Part ArrayList<MultipartBody.Part> images, @Part("document") RequestBody json);
And:
@Override
public void callRestApi(PuriRestApi restApi, RestApiJobService.ApiRequestor apiRequestor) {
MediaType JSON = MediaType.parse("application/json");
MediaType JPG = MediaType.parse("image/jpg");
ArrayList<MultipartBody.Part> imageParts = new ArrayList<>();
for (String imagePath : imagePaths) {
File image = new File(imagePath);
RequestBody imageBody = RequestBody.create(JPG, image);
imageParts.add(MultipartBody.Part.createFormData("images", image.getName(), imageBody));
}
RequestBody jsonPart = RequestBody.create(JSON, documentString);
apiRequestor.request(restApi.createNewDocument(authentication, imageParts, jsonPart), response -> {
if (response.isSuccessful()) {
if (imagePaths != null && imagePaths.length > 0) {
for (String imagePath : imagePaths) {
File image = new File(imagePath);
image.delete();
}
}
return true;
} else {
return false;
}
});
}
Maybe creating a large variable is what throws this error. Because variable ArrayList<MultipartBody.Part> imageParts will contain around 150mb of image data with 30 images. But other than that I have no idea what could be causing this error.
Any kind of help is really appreciated.
A: Unless I've misread that error stack it looks to me like that error is coming from HttpLoggingInterceptor trying to allocate a 102Mb buffer to quite literally log the whole of your Image data.
If so I presume you've set the logging level to BODY, in which case setting it to any other level would fix the problem.
A: Add below entities in your manifest file android:hardwareAccelerated="false" , android:largeHeap="true" it will work for some environment's.
<application
android:allowBackup="true"
android:hardwareAccelerated="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:largeHeap="true"
android:supportsRtl="true"
android:theme="@style/AppTheme">
See the StackOverflow answer for details...
A: You can use compress method before sending images to server
public Bitmap compressInputImage(Uri inputImageData){
try {
bitmapInputImage=MediaStore.Images.Media.getBitmap(context.getContentResolver(), inputImageData);
if (bitmapInputImage.getWidth() > 2048 && bitmapInputImage.getHeight() > 2048)
{
dpBitmap = Bitmap.createScaledBitmap(bitmapInputImage, 1024, 1280, true); }
else if (bitmapInputImage.getWidth() > 2048 && bitmapInputImage.getHeight() < 2048)
{
dpBitmap = Bitmap.createScaledBitmap(bitmapInputImage, 1920, 1200, true); }
else if (bitmapInputImage.getWidth() < 2048 && bitmapInputImage.getHeight() > 2048)
{
dpBitmap = Bitmap.createScaledBitmap(bitmapInputImage, 1024, 1280, true); }
else if (bitmapInputImage.getWidth() < 2048 && bitmapInputImage.getHeight() < 2048)
{
dpBitmap = Bitmap.createScaledBitmap(bitmapInputImage, bitmapInputImage.getWidth(), bitmapInputImage.getHeight(), true); }
} catch (Exception e)
{
dpBitmap = bitmapInputImage;
}
return dpBitmap;
}
It can minimise the chances of OutOfMemory Exception. Besides this you can handle exception
by adding try - catch .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59819558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: VBA wont click gif nested in a tag I am running into an issue with my macro that works on Excel 2013 but will not work on Excel 2010. I am trying to click a gif that is on the webpage but for some reason it does not "see" it.
The HTML I am using is as follows:
<a href="#" style="color:#009900;">
<img src='images/CheckMarkGreen.gif' border=0 alt='Select This Item'>
</a>
And the VBA I am using is:
Dim imgElm
For Each imgElm In objIE.Document.getElementsByTagName("img")
If imgElm.innertext = "images/CheckMarkGreen.gif" Then
imgElm.Click
Exit For
End If
Next
Any help would be appreciated!
A: Image elements don't have an innerText (maybe you mean innerHTML?)
Easier maybe to check the alt attribute:
If imgElm.getAttribute("alt") = "Select This Item" Then
imgElm.Click
Exit For
End If
A: Dim imgElm as IHTMLElement
For Each imgElm In objIE.Document.getElementsByTagName("img")
If imgElm.getAttribute("src") = "images/CheckMarkGreen.gif" Then
imgElm.Click
Exit For
End If
Next
OR
Dim imgElm as HTMLImg
For Each imgElm In objIE.Document.getElementsByTagName("img")
If imgElm.src = "images/CheckMarkGreen.gif" Then
imgElm.Click
Exit For
End If
Next
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41655736",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: WebDAV Server for Cocoa iPhone and iPad running iOS I'm looking for a WebDAV server - best Open Source - for iPhone and iPad for integration in my app. It should be possible to list, download and upload files. I would like to point the server root on the 'Documents' folder of my app, so the methods should be mapped directly to the file system if possible.
On my search through the internet I came around some suggestions, but they did not work for me:
*
*touchcode - the WebDAV server part can be found unter 'Experimental' and I was not able to get it running. Maybe someone has a working release of it?
*iSharing - this seemed to be a commercial solution which now has been dropped by the developer. I was not able to find more info about it.
*CocoaHTTPServer - an Apple sample project of a simple HTTP Server. Apple employees themselves write non their support list that this would be a good starting point, though I was not able to find a WebDAV addition for it. Maybe there is one?
So that's what I was able to find so far. Hint would be very appreciated. Thanks.
A: Try https://github.com/swisspol/GCDWebServer#webdav-server-in-ios-apps it seems to be doing well and active.
A: Try combining the DynamicServer and iPhoneHTTPServer projects in CocoaHTTPServer. Use NSFileManager to get the file contents. You have to use a web browser...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3567763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Why does Celery work in Python shell, but not in my Django views? (import problem) I installed Celery (latest stable version.)
I have a directory called /home/myuser/fable/jobs. Inside this directory, I have a file called tasks.py:
from celery.decorators import task
from celery.task import Task
class Submitter(Task):
def run(self, post, **kwargs):
return "Yes, it works!!!!!!"
Inside this directory, I also have a file called celeryconfig.py:
BROKER_HOST = "localhost"
BROKER_PORT = 5672
BROKER_USER = "abc"
BROKER_PASSWORD = "xyz"
BROKER_VHOST = "fablemq"
CELERY_RESULT_BACKEND = "amqp"
CELERY_IMPORTS = ("tasks", )
In my /etc/profile, I have these set as my PYTHONPATH:
*
*PYTHONPATH=/home/myuser/fable:/home/myuser/fable/jobs
So I run my Celery worker using the console ($ celeryd --loglevel=INFO), and I try it out.
I open the Python console and import the tasks. Then, I run the Submitter.
>>> import fable.jobs.tasks as tasks
>>> s = tasks.Submitter()
>>> s.delay("abc")
<AsyncResult: d70d9732-fb07-4cca-82be-d7912124a987>
Everything works, as you can see in my console
[2011-01-09 17:30:05,766: INFO/MainProcess] Task tasks.Submitter[d70d9732-fb07-4cca-82be-d7912124a987] succeeded in 0.0398268699646s:
But when I go into my Django's views.py and run the exact 3 lines of code as above, I get this:
[2011-01-09 17:25:20,298: ERROR/MainProcess] Unknown task ignored: "Task of kind 'fable.jobs.tasks.Submitter' is not registered, please make sure it's imported.": {'retries': 0, 'task': 'fable.jobs.tasks.Submitter', 'args': ('abc',), 'expires': None, 'eta': None, 'kwargs': {}, 'id': 'eb5c65b4-f352-45c6-96f1-05d3a5329d53'}
Traceback (most recent call last):
File "/home/myuser/mysite-env/lib/python2.6/site-packages/celery/worker/listener.py", line 321, in receive_message
eventer=self.event_dispatcher)
File "/home/myuser/mysite-env/lib/python2.6/site-packages/celery/worker/job.py", line 299, in from_message
eta=eta, expires=expires)
File "/home/myuser/mysite-env/lib/python2.6/site-packages/celery/worker/job.py", line 243, in __init__
self.task = tasks[self.task_name]
File "/home/myuser/mysite-env/lib/python2.6/site-packages/celery/registry.py", line 63, in __getitem__
raise self.NotRegistered(str(exc))
NotRegistered: "Task of kind 'fable.jobs.tasks.Submitter' is not registered, please make sure it's imported."
It's weird, because the celeryd client does show that it's registered, when I launch it.
[2011-01-09 17:38:27,446: WARNING/MainProcess]
Configuration ->
. broker -> amqp://GOGOme@localhost:5672/fablemq
. queues ->
. celery -> exchange:celery (direct) binding:celery
. concurrency -> 1
. loader -> celery.loaders.default.Loader
. logfile -> [stderr]@INFO
. events -> OFF
. beat -> OFF
. tasks ->
. tasks.Decayer
. tasks.Submitter
Can someone help?
A: See Automatic Naming and Relative Imports, in the docs:
http://celeryq.org/docs/userguide/tasks.html#automatic-naming-and-relative-imports
The tasks name is "tasks.Submitter" (as listed in the celeryd output),
but you import the task as "fable.jobs.tasks.Submitter"
I guess the best solution here is if the worker also sees it as "fable.jobs.tasks.Submitter",
it makes more sense from an app perspective.
CELERY_IMPORTS = ("fable.jobs.tasks", )
A: This is what I did which finally worked
in Settings.py I added
CELERY_IMPORTS = ("myapp.jobs", )
under myapp folder I created a file called jobs.py
from celery.decorators import task
@task(name="jobs.add")
def add(x, y):
return x * y
Then ran from commandline: python manage.py celeryd -l info
in another shell i ran python manage.py shell, then
>>> from myapp.jobs import add
>>> result = add.delay(4, 4)
>>> result.result
and the i get:
16
The important point is that you have to rerun both command shells when you add a new function. You have to register the name both on the client and and on the server.
:-)
A: I believe your tasks.py file needs to be in a django app (that's registered in settings.py) in order to be imported. Alternatively, you might try importing the tasks from an __init__.py file in your main project or one of the apps.
Also try starting celeryd from manage.py:
$ python manage.py celeryd -E -B -lDEBUG
(-E and -B may or may not be necessary, but that's what I use).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4643065",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Did listeners on panel in Ext JS 5 depends on the panel content? I wan't to detect 'pinch' event on a Extjs 5 Panel, if I load the panel content using loader property it's working, but if I put an item (Iframe) in the panel, it doesn't work
Panel with an item (IFrame):
Ext.create('Ext.panel.Panel', {
layout: 'fit',
autoScroll: true,
items: [
Ext.create('Ext.ux.IFrame', {
autoScroll: true,
src: 'resources/docs/doc1.html',
cls: 'iframeStyle'
})
],
listeners: {
pinch: function (event) {
alert('pinch event');
},
element: 'body'
}
})
Panel that the content was loaded using loader property
Ext.create('Ext.panel.Panel', {
layout: 'fit',
loader: {
url: 'resources/docs/doc1.html',
autoLoad: true
},
listeners: {
pinch: function (event) {
alert('pinch event');
},
element: 'body'
}
})
Can you explain me the difference, and why with an IFrame it doesn't work??
Thank you
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27528897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unable to fix the x-axis labels in ggplot2 facet_wrap geom_histogram plot Maybe I have missed this in the stackexchange literature, as I'm surprised to find many solutions for adding floating axis labels and adjustments to axes (e.g. add "floating" axis labels in facet_wrap plot), but nothing to solve my issue of overlapping x-axis labels with a facet_wrap and scales = "free". This one is close, but for an older ggplot version: overlapping y-scales in facet (scale="free"). This one may be the answer, to write a function to do such an operation, but I couldn't make it work for me: Is there a way of manipulating ggplot scale breaks and labels?
Here is a reproducible example:
v<-runif(1000,min=1000000,max=10000000)
x<-runif(100,min=0.1,max=1)
y<-runif(100000,min=0,max=20000)
z<-runif(100000,min=10000,max=2000000)
df<-data.frame(v,x,y,z)
colnames(df)<-c("Order V","Order X","Order Y","Order z")
library(reshape2)
melt.df<-melt(df[,c(1:4)])
library(ggplot2)
ggplot(melt.df, aes(x = value)) +
geom_histogram(bins=50,na.rm=TRUE) +
facet_wrap(~variable, scales="free") +
theme_bw()
The resulting figure is this:
I have a similar setup, which produces this:
Any help on a cmd to do this, or a function that could set up these x-axis label breaks would be awesome!
A: I figured it out - at least a hacked answer - and will post my solution in case others can use it.
Basically I adjusted the font size of the axis text, and used the scales pkg to keep the notation consistent (i.e. get rid of scientific). My altered code is:
ggplot(melt.df, aes(x = value)) +
geom_histogram(bins=50,na.rm=TRUE) +
facet_wrap(~variable, scales="free") +
theme_bw()+
theme(axis.text=element_text(size=10),text=element_text(size=16))+
scale_x_continuous(labels = scales::comma)
A: If you don't want the commas in the labels, you can set something like
options(scipen = 10)
before plotting. This makes the threshold for using scientific notation higher so ordinary labels will be used in this case.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40685384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Conditional Display of Plots in Shiny I'm trying to create a shiny app that allows user to display the kind of plot they want to show.
I've tried using a simple if else statement for the display of plot, however, it does not seem to work.
Is it because of my reactive function?
library(shiny)
library(ggplot2)
library(shinyjs)
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("File to Plot"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
# Input: Select a file ----
fileInput('file1', 'Choose CSV File',
accept=c('text/csv',
'text/comma-separated-values,text/plain',
'.csv')),
# Horizontal line ----
tags$hr(),
checkboxInput('header', 'Header', TRUE),
radioButtons('sep', 'Separator',
c(Comma=',',
Semicolon=';',
Tab='\t'),
','),
radioButtons('quote', 'Quote',
c(None='',
'Double Quote'='"',
'Single Quote'="'"),
'"'),
#implementing dropdown column
selectInput('xcol', 'X Variable', ""),
selectInput('ycol', 'Y Variable', "", selected = ""),
selectInput('color', 'Colour', "", selected = ""),
tags$hr(),
checkboxGroupInput("my_choices", "Plots to Display",
choices = c("Scatterplot", "CorrMat"), selected = "Scatterplot")
),
# Show a plot of the generated distribution
mainPanel(
# Output: Data file ----
plotOutput('Scatterplot'), #need to add in more plots into the UI
plotOutput('CorrMat')
)
)
)
# Define server logic
server <- function(input, output, session) {
# added "session" because updateSelectInput requires it
data <- reactive({
req(input$file1) ## ?req # require that the input is available
inFile <- input$file1
# tested with a following dataset: write.csv(mtcars, "mtcars.csv")
# and write.csv(iris, "iris.csv")
df <- read.csv(inFile$datapath, header = input$header, sep = input$sep,
quote = input$quote)
updateSelectInput(session, inputId = 'xcol', label = 'X Variable',
choices = names(df), selected = names(df))
updateSelectInput(session, inputId = 'ycol', label = 'Y Variable',
choices = names(df), selected = names(df)[2])
updateSelectInput(session, inputId = 'color', label = 'Colour',
choices = names(df), selected = names(df)[3])
return(df)
})
# hide plots on start
hide("Scatterplot");hide("CorrMat")
output$Scatterplot <- renderPlot({
ggplot(data = data(), aes_string(x = input$xcol, y = input$ycol, colour = input$color)) +
geom_point() +
theme_bw()
})
output$CorrMat <- renderPlot({
ggplot(data = data(), aes_string(x = input$xcol, y = input$ycol, colour = input$color)) +
geom_point() +
theme_bw()
})
observeEvent(input$my_choices,{
if(is.null(input$my_choices)){
hide("Scatterplot"); hide("CorrMat")
}
else if(length(input$my_choices) == 1){
if(input$my_choices == "Scatterplot"){
show("Scatterplot");hide("CorrMat")
}
if(input$my_choices == "CorrMat"){
hide("Scatterplot");show("CorrMat")
}
}
else{
if(all(c("Scatterplot","CorrMat") %in% input$my_choices)){
show("Scatterplot");show("CorrMat")
}
}
},ignoreNULL = F)
}
shinyApp(ui, server)
The code above is reproducible with any .csv file. Thank you so much!
A: Your code is sound. You just need to include this in the beginning of your ui:
ui <- fluidPage(
useShinyjs(), # add this
# rest of your ui code
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52492974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Run application in background when phone in Doze Application is running SDK 23 and above. I am running some tasks using Service after completing the task and scheduling the next task using AlaramManager (setExactAndAllowWhileIdle). This is working fine. If the phone is idle continuously for 2 or 3 days then its going to Doze mode. After Doze mode ,application loosing the network and wakelock also not working.
Is there way even if phone is Doze can we run the application with any network interposition issues.I tried to keep the application witelist but i needs device to be rooted.
adb shell dumpsys deviceidle whitelist +<Package Name>
Can anyone suggest me which best way to run application without interruption?
A: Actually there is no way of doing this without running a foreground service. Having listed in white list may not be appropriate for your application and even though it is, you ask user to give you permission which can be seen as something dangerous from the end user's point of view.
However, I have a trick about this. Listen android's broadcasts and when you catch that device will move into doze mode, start a foreground service. In most of the cases user won't be able to see your foreground notification image and won't know that you are running a service. Because device is in the doze mode meaning it is stable in somewhere user not watching. So you can do whatever is needed.
You also listen broadcasts sent when doze mode is finished. When that happens, stop your foreground service and work in a normal logic of yours with alarm managers.
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(intent.getAction().equals("android.os.action.DEVICE_IDLE_MODE_CHANGED")){
if (pm.isDeviceIdleMode()) {
startForegroundService();
//stopAlarmManagerLogic();
} else {
stopForegroundService();
//startAlarmManagerLogic();
return;
}
return;
}
}
A: You can request android to whitelist your app for doze mode by sending a high pirority GCM message. But remember this might make your app not approved by Google Play:
Intent intent = new Intent();
String packageName = context.getPackageName();
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (pm.isIgnoringBatteryOptimizations(packageName))
intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
else {
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + packageName));
}
context.startActivity(intent);
https://developer.android.com/training/monitoring-device-state/doze-standby.html#whitelisting-cases
A: Edit-WakefulBroadcastReceiver is now deprecated
Firstly, instead of directly calling a service in the AlarmManager call a broadcast receiver which then calls the service.
The broadcast receiver should extend a WakefulBroadcastReceiver instead of a regular BroadcastReceiver.
And then, let the broadcast receiver schedule a new Alarm, start the service using startWakefulService() instead of startService()
public class MyAwesomeReceiver extends WakefulBroadcastReceiver {
int interval=2*60*60*1000;
@Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent(context, MyAwesomeService.class);
Intent receiverIntent = new Intent(context, MyAwesomeReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 11, receiverIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+interval,alarmIntent);
startWakefulService(context, serviceIntent);
}
}
The WakefulBroadcastReceiver and startWakefulService() will let your app a 10 seconds window to let do what it needs to do.
Also,
You can always ask the user to let your app ignore battery optimization functionality using-
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
Intent intent=new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
if (powerManager.isIgnoringBatteryOptimizations(getPackageName())) {
intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
}
else {
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivity(intent);
}
and in the manifest
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"></uses-permission>
A: After Android N, no app can run in background forever. However you can use Firebase Job Dispatcher which can help you to run your app even if it is in doze mode. With the help of Firebase Job Dispatcher you can tell the system that your app should run at a particular time if provided conditions are matched.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43508748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Managing media using the Android MediaStore I manage media (images, sound) of my app directly, reading and saving to the SD card. Should I be using the MediaStore instead? I'm not quite sure what the MediaStore is for, and the javadoc is not very helpful.
When should an app use the MediaStore? A brief overview of the pros and cons of the MediaStore will be much appreciated.
A: As an avid android user.
I think MediaStore is the "Public Link" between the internal Android Media Scanner Application (You can manually invoke it through Spare Parts) and 3rd party applications, like yours.
I'm guessing MediaStore is this "public link" based on its android.provider packaging.
As providers in android, is how applications provide information to other applications
If MediaStore is a ContentProvider, reading information populated by MediaScanner.
Then MediaStore is for User media, such as music, video, pictures etc.
For ringtones, notifications; I think you are supposed to use android.media.RingtoneManager
Also don't hardcode the path "/sdcard/" There is an api call to get it, Environment.getExternalStorageDirectory()
http://twitter.com/cyanogen/status/13980762583
====
The pro is that Media Scanner runs every time you mount the removable storage to the phone, and it also scans the internal memory (if it has any like the HTC EVO & incredible)
A: I am no expert in this but as far as my common sense goes, well its the easy way to search for certain types of files.
If your app has a library of sorts, then using MediaStore instead of searching all by yourself is more useful, faster and less power consuming. Also you can be assured that those are all the files present in the system.
I hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2751958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: why pytorch linear model isn't using sigmoid function I'm expecting that the linear model in pytorch yields sigmoid(WX+b). But I see it is only returning Wx+b. Why is this the case?
In Udacity "Intro to deep learning with pytorch" -> Lesson 2: Introduction to Neural Networks, They say that the output is sigmoid:
̂ =(11+22+)
From the below code I was expecting y cap to be 0.38391371665752183, but it is just the value of WX+b, which I confirmed the output. Why is this discrepancy?
import torch
from torch import nn
import numpy as np
torch.manual_seed(0)
model = nn.Linear(2,1)
w1 = model.weight.detach().numpy()
b1 = model.bias.detach().numpy()
print (f'model.weight = {w1}, model.bias={b1}')
x = torch.tensor([[0.2877, 0.2914]])
print(f'model predicted {model(x)}')
z = x.numpy()[0][0] * w1[0][0] + x.numpy()[0][1] * w1 [0][1] + b1[0]
print(f'manual multiplication yielded {z}')
ycap = 1/(1+ np.exp(-z))
print(f'y cap is {ycap}')
Output:
model.weight = [[-0.00529398 0.3793229 ]], model.bias=[-0.58198076]
model predicted tensor([[-0.4730]], grad_fn=<AddmmBackward>)
manual multiplication yielded -0.4729691743850708
y cap is 0.38391371665752183
A: The nn.Linear layer is a linear fully connected layer. It corresponds to wX+b, not sigmoid(WX+b).
As the name implies, it's a linear function. You can see it as a matrix multiplication (with or without a bias). Therefore it does not have an activation function (i.e. nonlinearities) attached.
If you want to append an activation function to it, you can do so by defining a sequential model:
model = nn.Sequential(
nn.Linear(2, 1)
nn.Sigmoid()
)
Edit - if you want to make sure:
x = torch.tensor([[0.2877, 0.2914]])
model = nn.Linear(2,1)
m1 = nn.Sequential(model, nn.Sigmoid())
m1(x)[0].item(), torch.sigmoid(model(x))[0].item()
A: Not surprisingly, PyTorch implements Linear as a linear function.
Why the sigmoid is not included?
*
*well, in that case it'd be weird to call the resultant module Linear, since the purpose of the sigmoid is to "break" the linearity: the sigmoid is a non-linear function;
*having a separate Linear module makes it possible to combine Linear with many activation functions other than the sigmoid, like the ReLU.
If the course says that a sigmoid is included in a "linear layer", that's a mistake (and I'd suggest you to change course). Maybe you're mistaking a linear layer for a "fully-connected layer". In practice, a fully-connected layer is made of a linear layer followed by a (non-linear) activation layer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65451589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Custom toast for application I need to create custom Toast like component. This should appears over only my application to show some message.
Why i don't use android Toast - because i need custom duration.
Problem is I'm creating view through WindowManager.addView with type WindowManager.LayoutParams.TYPE_APPLICATION
But it works only over 1 Activity, when i close it, toast disappears.
But I have a lot of places - where i open an activity to do some task, and after success result i should immediately show toast and close this Activity.
I need to keep toast over all my activities, but not over android system. And i don't want to use TYPE_SYSTEM_ALERT because it's require additional permission
Is there some method to sure do that? Use of WindowManager is not required.
A: try it methood Custom Toast
public static void Toast(String textmessage) {
LinearLayout layout = new LinearLayout(getContext());
layout.setBackgroundResource(R.drawable.shape_toast);
layout.setPadding(30, 30, 30, 30);
TextView tv = new TextView(getContext());
tv.setTextColor(Color.WHITE);
tv.setTextSize(12);
tv.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/font.ttf"));
tv.setGravity(Gravity.CENTER);
tv.setText(textmessage);
layout.addView(tv);
Toast toast = new Toast(getContext());
toast.setView(layout);
toast.setGravity(Gravity.BOTTOM, 0, 240);
toast.show();
}
you can try it methood Toast with duration
public class ToastExpander {
public static final String TAG = "ToastExpander";
public static void showFor(final Toast aToast, final long durationInMilliseconds) {
aToast.setDuration(Toast.LENGTH_SHORT);
Thread t = new Thread() {
long timeElapsed = 0l;
public void run() {
try {
while (timeElapsed <= durationInMilliseconds) {
long start = System.currentTimeMillis();
aToast.show();
sleep(1750);
timeElapsed += System.currentTimeMillis() - start;
}
} catch (InterruptedException e) {
Log.e(TAG, e.toString());
}
}
};
t.start();
}
}
and for show toast use this
Toast aToast = Toast.makeText(this, "Hello World", Toast.LENGTH_SHORT);
ToastExpander.showFor(aToast, 5000);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57036180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: Displaying a modal instead of a echo message if (mysqli_num_rows($res_username) > 0) {
//echo "Sorry... Username already taken";
echo "<script>$('#RegisterModal').modal('show')</script>";
}
<div id="RegisterModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
You have sucess registered!
</div>
</div>
</div>
For the echo part, I want to display a modal showing a popup instead of a echo message.
Anybody help?
A: Enclose your script in $(document).ready() so your show command executes only when the document is fully loaded to limit failure.
Like:
echo "
<script>
$( document ).ready(function() {
$('#RegisterModal').modal('show')
});
</script>";
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50675092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: dpkg-scanpackages -a amd64 . > Packages - Wrote 0 entries with --arch arm64 I am trying to pack(and create a repo on github) using the following, but dpkg-scanpackages is not writing anything when using --arch arm64?
control file:
Package: hello-world
Version: 0.0.1
Maintainer: example <[email protected]>
Depends: git
Architecture: arm64
Homepage: http://example.com
Description: A program that prints hello
Created .deb file and verified with dpkg-deb --contents ./arm64
dpkg-deb -b ./arm64
Wrote 1 entries:
dpkg-scanpackages --multiversion . > Packages
dpkg-scanpackages: info: Wrote 1 entries to output Packages file.
Problem
Wrote 0 entries with --arch arm64:
dpkg-scanpackages --arch amd64 . > Packages
dpkg-scanpackages: info: Wrote 0 entries to output Packages file.
A: Probably foo/ is missing, so try this:
dpkg-scanpackages --arch arm64 pool/ > dists/stable/main/binary-amd64/Packages
A: I had the same problem. Solution form Chris G. works for me: make sure that name of your .deb file contains the architecture like this:
XnViewMP-linux-64_amd64.deb
After this, dpkg-scanpackages work me as expected:
gabor@focal-autoinstall:/var/www/html/repo$ ll pool/main/
total 53664
drwxrwxr-x 2 gabor gabor 4096 May 21 14:54 ./
drwxrwxr-x 3 gabor gabor 4096 May 21 14:46 ../
-rw-rw-r-- 1 gabor gabor 54943400 May 3 13:25 XnViewMP-linux-64_amd64.deb
gabor@focal-autoinstall:/var/www/html/repo$ dpkg-scanpackages --arch amd64 pool/
Package: xnview
Version: 1.00.0
Architecture: amd64
Maintainer: None <[email protected]>
Installed-Size: 16
Depends: libasound2 (>= 1.0.16), libatk1.0-0 (>= 1.12.4), libbz2-1.0, libc6 (>= 2.17), libcairo-gobject2 (>= 1.10.0), libcairo2 (>= 1.2.4), libcups2 (>= 1.4.0), libdbus-1-3 (>= 1.9.14), libdrm2 (>= 2.4.30), libegl1-mesa | libegl1, libfontconfig1 (>= 2.11), libfreetype6 (>= 2.3.5), libgcc1 (>= 1:3.4), libgdk-pixbuf2.0-0 (>= 2.22.0), libgl1-mesa-glx | libgl1, libglib2.0-0 (>= 2.33.14), libgstreamer-plugins-base1.0-0 (>= 1.0.0), libgstreamer1.0-0 (>= 1.4.0), libgtk-3-0 (>= 3.5.18), libopenal1 (>= 1.14), libpango-1.0-0 (>= 1.14.0), libpangocairo-1.0-0 (>= 1.14.0), libpulse-mainloop-glib0 (>= 0.99.1), libpulse0 (>= 0.99.4), libsqlite3-0 (>= 3.5.9), libstdc++6 (>= 5), libx11-6 (>= 2:1.4.99.1), libx11-xcb1, libxcb-shm0, libxcb1 (>= 1.8), libxcb-xinerama0, libxext6, libxfixes3, libxi6 (>= 2:1.5.99.2), libxv1, zlib1g (>= 1:1.2.3.4), libopenal1
Filename: pool/main/XnViewMP-linux-64_amd64.deb
Size: 54943400
MD5sum: cf5aea700b14b50fe657c406f6f84894
SHA1: a27d7a0d17dc11825666c9175b974f51f5e7d69f
SHA256: 6f409eb6d890a827bd382b38a8a9e89eacbad6eb2b5edba01265bd20f2ed3655
Section: graphics
Priority: optional
Homepage: http://www.xnview.com
Description: Graphic viewer, browser, converter.
dpkg-scanpackages: info: Wrote 1 entries to output Packages file.
gabor@focal-autoinstall:/var/www/html/repo$
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68577036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Deserializing Collections with protobuf-net During my switch from BinaryFormatter to protobuf-net,
I observed a difference when serializing collections.
In the code sample below, Deserialize (protobuf-net v2r470) returns
different results if an array is instantiated within
the class (street1) than outside (street2).
Is it not allowed to serialize collections instatiated within a class declaration?
[ProtoContract]
public class City
{
[ProtoMember(1)]
public string[] streets1;
[ProtoMember(2)]
public string[] streets2 = new string[2];
}
City city = new City();
// Instantiate and populate streets1
city.streets1 = new string[2];
city.streets1[0] = "streetA";
city.streets1[1] = "streetB";
// Populate streets2. Already instantiated
city.streets2[0] = "streetA";
city.streets2[1] = "streetB";
// Serializing
using (var file = File.Create("city.bin"))
{
Serializer.Serialize(file, city);
}
// Deserializing
using (var file = File.OpenRead("city.bin"))
{
City getCity = Serializer.Deserialize<City>(file);
}
Deserialize loads the following in getCity:
getCity.streets1: "streetA", "streetB" (as expected)
getCity.streets2: null, null, "streetA", "streetB" <--------- Why the null's ?
There are as many null's returned as there are items in the collection.
A: It is, but the problem is that protobuf-net assumes (due to the concatenatable nature of the protobuf format) that it should extend (append to) lists/arrays, and your field-initializer is starting it at length 2.
There are at least 3 fixes here:
*
*you can add SkipConstructor=true to the ProtoContract, which will mean it doesn't run the field initializer
*there is a "replace lists" syntax on ProtoMember which tells it to replace rather than append (I can't remember the actual option, but it is there)
*you can add a before-deserialization callback to clear the field between the constructor and the deserialization
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8285566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Application not appearing after launching from visual studio I have a strange problem, which i have never seen before , i have a wpf application and i am using prism for mvvm and sqlserverCe 4 for database, today i uninstalled sqlserverCe and prism packages from the executable project and re installed them back, now when i launch the application from visual studio 2012/13 the application is not appearing on the screen. the build output window shows the following.
Step into: Stepping over non-user code 'XamlGeneratedNamespace.GeneratedApplication.Main'
Step into: Stepping over non-user code 'XamlGeneratedNamespace.GeneratedApplication.InitializeComponent'
'NewPos.Main.vshost.exe' (CLR v4.0.30319: NewPos.Main.vshost.exe): Loaded 'F:\Practise\NewPos\NewPos.Main\bin\Debug\NewPos.MenuModule.dll'. Symbols loaded.
The thread 0x138c has exited with code 259 (0x103).
The thread 0x2d4 has exited with code 0 (0x0).
The thread 0x118c has exited with code 0 (0x0).
Double clicking the application icon directly also does nothing. I am scratching my head and wondering what has gone wrong with it
Things that i did before the application seized to appear
*
*uninstall and re install prism package because service locator package was referencing .net45 and i changed the target framework to .net4 on the project.
*uninstall and re install the sqlserverCE package becasuse of the same above reason.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26996911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why is vim turning map into strange character ï I have the following map command in my ~/.vimrc that I've used for years:
map <M-o> :split<Space>
It works well when I use it in OS X, Ubuntu, even when running Ubuntu in a Parallels Desktop VM. However, I just installed a fresh Ubuntu 14.04.2 on a VM using Parallels on my mac OS X Yosemite. When I copied the same .vimrc to the VM, when I run vim or gvim, pressing M-o doesn't work at all.
If I type :map inside vim running in the VM I see the following:
ï :split<Space>
If I do it inside, say, MacVim or just vim on my Mac or any other OS where it does work I see the following:
<M-o> :split<Space>
Why is <M-o> being turned into ï? What gives, I tried setting:
set encoding=utf-8
in my .vimrc but it doesn't help.
Any ideas?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31096474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ABAP equality check is wrong for INT4 and CHAR numeric I've ran into an issue here, and I can't figure out exactly what SAP is doing. The test is quite simple, I have two variables that are a completely different type as well as having two completely different values.
The input is an INT4 of value 23579235. I am testing the equality function against a string '23579235.43'. Obviously my expectation is that these two variables are different because not only are they not the same type of variable, but they don't have the same value. Nothing about them is similar, actually.
EXPECTED1 23579235.43 C(11) \TYPE=%_T00006S00000000O0000000302
INDEX1 23579235 I(4) \TYPE=INT4
However, cl_abap_unit_assert=>assert_equals returns that these two values are identical. I started debugging and noticed the 'EQ' statement was used to check the values, and running the same statement in a simple ABAP also returns 'true' for this comparison.
What is happening here, and why doesn't the check fail immediately after noticing that the two data types aren't even the same? Is this a mistake on my part, or are these assert classes just incorrect?
report ztest.
if ( '23579235.43' eq 23579235 ).
write: / 'This shouldn''t be shown'.
endif.
A: As @dirk said, ABAP implicitly converts compared or assigned variables/literals if they have different types.
First, ABAP decides that the C-type literal is to be converted into type I so that it can be compared to the other I literal, and not the opposite because there's this priority rule when you compare types C and I : https://help.sap.com/http.svc/rc/abapdocu_752_index_htm/7.52/en-US/abenlogexp_numeric.htm#@@ITOC@@ABENLOGEXP_NUMERIC_2
| decfloat16, decfloat34 | f | p | int8 | i, s, b |
.--------------|------------------------|---|---|------|---------|
| string, c, n | decfloat34 | f | p | int8 | i |
(intersection of "c" and "i" -> bottom rightmost "i")
Then, ABAP converts the C-type variable into I type for doing the comparison, using the adequate rules given at https://help.sap.com/http.svc/rc/abapdocu_752_index_htm/7.52/en-US/abenconversion_type_c.htm#@@ITOC@@ABENCONVERSION_TYPE_C_1 :
Source Field Type c -> Numeric Target Fields -> Target :
"The source field must contain a number in mathematical or
commercial notation. [...] Decimal places are rounded commercially
to integer values. [...]"
Workarounds so that 23579235.43 is not implicitly rounded to 23579235 and so the comparison will work as expected :
*
*either IF +'23579235.43' = 23579235. (the + makes it an expression i.e. it corresponds to 0 + '23579235.43' which becomes a big Packed type with decimals, because of another rule named "calculation type")
*or IF conv decfloat16( '23579235.43' ) = 23579235. (decfloats 16 and 34 are big numbers with decimals)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51875875",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Angular ignores the iframe element I've found Angular 15 to be ignoring the iframe element. I've found the following existing example on stackblitz that is not working either. In both cases I've found the iframe element to be simply missing from the dom.
https://stackblitz.com/edit/angular-iframe-src?file=src/app/app.component.html
Is this a bug in Angular? Or both me and the example are missing something?
A: The pages you are trying to frame forbid being framed and throw a "Refused to display document because display forbidden by X-Frame-Options." error in Chrome.
If they're your pages, then remove the frame limiter. Otherwise, respect the page's author's wishes and DON'T FRAME THEM.
Working StackBlitz
Reference
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74710692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In consistent results returned with white space in query Using NEST.
I have the following code.
QueryContainerDescriptor<ProductIndex> q
var queryContainer = new QueryContainer();
queryContainer &= q.Match(m => m.Field(f => f.Code).Query(parameters.Code));
I would like to have both these criteria
code=FRUIT 12 //with space
code=FRUIT12 //no space
Return products 1 and 2
Currently
I get products 1 and 2 if I set code=FRUIT 12 //with space
and I only get product 2 if I set code=FRUIT12 //no space
Sample data
Products
[
{
"id": 1,
"name": "APPLE",
"code": "FRUIT 12"
},
{
"id": 2,
"name": "ORANGE",
"code": "FRUIT12"
}
]
A: by default, a string field will have a standard tokenizer, that will emit a single token "FRUIT12" for the "FRUIT12" input.
You need to use a word_delimiter token filter in your field analyzer to allow the behavior your are expecting :
GET _analyze
{
"text": "FRUIT12",
"tokenizer": "standard"
}
gives
{
"tokens": [
{
"token": "FRUIT12",
"start_offset": 0,
"end_offset": 7,
"type": "<ALPHANUM>",
"position": 0
}
]
}
----------- and
GET _analyze
{
"text": "FRUIT12",
"tokenizer": "standard",
"filters": ["word_delimiter"]
}
gives
{
"tokens": [
{
"token": "FRUIT",
"start_offset": 0,
"end_offset": 5,
"type": "<ALPHANUM>",
"position": 0
},
{
"token": "12",
"start_offset": 5,
"end_offset": 7,
"type": "<ALPHANUM>",
"position": 1
}
]
}
If your add the word_delimiter token filter on your field, any search query on this field will also have the word_delimiter token filter enabled ( unless you override it with search_analyzer option in the mapping )
so "FRUIT12" mono-term query will be "translated" to ["FRUIT", "12"] multi term query.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52088489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Create nested array in custom soap webservice mirth I'm creating a custom webservice to host in Mirth. I wanted to create nested Array inside this SOAP structure. There may be other ways of creating SOAP, but I'm following this way so that other external JARS need not be used. Currently this is the class I'm doing my getter and setter
public class ResultSpecification {
private String AccessionNumber;
private String AddtionalPatientHistory;
private long FacilityCode;
private String[] Code;
private String[] Description;
public String getAccessionNumber() {
return AccessionNumber;
}
public void setAccessionNumber(String AccessionNumber) {
this.AccessionNumber = AccessionNumber;
}
public String getAddtionalPatientHistory() {
return AddtionalPatientHistory;
}
public void setAddtionalPatientHistory(String AddtionalPatientHistory) {
this.AddtionalPatientHistory = AddtionalPatientHistory;
}
public long getFacilityCode() {
return FacilityCode;
}
public void setFacilityCode(long FacilityCode) {
this.FacilityCode = FacilityCode;
}
public String[] getCode() {
return Code;
}
public void setCode(String[] Code) {
this.Code = Code;
}
public String[] getDescription() {
return Description;
}
public void setDescription(String[] Description) {
this.Description = Description;
}
@Override
public String toString() {
String codeInString = Arrays.toString(Code);
String descriptionInString = Arrays.toString(Description);
return "{\"reportDetails\": {\"AccessionNumber\":" + "\"" + AccessionNumber + "\""
+ ", \"AddtionalPatientHistory\":" + "\"" + AddtionalPatientHistory.replaceAll("\"", "\\\\\"") + "\""
+ ", \"FacilityCode\":" + "\"" + FacilityCode + "\"" +"},\"Hl7Message\":[{\"Code\":" + "\"" + codeInString + "\"" + ", \"Description\":" + "\""
+ descriptionInString + "\"}]}";
}
}
I called this as an Array inside the Webreceiver calling class.That will be the class which I will call inside Mirth and I have provide super.webServiceReceiver.processData(String.valueOf(str)); within that class.
With the current state I'm getting the below SOAP message.
<ray:data>
<!--Zero or more repetitions:-->
<TestResult>
<!--Optional:-->
<accessionNumber></accessionNumber>
<!--Optional:-->
<addtionalPatientHistory></addtionalPatientHistory>
<!--Zero or more repetitions:-->
<code></code>
<!--Zero or more repetitions:-->
<description></description>
</TestResult>
</ray:data>
But I'm expecting the SOAP structure in the below format where the tags code and will be enclosed inside an array by other XML tags.I'm not sure how to construct that in my getter setter class. When I use annotations like @XmlElement it is throwing error inside mirth.
<Statuses>
<!--Zero or more repetitions:-->
<MessageStatus>
<!--Optional:-->
<Code />
<!--Optional:-->
<Description />
</MessageStatus>
</Statuses>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50140380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ViewGroup.java AddViewInner issue i keep getting following errors, it's basically same error but keeps occuring on different lines
Fatal Exception: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:3883)
Fatal Exception: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:4312)
Fatal Exception: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:4310)
Things i have tried :-
*
*while adding any fragment i add this code in onCreateView
((ViewGroup) view.getParent()).removeView(view);
view = inflater.inflate(R.layout.create_carpool_layout, container, false);
return view;
and then inflate the view
*While inflating layouts / views in adapter also i make sure the view is removed from parent view
I am not sure what is causing this problem
A: Try double checking how you are inflating the view.
There are two possible ways:
*
*Passing the parent to the inflater:
LayoutInflater.from(context).inflate(R.layout.layout, this, true);
*Keep the view without the parent:
LayoutInflater.from(context).inflate(R.layout.layout, null);
When using the first method, you cannot call addView() with the view as parameter.
Using the second way, the view is not pinned to parent, therefore you can invoke addView()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39641951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Google analytic shows me wired links for one of my visitors I have a website wich is registered with google analytic so I can see the statistics of it The problem is that sometime it shows me this link :
website.com/www.bndv521.cf/
or:
website.com/admin
I do not know if this is a hacker trying to hack me or something but I think nobody will try to access my admin for good
Can you help me to know what is this link refers to ?
A: Consider checking for a malicious code included on your pages. And yes it's likely that some one is trying to access those pages but it may not execute because it's invalid path. You should consider blocking such ip addresses after checking in logs.
A: Although trying to reach an admin page seems a suspicious action, in our website we come accross this issue every one in ten thousand requests.
We think that a browser extension or a virus like program tries to change URL or trying to add this keyword to URL. Not for a hacking purpose, but to redirect to their advertisement website.
Very similar issue here: Weird characters in URL
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23363226",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Could not find class referenced from Google Play Services Util I've added Google Analytics to my Android Project and followed all of the instructions, but still I'm getting this 2 error messages inside LogCat:
E/dalvikvm: Could not find class 'android.os.UserManager', referenced from method com.google.android.gms.common.GooglePlayServicesUtil.zzah
W/dalvikvm: VFY: unable to resolve check-cast 276 (Landroid/os/UserManager;) in Lcom/google/android/gms/common/GooglePlayServicesUtil;
E/dalvikvm: Could not find class 'android.app.AppOpsManager', referenced from method com.google.android.gms.common.GooglePlayServicesUtil.zzb
W/dalvikvm: VFY: unable to resolve check-cast 25 (Landroid/app/AppOpsManager;) in Lcom/google/android/gms/common/GooglePlayServicesUtil;
This doesn't actually crash the application, but it would be great to know why this is happening.
Android Manifest (obfuscated):
<?xml version="1.0" encoding="utf-8"?>
<manifest
package="com.example.android"
xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:allowBackup="true"
android:allowClearUserData="true"
android:allowTaskReparenting="true"
android:fullBackupContent="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:restoreAnyVersion="true"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version"/>
<receiver
android:name="com.google.android.gms.analytics.AnalyticsReceiver"
android:enabled="true">
<intent-filter>
<action android:name="com.google.android.gms.analytics.ANALYTICS_DISPATCH"/>
</intent-filter>
</receiver>
<receiver
android:name="com.google.android.gms.analytics.CampaignTrackingReceiver"
android:exported="true">
<intent-filter>
<action android:name="com.android.vending.INSTALL_REFERRER"/>
</intent-filter>
</receiver>
<service
android:name="com.google.android.gms.analytics.AnalyticsService"
android:enabled="true"
android:exported="false"/>
<service android:name="com.google.android.gms.analytics.CampaignTrackingService"/>
</application>
</manifest>
Does anyone of you know about this errors?
Gradle (shortened):
classpath 'com.android.tools.build:gradle:1.4.0-beta3'
classpath 'com.google.gms:google-services:1.4.0-beta3'
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.google.android.gms:play-services-analytics:8.1.0'
A: Refering to Koh
"UserManager requires API level 17 while AppOpsManager requires API level 19. [...] Otherwise, this could be a multidex issue such as here."
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32909970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is it possible to share my page into specific group or page in facebook Laravel I have facing a problem in my project. Suppose I have 3 groups of in my facebook account. I want to share my blog post or page into specific group. Is it possible? I am using laravel for this. Please help me.
After googling I only find to share post in facebook using this
<script type="text/javascript">
$(document).ready(function () {
$(".modal_share .shareNow").click(function () {
var shareUrl = $.trim($(this).attr("data-url")).replace(/(\r\n|\n|\r)/gm, "");
window.open(shareUrl, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400");
});
});
</script>
But this is for my facebook wall. Also all controls manage by facebook in here I can choose the group, message to share my bolg. But the control and functionality is done facebook. I only called. But is it possible to share it specific group or page in facebook.
A: If you can implement Facebook Graph API to login to your Facebook App in Laravel then you can post to Facebook Groups that you manage.
You can obtain Facebook Group IDs that you manage using the following Facebook Graph API(See Reading):
https://developers.facebook.com/docs/graph-api/reference/user/groups/
Once you have Facebook Group IDs that you manage, you can post on your groups by using the following Facebook Graph API (See Publishing):
https://developers.facebook.com/docs/graph-api/reference/v3.1/group/feed
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51645713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to align the sibling values under the child values as per child to parent?
var app = angular.module('app', ['ngAnimate', 'ngTouch', 'ui.grid', 'ui.grid.treeView' ]);
app.controller('MainCtrl', ['$scope', '$http', '$interval', 'uiGridTreeViewConstants','uiGridTreeBaseService',function ($scope, $http, $interval, uiGridTreeViewConstants,uiGridTreeBaseService ) {
$scope.gridOptions = {
enableSorting: false,
enableFiltering: false,
showTreeExpandNoChildren: true,
showTreeRowHeader: false,
enableColumnMenus : false,
rowHeight: 50,
enableHorizontalScrollbar: 0,
enableVerticalScrollbar: 0,
columnDefs: [
{ name: 'name', width: '30%' , cellTemplate : "<div class=\"ui-grid-cell-contents\" title=\"TOOLTIP\"><div style=\"float:left;\" class=\"ui-grid-tree-base-row-header-buttons\" ng-class=\"{'ui-grid-tree-base-header': row.treeLevel > -1 }\" ng-click=\"grid.appScope.toggleRow(row,evt)\"><i ng-class=\"{'ui-grid-icon-minus-squared': ( ( grid.options.showTreeExpandNoChildren && row.treeLevel > -1 ) || ( row.treeNode.children && row.treeNode.children.length > 0 ) ) && row.treeNode.state === 'expanded', 'ui-grid-icon-plus-squared': ( ( grid.options.showTreeExpandNoChildren && row.treeLevel > -1 ) || ( row.treeNode.children && row.treeNode.children.length > 0 ) ) && row.treeNode.state === 'collapsed'}\" ng-style=\"{'padding-left': grid.options.treeIndent * row.treeLevel + 'px'}\"></i> </div>{{COL_FIELD CUSTOM_FILTERS}}</div>" },
{ name: 'gender', width: '20%' },
{ name: 'age', width: '20%' },
{ name: 'company', width: '25%' },
{ name: 'state', width: '35%' },
{ name: 'balance', width: '25%', cellFilter: 'currency' }
],
onRegisterApi: function( gridApi ) {
$scope.gridApi = gridApi;
$scope.gridApi.treeBase.on.rowExpanded($scope, function(row) {
if( row.entity.$$hashKey === $scope.gridOptions.data[50].$$hashKey && !$scope.nodeLoaded ) {
$interval(function() {
$scope.gridOptions.data.splice(51,0,
{name: 'Dynamic 1', gender: 'female', age: 53, company: 'Griddable grids', balance: 38000, $$treeLevel: 1},
{name: 'Dynamic 2', gender: 'male', age: 18, company: 'Griddable grids', balance: 29000, $$treeLevel: 1}
);
$scope.nodeLoaded = true;
}, 2000, 1);
}
});
}
};
$http.get('https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/500_complex.json')
.success(function(data) {
for ( var i = 0; i < data.length; i++ ){
data[i].state = data[i].address.state;
data[i].balance = Number( data[i].balance.slice(1).replace(/,/,'') );
}
data[0].$$treeLevel = 0;
data[1].$$treeLevel = 1;
data[10].$$treeLevel = 1;
data[11].$$treeLevel = 1;
data[20].$$treeLevel = 0;
data[25].$$treeLevel = 1;
data[50].$$treeLevel = 0;
data[51].$$treeLevel = 0;
$scope.gridOptions.data = data;
});
$scope.expandAll = function(){
$scope.gridApi.treeBase.expandAllRows();
};
$scope.collapseAll = function(){
$scope.gridApi.treeBase.collapseAllRows();
};
$scope.toggleRow = function( row,evt ){
uiGridTreeBaseService.toggleRowTreeState($scope.gridApi.grid, row, evt);
//$scope.gridApi.treeBase.toggleRowTreeState($scope.gridApi.grid.renderContainers.body.visibleRowCache[rowNum]);
};
$scope.toggleExpandNoChildren = function(){
$scope.gridOptions.showTreeExpandNoChildren = !$scope.gridOptions.showTreeExpandNoChildren;
$scope.gridApi.grid.refresh();
};
}]);
.grid {
width: 400px;
}
<!doctype html>
<html ng-app="app">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular-touch.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular-animate.js"></script>
<script src="http://ui-grid.info/docs/grunt-scripts/csv.js"></script>
<script src="http://ui-grid.info/docs/grunt-scripts/pdfmake.js"></script>
<script src="http://ui-grid.info/docs/grunt-scripts/vfs_fonts.js"></script>
<script src="http://ui-grid.info/release/ui-grid-unstable.js"></script>
<link rel="stylesheet" href="http://ui-grid.info/release/ui-grid-unstable.css" type="text/css">
<link rel="stylesheet" href="main.css" type="text/css">
</head>
<body>
<div ng-controller="MainCtrl">
<button id="expandAll" type="button" class="btn btn-success" ng-click="expandAll()">Expand All</button>
<button id="collapseAll" type="button" class="btn btn-collapse" ng-click="collapseAll()">collapseAll</button>
<button id="toggleFirstRow" type="button" class="btn btn-success" ng-click="toggleRow(0)">Toggle First Row</button>
<button id="toggleSecondRow" type="button" class="btn btn-success" ng-click="toggleRow(1)">Toggle Second Row</button>
<button id="toggleExpandNoChildren" type="button" class="btn btn-success" ng-click="toggleExpandNoChildren()">Toggle Expand No Children</button>
<br/>
<br/>
<div id="grid1" ui-grid="gridOptions" ui-grid-tree-view class="grid"></div>
</div>
<script src="app.js"></script>
</body>
</html>
Remove extra column of icons from Angular UI-Grid TreeView
As per provided solution above URL it is working fine but in the grid table how to align the sibling values under the child values as per child to parent?
var app = angular.module('app', ['ngAnimate', 'ngTouch', 'ui.grid', 'ui.grid.treeView']);
app.controller('MainCtrl', ['$scope', '$http', '$interval', 'uiGridTreeViewConstants', 'uiGridTreeBaseService',
function($scope, $http, $interval, uiGridTreeViewConstants, uiGridTreeBaseService) {
$scope.gridOptions = {
enableSorting: true,
enableFiltering: true,
showTreeExpandNoChildren: true,
showTreeRowHeader: false,
columnDefs: [{
name: 'name',
width: '30%',
cellTemplate: "<div class=\"ui-grid-cell-contents\" title=\"TOOLTIP\"><div style=\"float:left;\" class=\"ui-grid-tree-base-row-header-buttons\" ng-class=\"{'ui-grid-tree-base-header': row.treeLevel > -1 }\" ng-click=\"grid.appScope.toggleRow(row,evt)\"><i ng-class=\"{'ui-grid-icon-minus-squared': ( ( grid.options.showTreeExpandNoChildren && row.treeLevel > -1 ) || ( row.treeNode.children && row.treeNode.children.length > 0 ) ) && row.treeNode.state === 'expanded', 'ui-grid-icon-plus-squared': ( ( grid.options.showTreeExpandNoChildren && row.treeLevel > -1 ) || ( row.treeNode.children && row.treeNode.children.length > 0 ) ) && row.treeNode.state === 'collapsed'}\" ng-style=\"{'padding-left': grid.options.treeIndent * row.treeLevel + 'px'}\"></i> </div>{{COL_FIELD CUSTOM_FILTERS}}</div>"
}, {
name: 'gender',
width: '20%'
}, {
name: 'age',
width: '20%'
}, {
name: 'company',
width: '25%'
}, {
name: 'state',
width: '35%'
}, {
name: 'balance',
width: '25%',
cellFilter: 'currency'
}],
onRegisterApi: function(gridApi) {
$scope.gridApi = gridApi;
$scope.gridApi.treeBase.on.rowExpanded($scope, function(row) {
if (row.entity.$$hashKey === $scope.gridOptions.data[50].$$hashKey && !$scope.nodeLoaded) {
$interval(function() {
$scope.gridOptions.data.splice(51, 0, {
name: 'Dynamic 1',
gender: 'female',
age: 53,
company: 'Griddable grids',
balance: 38000,
$$treeLevel: 1
}, {
name: 'Dynamic 2',
gender: 'male',
age: 18,
company: 'Griddable grids',
balance: 29000,
$$treeLevel: 1
});
$scope.nodeLoaded = true;
}, 2000, 1);
}
});
}
};
$http.get('https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/500_complex.json')
.success(function(data) {
for (var i = 0; i < data.length; i++) {
data[i].state = data[i].address.state;
data[i].balance = Number(data[i].balance.slice(1).replace(/,/, ''));
}
data[0].$$treeLevel = 0;
data[1].$$treeLevel = 1;
data[10].$$treeLevel = 1;
data[11].$$treeLevel = 1;
data[20].$$treeLevel = 0;
data[25].$$treeLevel = 1;
data[50].$$treeLevel = 0;
data[51].$$treeLevel = 0;
$scope.gridOptions.data = data;
});
$scope.expandAll = function() {
$scope.gridApi.treeBase.expandAllRows();
};
$scope.toggleRow = function(row, evt) {
uiGridTreeBaseService.toggleRowTreeState($scope.gridApi.grid, row, evt);
//$scope.gridApi.treeBase.toggleRowTreeState($scope.gridApi.grid.renderContainers.body.visibleRowCache[rowNum]);
};
$scope.toggleExpandNoChildren = function() {
$scope.gridOptions.showTreeExpandNoChildren = !$scope.gridOptions.showTreeExpandNoChildren;
$scope.gridApi.grid.refresh();
};
}
]);
.grid {
width: 500px;
height: 400px;
}
<!doctype html>
<html ng-app="app">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular-touch.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular-animate.js"></script>
<script src="http://ui-grid.info/docs/grunt-scripts/csv.js"></script>
<script src="http://ui-grid.info/docs/grunt-scripts/pdfmake.js"></script>
<script src="http://ui-grid.info/docs/grunt-scripts/vfs_fonts.js"></script>
<script src="http://ui-grid.info/release/ui-grid-unstable.js"></script>
<link rel="stylesheet" href="http://ui-grid.info/release/ui-grid-unstable.css" type="text/css">
<link rel="stylesheet" href="main.css" type="text/css">
</head>
<body>
<div ng-controller="MainCtrl">
<button id="expandAll" type="button" class="btn btn-success" ng-click="expandAll()">Expand All</button>
<button id="toggleFirstRow" type="button" class="btn btn-success" ng-click="toggleRow(0)">Toggle First Row</button>
<button id="toggleSecondRow" type="button" class="btn btn-success" ng-click="toggleRow(1)">Toggle Second Row</button>
<button id="toggleExpandNoChildren" type="button" class="btn btn-success" ng-click="toggleExpandNoChildren()">Toggle Expand No Children</button>
<div id="grid1" ui-grid="gridOptions" ui-grid-tree-view class="grid"></div>
</div>
<script src="app.js"></script>
</body>
</html>
Plunker Demo
A: Change :
ng-style="{'padding-left': grid.options.treeIndent * row.treeLevel + 'px'}
to :
ng-style="{'padding-left': (grid.options.treeIndent+10) * row.treeLevel + 'px'}
Result
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33721458",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What does just ";" inside an "if" block mean? Why would someone use this?
if(a==1){;}
There no statement, only one semicolon, and it doesn't throw an error.
What purpose does this semicolon serve?
A: As so many have said - it does nothing.
Why is it there? Here is a possibility …
I am fed up with bad coders on my team not checking return values of functions.
So, since we develop in Linux with the GCC compiler, I add __attribute__((warn_unused_result)) to the declaration of all of my typed functions. See also this question for a MS VC equivalent.
If the user does not check the return value, then the compiler generates a warning.
The cowboys, of course, have gamed the system and code if (foo() != SUCCESS) ; which satisfies the compiler (although it does not satisfy me :-).
A: A single ; is the null statement which does nothing. It's often used in long if/else chains like:
if (a == 1) {
// Do nothing.
;
}
else if (...) {
...
}
else if (...) {
...
}
This could also be written as:
if (a != 1) {
if (...) {
...
}
else if (...) {
...
}
}
The latter adds another level of indentation but IMO, it's clearer. But null statements can sometimes be useful to avoid excessive indentation if there are multiple branches without code.
Note that an empty compound statement (also called block) has the same effect:
if (a == 1) {}
Technically, you only need the semicolon if you want to use an expression statement directly:
if (a == 1) ;
else if (...) { ... }
else if (...) { ... }
So writing {;} is redundant and only serves a dubious illustrative purpose.
Another example from the C standard where the null statement is used to supply an empty loop body:
char *s;
/* ... */
while (*s++ != '\0')
;
But here I'd also prefer an empty compound statement.
A: It's an empty statement. A single semicolon by itself performs no operation.
In this context, it means that if the if condition is true, do nothing.
Without an else section, there is not much use to this code. If there is, then it's a matter of style whether the condition should be inverted and should contain just a non-empty if portion.
In this case it's a simple conditional, so style-wise it's probably better to invert it, however if the condition is more complicated it may be clearer to write this way. For example, this:
if ((a==1) && (b==2) && (c==3) && (d==4)) {
;
} else {
// do something useful
}
Might be clearer than this:
if (!((a==1) && (b==2) && (c==3) && (d==4))) {
// do something useful
}
Or this:
if ((a!=1) || (b!=2) || (c!=3) || (d!=4)) {
// do something useful
}
A better example from the comments (thanks Ben):
if (not_found) {
;
} else {
// do something
}
Versus:
if (!not_found) {
// do something
}
Which method to use depends largely on exactly what is being compared, how many terms there are, how nested the terms are, and even the names of the variables / functions involved.
Another example of when you might use this is when you have a set of if..else statements to check a range of values and you want to document in the code that nothing should happen for a particular range:
if (a < 0) {
process_negative(a);
} else if (a >=0 && a < 10) {
process_under_10(a);
} else if (a >=10 && a < 20) {
; // do nothing
} else if (a >=20 && a < 30) {
process_20s(a);
} else if (a >= 30) {
process_30s_and_up(a);
}
If the empty if was left out, a reader might wonder if something should have happened there and the developer forgot about it. By including the empty if, it says to the reader "yes I accounted for this and nothing should happen in this case".
Certain coding standards require that all possible outcomes be explicitly accounted for in code. So code adhering to such a standard might look something like this.
A: It's called null statement.
From 6.8.3 Expression and null statements:
A null statement (consisting of just a semicolon) performs no
operations.
In this particular example if(a==1){;}, it doesn't do anything useful (except perhaps a bit more obvious) as it's same as if(a==1){} or if(a==1);.
A: It is basically an null/empty statement, which does nothing, and is as expected benign (no error) in nature.
C Spec draft N1570 clarifies that:
*
*the expressions are optional: expression[opt] ;
*A null statement (consisting of just a semicolon) performs no operations.
On the other hand, Bjarne quotes in his C++ book #9.2 Statement Summary:
A semicolon is by itself a statement, the empty statement.
Note that these two codes, if(1) {;} and if(1) {}, have no difference in the generated gcc instructions.
A: ; on its own is an empty statement. If a is an initialised non-pointer type, then
if(a==1){;}
is always a no-op in C. Using the braces adds extra weight to the assertion that there is no typo. Perhaps there is an else directly beneath it, which would execute if a was not 1.
A: No purpose at all. It's an empty statement. It's possible that the developer wanted to do something if a was not 1 in which case the code would be something like (even though the ; can still be omitted) :
if(a==1)
{
;
}
else
{
//useful code...
}
But in that case, it could've easily been written as if(a != 1).
Note however, if this is C++(tags aren't clear yet) then there would be a possibility that the operator== of type a was overloaded and some side effects could've been observed. That would mean that the code is insane though.
A: It is so called null statement. It is a kind of the expression statement where the expression is missed.
Sometimes it is used in if-else statements as you showed when it is easy to write the if condition than its negation (or the if condition is more clear) but the code should be executed when the if condition is evaluated to false.
For example
if ( some_condition )
{
; // do nothing
}
else
{
// here there is some code
}
Usually the null statement is used for exposition only to show that for example body of a function, or a class constructor or a for loop is empty. For example
struct A
{
A( int x ) : x( x )
{
;
}
//...
};
Or
char * copy_string( char *dsn, const char *src )
{
char *p = dsn;
while ( ( *dsn++ = *src++ ) ) ;
^^^
return p;
}
Here the null statement is required for the while loop. You could also rewrite it like
while ( ( *dsn++ = *src++ ) ) {}
Sometimes the null statement is required especially in rare cases when goto statement is used. For example in C declarations are not statements. If you want to pass the program control to a point before some declaration you could place a label before the declaration. However in C a label may be placed only before a statement. In this case you could place a null statement with a label before the declaration. For example
Repeat:;
^^^
int a[n];
//....
n++;
goto Repeat;
Pay attention to the null statement after the label. If to remove it then the C compiler will issue an error.
This trick also is used to pass the program control to the end of a compound statement. For example
{
// some code
goto Done;
//...
Done:;
}
Though you should not use the goto statement but you should know about these cases.:)
A: Why would you do it? I do similar things all the time when debugging to give me something that (I hope) won't be optimized away so I can put a break point on it.
Normally though I make it obvious its a debug mark
if( (a==1) && (b==2) && (c==3) && (d==4) ){
int debug=1;
}
Otherwise I end up with weird little bits of code stuck everywhere that make absolutely no sense even to me.
But that is not guarantee that's what this was.
A: ; is an empty statement noop
What is its purpose?
Sometimes we just want to compare things like in this case the equality of a and 1. With primitive types like integer, this will set condition register so if you have after this if something like if(a > 1) or if(a < 1), and a is not changed in the meantime, this might not be evaluated again depending on the compiler decision.
This code
int f(int a){
if(a == 1){;}
if(a > 1){return 3;}
if(a < 1){return 5;}
return 0;
}
will give
.file "c_rcrYxj"
.text
.p2align 2,,3
.globl f
.type f, @function
f:
.LFB0:
.cfi_startproc
cmpl $1, 4(%esp)
jle .L6
movl $3, %eax
ret
.p2align 2,,3
.L6:
setne %al
movzbl %al, %eax
leal (%eax,%eax,4), %eax
ret
.cfi_endproc
.LFE0:
.size f, .-f
.ident "GCC: (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4"
.section .note.GNU-stack,"",@progbits
The comparison is done only once cmpl $1, 4(%esp), exactly where if(a==1) is written.
A: You probably already know that the semicolon is an empty statement. Concerning the actual question "what purpose does this semicolon serve", the answer is (unless the author of this code wanted to enliven the code with some weird emoticon), that it serves absolutely no purpose at all. That is, {;} is completely equivalent to {} in any context (where a statement is expected, which I think is the only place where {;} can be used). The presence of the semicolon changes a compound statement with 0 constituent statements into a compound statement with 1 constituent statement which is an empty statement, but the two cases are equivalent as far as semantics is concerned.
I'll add a personal opinion that for readability concern of not being accidentally overlooked by a reader of the code, {;} is no better than {} (if it were, then maybe {;;;;;;;;} would be better still), though both are considerably better than a lone ; (and as a consequence the language would have been better off without allowing ; as empty statement at all, since replacing it with {} is always advantageous).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41592982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "41"
} |
Q: Multiple Join in Entity Framework I have the following query in TSQL
select * from users
inner join linkUserPhoneNumber on users.UserId = linkUserPhoneNumber.UserId
INNER JOIN PhoneNumber ON PhoneNumber.PhoneNumberId =
linkUserPhoneNumber.PhoneNumberId
where UserName = 'superuser' and password ='password'
I have the following query in Entity Framework
var query = (from u in myEntities.Users
join link in myEntities.linkUserPhoneNumbers on u.UserId equals link.UserId
join p in myEntities.PhoneNumbers on p.PhoneNumberId equals link.PhoneNumberId
where u.UserName == Username && u.Password == Password
select u).ToList();
When I try to compile it, I get
Error 3 The name 'p' is not in scope on the left side of 'equals'. Consider swapping the expressions on either side of 'equals'.
Error 4 The name 'link' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
A: Exactly what the error is saying
p.PhoneNumberId equals link.PhoneNumberId
should be
link.PhoneNumberId equals p.PhoneNumberId
Full code
var query = (from u in myEntities.Users
join link in myEntities.linkUserPhoneNumbers on u.UserId equals link.UserId
join p in myEntities.PhoneNumbers on link.PhoneNumberId equals p.PhoneNumberId
where u.UserName == Username && u.Password == Password
select u).ToList();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11537757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Codeigniter MySQL security, htmlspecialcharacters & mysql_real_escape_string? I've been reading a lot about database security and using htmlspecialcharacters() and mysql_real_escape_string.
Is this necessary to use these functions with codeigniter or does it handle this automatically? e.g.
$this->db->select('*', FALSE);
$this->db->where('published', 'yes');
$query = $this->db->get('my_table');
$results = $query->result_array()
A: You don't have to worry about escaping your text as long as you use active records.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22875778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Efficiently combine two queries with both have a common inner join I would like to join three tables and then union them. Two of the table that are joined are the same in the two queries which are union'd, and it seems like a waste to perform this join twice. See below for an example. How is this best performed? Thanks
SELECT t1.c1,t2.c1,t3.c1
FROM audits AS t1
INNER JOIN t2 ON t2.t1_id=t1.id
INNER JOIN t3 ON t3.t1_id=t1.id
WHERE t2.fk1=123
UNION
SELECT t1.c1,t2.c1,t4.c1
FROM audits AS t1
INNER JOIN t2 ON t2.t1_id=t1.id
INNER JOIN t4 ON t4.t1_id=t1.id
WHERE t2.fk1=123
ORDER BY t1.fk1 ASC
A: This would work, if the syntax is supported by MySql, and might be slightly more efficient:
SELECT t1.c1, t2.c1, t.c1
FROM audits AS t1
INNER JOIN t2 ON t2.t1_id=t1.id
INNER JOIN (
select t1_id from t3
union
select t1_id from t4
) as t ON t.t1_id=t1.id
WHERE t2.fk1=123
ORDER BY t1.fk1 ASC
The reason for a pssible performance improvement is the smaller footprint of the relation being UNION'ed; one column instead of 3. UNION eliminates duplicates (unlike UNION ALL) so the entire collection of records must be sorted to eliminate duplicates.
At the meta-level this query informs the optimizer of a specific optimization available, that it may be unable to determine on it's own.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15914369",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Use jQuery to apply styling to all instances of clicked element What I'm aiming for is for jQuery to look at the element I've just clicked on (for example a p or an li tag), then apply a styling to all instances of that element (so all p tags on the page).
This is my code so far, but it only applies the styling to the single element that has been clicked on.
$("article *", document.body).click(function (e) {
e.stopPropagation();
selectedElement = $(this);
$(selectedElement).css("border", "1px dotted #333")
});
Would appreciate any help or advice!
A: $('article *',document.body).click(
function(e){
e.stopPropagation();
var selectedElement = this.tagName;
$(selectedElement).css('border','1px dotted #333');
}
);
Demo at JS Bin, albeit I've used the universal selector (since I only posted a couple of lists (one an ol the other a ul).
Above code edited in response to comments from @Peter Ajtai, and linked JS Bin demo up-dated to reflect the change:
Why run around the block once before you look at the tagName? How about var selectedElement = this.tagName;. Also it's e.stopPropagation(), since you're calling a method.
A: I don't know how many elements are nested under your article elements, but it would seem wasteful to add click event handlers to all of them using *.
Instead, just add the handler to article, and get the tagName of the e.target that was clicked.
$("article", document.body).click(function ( e ) {
e.stopPropagation();
$( e.target.tagName ).css("border", "1px dotted #333")
});
This will be much more efficient.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3886566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: LineChart with annotations and multiple graph lines I'm using Google Charts to try and create a line chart that looks like the first one labelled Example:
https://developers.google.com/chart/interactive/docs/gallery/linechart
However, I cannot use google.visualization.arrayToDataTable() as shown in the 1st example.
The problem is I want to add annotations and annotationText to each plotted point. The documentation says I must use:
google.visualization.DataTable()
In order to do that, i must do the following:
var data1 = [
[ 'C' ,4, 'o', 'note'],
[ 'D' ,6, 'o', 'note'],
[ 'O' ,4, 'o', 'note']
];
var chartData = new google.visualization.DataTable();
chartData.addColumn('string', 'X'); // Implicit series 1 data col.
chartData.addColumn('number', 'DOGS'); // Implicit domain label col.
chartData.addColumn({type:'string', role:'annotation'});
chartData.addColumn({type:'string', role:'annotationText'});
chartData.addRows(data1);
var chart = new
google.visualization.LineChart(document.getElementById('visualization'));
var options = {
title: "My Title",
};
chart.draw(chartData,options);
This gives me one line of plotted data.
How do I adapt this to allow me to add a 2nd line of plotted data?goo
A: You have to add additional columns and expand your data. For example:
chartData.addColumn('string', 'X'); // Implicit series 1 data col.
chartData.addColumn('number', 'DOGS'); // Implicit domain label col.
chartData.addColumn({type:'string', role:'annotation'});
chartData.addColumn({type:'string', role:'annotationText'});
chartData.addColumn('number', 'CATS'); // Implicit domain label col.
chartData.addColumn({type:'string', role:'annotation'});
chartData.addColumn({type:'string', role:'annotationText'});
var data1 = [
[ 'C', 4, 'Dog1', 'Dog1 note', 7, 'Cat1', 'Cat1 note'],
[ 'D', 6, 'Dog2', 'Dog2 note', 11, 'Cat2', 'Cat3 note'],
[ 'O', 4, 'Dog3', 'Dog3 note', 13, 'Cat3', 'Cat3 note']
];
chartData.addColumn('string', 'X'); // Implicit series 1 data col.
chartData.addColumn('number', 'DOGS'); // Implicit domain label col.
chartData.addColumn({type:'string', role:'annotation'});
chartData.addColumn({type:'string', role:'annotationText'});
chartData.addColumn('number', 'CATS'); // Implicit domain label col.
chartData.addColumn({type:'string', role:'annotation'});
chartData.addColumn({type:'string', role:'annotationText'});
var data1 = [
[ 'C', 4, 'Dog1', 'Dog1 note', 7, 'Cat1', 'Cat1 note'],
[ 'D', 6, 'Dog2', 'Dog2 note', 11, 'Cat2', 'Cat3 note'],
[ 'O', 4, 'Dog3', 'Dog3 note', 13, 'Cat3', 'Cat3 note']
];
chartData.addRows(data1);
See example at jsBin
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20722738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to sample from multiple lists (numbers? I would like to sample, let's say the ages of 100 persons above 65 years old,
and the probabilities for the age groups are as follows:
65-74<- 0.56
75-84<- 0.30
85<- 0.24
I know the existence of the sample function and I tried it as follows,but that didn't work unfortunately
list65_74<-range(65,74)
list75_84<-range(75,84)
list85<-range(85,100)
age<-sample(c(list65_74,list75_84,list85),size=10,replace=TRUE,prob =c(0.56,0.30,0.24 ))I get the following error
I got then the following error
Error in sample.int(length(x), size, replace, prob) :
incorrect number of probabilities
So I was wondering what is the proper way to sample from multiple lists.
Thank you very much in advance!
A: First, let's I'll call those three objects groups instead since they don't use the list function.
The way you define them could be fine, but it's somewhat more direct to go with, e.g., 65:74 rather than c(65, 74). So, ultimately I put the three groups in the following list:
groups <- list(group65_74 = 65:74, group75_84 = 75:84, group85 = 85:100)
Now the first problem with the usage of sample was your x argument value, which is
either a vector of one or more elements from which to choose, or a
positive integer. See ‘Details.’
Meanwhile, you x was just
c(list65_74, list75_84, list85)
# [1] 65 74 75 84 85 100
Lastly, the value of prob is inappropriate. You supply 3 number to a vector of 6 candidates to sample from. Doesn't sound right. Instead, you need to assign an appropriate probability to each age from each group as in
rep(c(0.56, 0.30, 0.24), times = sapply(groups, length))
So that the result is
sample(unlist(groups), size = 10, replace = TRUE,
prob = rep(c(0.56, 0.30, 0.24), times = sapply(groups, length)))
# [1] 82 72 69 74 72 72 69 70 74 70
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53061890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What happens if I use CClientDC in OnPaint() function? I am new to MFC and Windows programming in general and this is something I haven't understood
Everywhere I have been reading it says not to use CClientDC in OnPaint and only use CPaintDC
In my code, I append my rectangle drawing functions to the default OnPaint() handler created when I make a dialog based MFC application using the wizard
void Cgraph_on_dlgboxDlg::OnPaint()
{
CPaintDC dc(this); // ----------------------------> LINE 1
if (IsIconic())
{
// CPaintDC dc(this); // device context for painting // ----------------------------> LINE 2
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
COLORREF pencolour = RGB(0, 0, 0);
COLORREF brushcolour = RGB(0, 0, 255);
CPen pen(PS_SOLID, 5, pencolour);
CBrush brush(HS_CROSS, brushcolour);
// CPaintDC Dc(this); // ----------------------------> LINE 3
// CClientDC Dc(this); // ----------------------------> LINE 4
dc.SetBkMode(TRANSPARENT);
/****
get rectangle coordinates and properties
****/
dc.Rectangle(CRect(point1, point2));
}
In this code, originally, LINE 1 doesn't exist. In this case, the program draws a rectangle if CClientDC is declared in LINE 4, but does not draw anything in CPaintDC in LINE 3 is enabled. If the CPaintDC in LINE 2 is removed to LINE 1 and LINE 3 and 4 are commented out, it works. Why is this happening? From what I understood, CClientDC should not work at all here, or am I missing something?
Again, shouldn't the CPaintDC in LINE 2 have it's scope within the if block only? Why does declaring CPaintDC twice create no output at all?
A: The CPaintDC constructor calls BeginPaint to get a DC that is clipped to the invalid area (the area that needs painting). Constructing a second CPaintDC gets an empty invalid area, so it can't paint anything.
The default code constructs a CPaintDC only at line 2 because it is not going to call CDialogEx::OnPaint when the dialog is minimized. When the dialog is not minimized then CDialogEx::OnPaint will construct a CPaintDC. One and only one CPaintDC can be used for any particlular call to OnPaint.
You can use CClientDC to paint your rectangle, as long as you leave the original treatment of CPaintDC as it was.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17444372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: My CSS works in the inline section but not as an external stylesheet I am currently trying to use CSS to stylize my application in Apex 5. The problem I am having is that when I write my CSS code in the "inline" section of any page in the application, then the CSS code works, but if I write the CSS code on Notepad and then upload the file and reference the file within my application, then the CSS code does not work. I have written several lines of CSS code, so I'll just post one small section of it as a sample so that you all can see my format:
body{
font: bold 12px/16px "Times New Roman";
}
I have uploaded the file in the Static Application Files section of the Shared Components page of the application. I have then tried referencing the file in different places, such as at the page level and user interface level, but nothing has worked so far. I'm very new to CSS, so any insight would be greatly appreciated. Thank you in advance!
A: After uploading the file have to be displayed in the list of static files. The list of files have a column Reference, which contain a string like this: #APP_IMAGES#test.css. Copy this string and put it, for example, on the page in the section CSS - File URLs. This should work.
Then make sure that file reference works. Open your page and take a look on a list of CSS files. The same functionality is present in all browsers, but it is accessible by different ways. In IE:
*
*Press F12.
*Open Network tab.
*Press "Enable network traffic capturing" (a green triangle in the left top corner).
*Reload the page. A list of files appears.
*Find your file in a list:
*
*If the file is not present, then you copied an incorrect link, or you copied it into an incorrect place, etc.
*If the file is present, normally it should have status 200 (the Result column). If a status is not 200, there could be a lot of reasons (depending on the status).
*If the file is present with the status 200, your CSS property doesn't work, because it is overridden with another CSS. To define with which one, go to the Dom Explorer tab.
A: You can try this approach:
*
*On server, go to ORACHE_HOME/apex/images/css (path can be different, but you can find it by .css extension)
*Put you file here
*Id editor, in page properties, go to the CSS -> File URLs section
*Write path like this: /i/css/new.css (i - in general, alias for your images directory)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48755826",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Rendering VTK visualization using OpenCV instead Is it possible to get a rendered frame from a VTK visualization and pass it to OpenCV as an image without actually rendering a VTK window?
Looks like I should be able to follow this answer to get the rendered VTK frame from a window and then pass it to OpenCV code, but I don't want to render the VTK window. (I want to render a PLY mesh using VTK to control the camera pose, then output the rendered view to OpenCV so I can distort it for an Oculus Rift application).
Can I do this using the vtkRenderer class and not the vtkRenderWindow class?
Also, I'm hoping to do this all using the OpenCV VTK module if that is possible.
EDIT: I'm starting to think I should just be doing this with VTK functions alone since there is plenty of attention being paid to VTK and Oculus Rift paired together. I would still prefer to use OpenCV since that side of the code is complete and works nicely already.
A: You must make your render windows to render offline like this:
renderWindow->SetOffScreenRendering( 1 );
Then use a vtkWindowToImageFilter:
vtkSmartPointer<vtkWindowToImageFilter> windowToImageFilter =
vtkSmartPointer<vtkWindowToImageFilter>::New();
windowToImageFilter->SetInput(renderWindow);
windowToImageFilter->Update();
This is called Offscreen Rendering in VTK. Here is a complete example
A: You can render the image offscreen as mentioned by El Marce and then convert the image to OpenCV cv::Mat using
unsigned char* Ptr = static_cast<unsigned char*>(windowToImageFilter->GetOutput()->GetScalarPointer(0, 0, 0));
cv::Mat RGBImage(dims[1], dims[0], CV_8UC3, Ptr);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33252527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What's the Intent to open DND settings? I'm sure I'm overlooking something in the Settings class documentation. What Intent can open the Settings app in the "Do not disturb" section?
I expected it to be the ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS action, but that is only for the screen which lists which apps have requested DND access.
A: Update
Looking at the AndroidManifest.xml for the Settings app there is an Activity Settings$ZenModeSettingsActivity already from Android 5.0.
To send the user to the "Do not disturb" screen you can use the action android.settings.ZEN_MODE_SETTINGS like this:
try {
startActivity(new Intent("android.settings.ZEN_MODE_SETTINGS"));
} catch (ActivityNotFoundException e) {
// TODO: Handle activity not found
}
Original answer
It looks like there are no screens in the Settings app (at least on Android 6+7) where you can enable/disable DND. It seems like this is only available through the settings tile (and can be disabled in the dialog when changing the volume).
I have a Samsung S6 (Android 6.0.1) which has this screen, but this is probably some custom Samsung changes. The screen is represented by the class com.android.settings.Settings$ZenModeDNDSettingsActivity which can be started by any app. This might be of help for some people out there.
AndroidManifest.xml for Settings app for Android 6+7:
*
*https://android.googlesource.com/platform/packages/apps/Settings/+/android-6.0.1_r68/AndroidManifest.xml
*https://android.googlesource.com/platform/packages/apps/Settings/+/android-7.0.0_r6/AndroidManifest.xml
A: You have to use the following Intent: ACTION_VOICE_CONTROL_DO_NOT_DISTURB_MODE and then pass a boolean through EXTRA_DO_NOT_DISTURB_MODE_ENABLED.
Make note that the documentation specifies the following: This intent MUST be started using startVoiceActivity.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39596496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Complicated MySQL Query with distinct Here is the table I am getting the data from "actually it's a view of two different tables"
*
*The first table is the users table the holds everything about the user.
*The second is a log table that logs who viewed the video and when they viewed it.
log_views.id,
log_views.user_id,
log_views.video_id,
log_views.date,
users.user_key,
users.name_display,
users.img_key
What I am trying to is display the last 18 users to view a video but I don't want any duplicate users. So if a user shows up twice in the last 18 I only want his latest view and then skip all the others.
I tried using the DISTINCT keyword but I am getting more than one column so it didn't work.
A: Have a look at these for some pointers:
MySQL Group By with top N number of each kind
http://explainextended.com/2009/03/06/advanced-row-sampling/
A: This is what i ended up using.
recent_video_viewers is the name of the view I made so i didn't have to do any joins
SELECT id, MAX(date), user_id, img_key, random_key
FROM recent_video_viewers
WHERE video_id = '$vr[id]' AND img_key != ''
GROUP BY user_id
ORDER BY MAX(date) DESC
LIMIT 18
I'm not sure if this is the best way to do this but it works.
A: Here is a query that works. It assume that you need logs only for a given video id (@video_id):
SELECT log_date, user_id, name_display
FROM (
SELECT MAX(l.date) AS log_date, user_id
FROM log_views AS l
WHERE (l.video_id=@video_id)
GROUP BY user_id
ORDER BY log_date DESC
LIMIT 18
) AS top
INNER JOIN users AS u ON (u.user_key=top.user_id)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5477963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: error for "apply" in kotlin on android studio I was following a tutorial on android studio and wrote the following lines:
RecyclerView.apply {this:RecyclerView!
var layoutManager = LinearLayoutManager(activity)
but the "apply" was giving me an error and when I did Alt+Enter I saw two options for import that I did not really understand. they had to do with something called "auto-import" and i saw the word "gravity gradle". The suggestions went away for some reason after i messed around with the settings that came up, but the error is still there.
A: "apply" is available to Any object in kotlin. You don't need to import anything to use "apply"
Apply in Kotlin
But, if IDE is suggesting you to import anything for apply, that means kotlin library is not properly configured.
Check your app/build.gradle dependencies whether kotlin-stdlib exists or not.
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
A: that is because RecyclerView is not an instance. You can't use "apply" on a class.
You may want to do something like this
val recyclerView = findViewById<RecyclerView>(R.id.your_recycler)
recyclerView.apply {
layoutManager = LinearLayoutManager(activity)
}
A: Here's how apply works:
val recyclerView = RecyclerView(context)
recyclerView.adapter = MyAdapter()
recyclerView.layoutManager = LinearLayoutManager()
recyclerView.hasFixedSize = true
vs
val recyclerView = RecyclerView(context).apply {
adapter = MyAdapter()
layoutManager = LinearLayoutManager()
hasFixedSize = true
}
you run it on an instance of an object, which becomes this in the lambda, so you can do all the calls on the object without referring to it by name. And the original object pops out of the end, so you can assign the whole thing to val recyclerView - it gets the RecyclerView() you created, with a few settings applyed to it. So it's common to configure objects like this.
So like people have said, you weren't calling apply on a RecyclerView instance, you were calling it on the class itself, which doesn't work. You need to create a thing. Kotlin synthetic binding is magic code that automatically creates objects for you, from the XML it inflates, and assigns them to a variable named after the view's ID in the XML. So your tutorial is referring to an instance, using a variable name that the synthetics declared in the background. It's confusing if you're not aware of it, and I wonder if that's part of the reason it's deprecated.
Sinner of the System's answer is the easiest (and normal) way to grab an object from your layout, by looking it up by ID yourself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65451695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Browsing a MySQL database on AWS servers I have just installed MySQL on to my AWS EC2 server, I have also imported my existing SQL file so that my new MySQL db is now populated. I would like to be able to browse my database somehow.
In the past I used phpmyadmin and it was great, should I install phpmyadmin and then access it through my browser somehow? or am I looking down the wrong road.
Cheers
A: No reason you cant install phpmyadmin on your new EC2 server. Just remember to open up the necessary ports through amazons security group, and if you dont want the whole world to be able to access it, you can restrict the ports to only IP addresses you use.
AWS SECURITY GROUPS
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37128275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Dragging multiple html elements at once I would like to be able to drag an image next to some text and have the text move with it, the problem is that I can either move the image or move the text not have one move the other my current code for that is:
<ol>
<div style="cursor: move; user-select: none;">
<img style="width: 50px;" src="hand.png" alt="drag">
<h3 style="float: right" contenteditable='true'>sample</h3>
</div>
<h3 contenteditable='true'>sample2</h3>
</ol>
how would I make it so that I can drag the image and have it move the text?
A: How to drag (and drop) an image back and forth between two elements:
<!DOCTYPE HTML>
<html>
<head>
<style>
#div1, #div2 {
float: left;
width: 100px;
height: 35px;
margin: 10px;
padding: 10px;
border: 1px solid black;
}
</style>
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>
<h2>Drag and Drop</h2>
<p>Drag the image back and forth between the two div elements.</p>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
<img src="img_w3slogo.gif" draggable="true" ondragstart="drag(event)" id="drag1" width="88" height="31">
</div>
<div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
</body>
</html>
i am not sure if this is what you are looking for if not, please provide an example of what you need
or you can refer to this link for dragging multiple items:
https://codepen.io/SitePoint/pen/gbdwjj
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68993148",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Get past request without waiting for response (Angular 2 +) I am looking for data in an API via Get request, I need the data inside my OnInit to use in composing other data. The problem is that the method is being called but it is as an async method (without await), it passes everywhere but when the return is obtained the excution of the main method has already been finished with no results. I tried the implementation of asynchronous methods but it did not solve.
service:
getObjects(): MyClass[] {
let objects = new Array<MyClass>();
this.obterTodos<MyClass>(this.uriApi)
.map(res => res.map(x => new MyClass(x.Description, x.Id)))
.subscribe(entities => {
objects = entities;
});
return objects ;
}
get request
public getObjects<TEntity>(url: string): Observable<TEntity[]> {
return this.httpService
.get(this.serviceUrl + url, this.options)
.map(res => res.json())
.catch(this.handleError);
}
component:
ngOnInit() {
this.myObjects= this.setorService.obterSetores();
console.log('this.myObjects is empty here');
}
A: so you'll want to subscribe to your observable in the component. This is typically done so the component can determine when the http request should be ran & so the component can wait for the http request to finish (and follow with some logic).
// subscribe to observable somewhere in your component (like ngOnInit)
this.setorService.obterSetores().subscribe(
res => {
this.myObjects = res;
},
err => {}
)
now the component knows when the http request finishes
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44686837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: celery 4.4.2 and django 3.0.2 raising self.notregistered error but calling the function in python manage.py shell works fine I am trying to add celery to my django project.
everything works fine when i run it from the manage.py shell, my celery worker returns the result of the add() function.
when i call this function from my view it raises a not registered error and a module object not callable error on celery/base.py line 1253
celery/app/base.py", line 1253, in loaderreturn get_loader_cls(self.loader_cls)(app=self)
TypeError: 'module' object is not callable
raise self.NotRegistered(key)
celery.exceptions.NotRegistered: 'home.tasks.add'
both are from the apache error log
my home.tasks.py looks like this
from celery import shared_task
from celery.schedules import crontab
from django.db import connection
from django.utils import timezone, translation
#import pandas as pd
from home.models import *
from residence_management.models import *
from sqlalchemy import *
from django.conf import settings
from django.contrib.auth.models import User
from decimal import Decimal
@shared_task
def add(x, y):
return x + y
my view where i call the task has the import: from home.tasks import add
in the view itself i just call add(9, 5) and it fails with the above error (without the @shared_task decorator it works fine).
when calling the function in the shell, even with the @shared_task decorator it works fine, i can start the celery worker without problems as well.
[2020-05-13 08:47:23,862: INFO/MainProcess] Received task: home.tasks.add[f7e50f7d-4e3d-4372-bf3e-e1c7175c7a2a]
[2020-05-13 08:47:23,879: INFO/ForkPoolWorker-8] Task home.tasks.add[f7e50f7d-4e3d-4372-bf3e-e1c7175c7a2a] succeeded in 0.015277621999999713s: 14
any ideas where the problem might be? i use redis for the broker and result backend
A: You can check docs and comments for shared_task on github https://github.com/celery/celery/blob/9d49d90074445ff2c550585a055aa222151653aa/celery/app/init.py
I think for some reasons you do not run creating of celery app. It is better in this case use explicit app.
from .celery import app
@app.task()
def add(x, y):
return x + y
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61764646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: bash script - escape characters in eval vs running command directly I am writing a bash script to count number of files given user parameters of path and exclude path. I construct a command using my bash script, where the last few line looks like this
command="find . $exclude | wc -l"
echo $command
So for example, it might result in
find .
Or if I set exclude to be '-not \( -path "./special_dir" -prune \)', then the command would be
find . -not \( -path "./special_directory" -prune \)
Both commands I can copy and paste into a command line and everything is fine.
The problem comes when I try to run it.
exclude=""
command="find $. $exclude | wc -l"
echo $command
results=$($command)
echo "result=$results"
Above works, but the snippet below would fail.
exclude='-not \( -path "./special_dir" -prune \)'
command="find $. $exclude | wc -l"
echo $command
results=$($command)
echo "result=$results"
returns
find . -not \( -path "./special_dir" -prune \) | wc -l
find: paths must precede expression: \(
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]
But if I use eval to run command, even the exclude is fine
exclude='-not \( -path "./special_dir" -prune \)'
command="find $. $exclude | wc -l"
echo $command
results=$(eval $command)
echo "result=$results"
Returns
find . -not \( -path "./special_dir" -prune \) | wc -l
result=872
I don't understand what's wrong with just running the command with exclude directory. My guess is it has to do some with kind of escaping special characters?
A:
what's wrong with just running the command with exclude directory.
Pipeline | is parsed before variables are expanded.
Unquoted variable expansion undergo word splitting and filename expansion. This is irrelevant of quotes and backslashes inside the string - you can put as many backslashes as you want, the result of the expansion still will be split on spaces. https://www.gnu.org/software/bash/manual/bash.html#Shell-Expansions
y guess is it has to do some with kind of escaping special characters?
No, it does not matter what is the content of the variable. It's important how you use the variable.
Above works, but the snippet below would fail.
Yes, \( is an invalid argument for find, it should be (. The result of expansion is not parsed for escape sequences, they are preserved literally, so \( stays to be \(, two characters. In comparison, when the line is parsed, then quoting is parsed. https://www.gnu.org/software/bash/manual/bash.html#Shell-Operation
In either case, you want to be using Bash arrays and want to do a lot of experimenting with quoting and expansion in shell. The following could be enough to get you started:
findargs=( -not \( -path "./special_directory" -prune \) )
find . "${findargs[@]}"
Check your scripts with shellcheck. Do not store commands in variables - use functions and bash arrays. Quote variable expansions. eval is very unsafe, and if the path comes from the user, shouldn't be used. Use printf "%q" to quote a string for re-eval-ing. See https://mywiki.wooledge.org/BashFAQ/050 , https://mywiki.wooledge.org/BashFAQ/048 , and read many introductions to bash arrays.
A: The reason you typically have to escape the parentheses in a find command is that parentheses have special meaning in bash. Bash sees a command like find . -not ( -path "./special_dir" -prune ) and tries to interpret those parentheses as shell syntax instead of literal characters that you want to pass to your command. It can't do that in this context, so it complains. The simple fix is to escape the parentheses to tell bash to treat them literally.
To reiterate: those backslashes are NOT syntax to the find command, they are there to tell bash not to treat a character specially even if it normally has special meaning. Bash removes those backslashes from the command line before executing the command so the find program never sees any backslashes.
Now in your use case, you're putting the command in a variable. Variable expansion happens after bash has parsed the contents of the command line, so escape characters inside the variable (like '\') won't be treated like escapes. They'll be treated like any normal character. This means your backslashes are being passed as literal characters to your command, and find doesn't actually know what to do with them because they aren't part of that command's syntax.
Further reading on the bash parser
The simplest thing you can do: Just don't include the backslashes. Something like this will work fine:
exclude='-not ( -path ./special_dir -prune )'
command="find . $exclude"
$command
The parentheses don't actually need to be escaped here because the parsing step that would interpret them as special characters happens before variable expansion, so they'll just be treated literally.
But really, you might be better off using a function. Variables are meant to hold data, functions are meant to hold code. This will save you a lot of headaches trying to understand and work around the parsing rules.
A simple example might be:
normal_find() {
find .
}
find_with_exclude() {
find . -not \( -path ./special_dir -prune \)
}
my_command=normal_find
#my_command=find_with_exclude #toggle between these however you like
results=$( $my_command | wc -l )
echo "results=$results"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72606721",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can't access variable in my helper from application controller in Rails engine I created a gem that extends a Rails Engine. I am using Rails 4. Everything works fine except i cant access instance variable in application controller from helpers. Here is my code...what am i doing wrong?
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
def get_context
@variable = "variable"
end
end
app/helpers/evaluate_helper.rb
module EvaluateHelper
def app_name
@variable #=> nothing here
end
end
lib/evaluate/version.rb
require "rails"
require "evaluate/version"
module Evaluate
VERSION = "0.0.1"
class Engine < ::Rails::Engine
end
end
evaluate.gemspec
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'evaluate/version'
Gem::Specification.new do |spec|
spec.name = "evaluate"
spec.version = Evaluate::VERSION
spec.authors = ["My name"]
spec.email = ["myemail"]
spec.summary = %q{Evaluation}
spec.description = %q{Evaluation and analysis of application usage.}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "rails", ">= 3.1"
spec.add_development_dependency "bundler", "~> 1.6"
spec.add_development_dependency "rake"
spec.add_development_dependency "browser"
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26126730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Converting 1D numpy array into top triangle of matrix Is it possible to take a 1D numpy array containing 171 values and place these values into the top triangle of an 18X18 matrix?
I feel like I should be able to use np.triu_indices to do this somehow but I can't quite figure it out!
Thanks!
A: See What is the most efficient way to get this kind of matrix from a 1D numpy array? and Copy flat list of upper triangle entries to full matrix?
Roughly the approach is
result = np.zeros(...)
ind = np.triu_indices(...)
result[ind] = values
Details depend on the size of the target array, and the layout of your values in the target.
In [680]: ind = np.triu_indices(4)
In [681]: values = np.arange(16).reshape(4,4)[ind]
In [682]: result = np.zeros((4,4),int)
In [683]: result[ind]=values
In [684]: values
Out[684]: array([ 0, 1, 2, 3, 5, 6, 7, 10, 11, 15])
In [685]: result
Out[685]:
array([[ 0, 1, 2, 3],
[ 0, 5, 6, 7],
[ 0, 0, 10, 11],
[ 0, 0, 0, 15]])
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34913483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Fatal error on Android 7.1.2(API 25) after execution of Garbage Collection If use app 3 to 4 min, I always end up with Fatal error which comes after the execution of Garbage collection.
I have almost optimised memory usage, however, my app crashes with Fatal error.
Here is the log,
08-30 04:59:48.603 W/InputEventReceiver(29468): Attempted to finish an input event but the input event receiver has already been disposed.
08-30 04:59:48.943 I/SearchCardActivity(29468): onDestroy
08-30 04:59:48.944 I/art (29468): Starting a blocking GC Explicit
08-30 04:59:49.054 I/art (29468): Explicit concurrent mark sweep GC freed 37724(2MB) AllocSpace objects, 17(2020KB) LOS objects, 40% free, 23MB/39MB, paused 1.180ms total 109.379ms
--------- beginning of crash
08-30 04:59:49.083 F/libc (29468): Fatal signal 11 (SIGSEGV), code 1, fault addr 0x44789914 in tid 29475 (FinalizerDaemon)
Thanks in advance!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73533274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: rails 4.2.1 server error Hi I am new to rails and every time I try to view the server i get this
testapp$ rails s
/home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/execjs-2.5.2/lib/execjs/runtimes.rb:48:in `autodetect': Could not find a JavaScript runtime. See https://github.com/rails/execjs for a list of available runtimes. (ExecJS::RuntimeUnavailable)
from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/execjs-2.5.2/lib/execjs.rb:5:in `<module:ExecJS>'
from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/execjs-2.5.2/lib/execjs.rb:4:in `<top (required)>'
from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/uglifier-2.7.1/lib/uglifier.rb:3:in `require'
from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/uglifier-2.7.1/lib/uglifier.rb:3:in `<top (required)>'
from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/bundler-1.9.9/lib/bundler/runtime.rb:76:in `require'
from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/bundler-1.9.9/lib/bundler/runtime.rb:76:in `block (2 levels) in require'
from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/bundler-1.9.9/lib/bundler/runtime.rb:72:in `each'
from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/bundler-1.9.9/lib/bundler/runtime.rb:72:in `block in require'
from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/bundler-1.9.9/lib/bundler/runtime.rb:61:in `each'
from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/bundler-1.9.9/lib/bundler/runtime.rb:61:in `require'
from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/bundler-1.9.9/lib/bundler.rb:134:in `require'
from /home/sky/testapp/config/application.rb:7:in `<top (required)>'
from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/railties-4.2.1/lib/rails/commands/commands_tasks.rb:78:in `require'
from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/railties-4.2.1/lib/rails/commands/commands_tasks.rb:78:in `block in server'
from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/railties-4.2.1/lib/rails/commands/commands_tasks.rb:75:in `tap'
from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/railties-4.2.1/lib/rails/commands/commands_tasks.rb:75:in `server'
from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/railties-4.2.1/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/railties-4.2.1/lib/rails/commands.rb:17:in `<top (required)>'
from /home/sky/testapp/bin/rails:8:in `require'
from /home/sky/testapp/bin/rails:8:in `<top (required)>'
from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/spring-1.3.6/lib/spring/client/rails.rb:28:in `load'
from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/spring-1.3.6/lib/spring/client/rails.rb:28:in `call'
from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/spring-1.3.6/lib/spring/client/command.rb:7:in `call'
from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/spring-1.3.6/lib/spring/client.rb:26:in `run'
from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/spring-1.3.6/bin/spring:48:in `<top (required)>'
from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/spring-1.3.6/lib/spring/binstub.rb:11:in `load'
from /home/sky/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/spring-1.3.6/lib/spring/binstub.rb:11:in `<top (required)>'
from /home/sky/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
from /home/sky/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
from /home/sky/testapp/bin/spring:13:in `<top (required)>'
from bin/rails:3:in `load'
from bin/rails:3:in `<main>'
what do?
A: You should ensure that you have a JS runtime declared in your Gemfile.
Try adding:
gem 'therubyracer'
or
gem 'execjs'
to your Gemfile and run:
bundle install
A: As mentioned above you need a JavaScript runtime. If you are unsure of which to choose, I've always been told to use Node.js
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30516166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: New file created inside Django App to seed data I've created an application inside my django project called SeedData. I've added then a file called import_data.py where I will be reading csv files and adding them to my database.
-SeedData
--__pycache__
--migrations
--__init__.py
--admin.py
--apps.py
--import_data.py
-- etc..
But whenever i do the following:
from Product.models import Product
from Category.models import Category
from SubCategory.models import SubCategory
from Brand.models import Brand
import pandas as pd
I get this error
File "C:\Users\...\SeedData\import_data.py", line 9, in <module>
from Product.models import Product
ModuleNotFoundError: No module named 'Product'
It's the same for Category, SubCategory and Brand.
I'd also like to say that the project is fully functional and all the mentioned projects above works perfectly fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66731887",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is this if statement correct, or is it redundant? I've a simple question about if statement in Objective - C.
Is this if statement correct, or is it redundant and I don't need to specify ==YES ?
NSNumber *boolean = [NSNumber numberWithBool:YES];
if (boolean == YES) ...
thanks
A: You compare pointer and integer, which won't lead you to the result you want.
Example:
NSNumber *boolean1 = [NSNumber numberWithBool:YES];
if (boolean1) {
// true
}
NSNumber *boolean2 = [NSNumber numberWithBool:NO];
if (boolean2) {
// this is also true
}
if ([boolean1 boolValue] && ![boolean2 boolValue]) {
// true
}
A: No, it isn't correct and it isn't going to generate the output you think it is. NSNumber * boolean is a pointer to an object in memory while YES is a scalar value; they should not be compared with ==.
If you type this code you'll also get the following warning:
The correct way to do it would be:
NSNumber *boolean = [NSNumber numberWithBool:YES];
if ( [boolean boolValue] ) {
// do something
}
But this statement itself does not make much sense, since you should be comparing the BOOLs and not NSNumber -- there is no need to use the NSNumber in there.
A: This won't work. An instance of NSBoolean is an object, and will be non-NULL whether YES or NO.
There's two good ways to check the value of a NSBoolean.
The first is to use boolValue:
NSNumber *boolean = [NSNumber numberWithBool:YES];
if ([boolean boolValue] == YES) ...
if ([boolean boolValue]) ... // simpler
The second is to use the identity of the object returned:
NSNumber *boolean = [NSNumber numberWithBool:YES];
if (boolean == (id)kCFBooleanTrue) ...
The latter is faster; it relies on there being only one each of NSBoolean YES and NSBoolean NO on the system. These have the same values as kCFBooleanTrue and kCFBooleanFalse. I've read this is safe forever, but I'm not sure it's part of Apple's published documentation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7132454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Why does regex require triple backslash to match a single backslash? I was trying to match a backslash using regex and thought that this could be done by using two double backslashes, using the former to escape the latter. However, when I run the code
path_str = r"\Animal_1-"
Match_backslash = re.search("[\\]", path_str)
print(Match_backslash)
I get the error message:
error: unterminated character set at position 0
But, when I use triple backslash:
path_str = r"\Animal_1-"
Match_backslash = re.search("[\\\]", path_str)
print(Match_backslash)
it for some reason works, can anyone explain why triple backslash is needed and why double backslash isn´t sufficient?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74732865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Start text animation on button click, clear and start animation again if button is clicked again I've taken this snippet of code from a project I'm working on with a few friends and I'm looking for a bit of knowledge on getting a function to not activate until a button is clicked. Also, If the animation could be restarted every time the button is clicked, that would be great.
I made an attempt at using:
// $('#savebtn').onClick(function(){
// $('#setupTypewriter').addClass('typewriter');
// });
and
$('#savebtn').onClick(function(){
setupTypewriter('typewriter');
});
in the js file to no avail. I'm probably missing something severely obvious that a second set of eyes will pick up as I am an amateur coder.
Also, if you notice random elements/code calling to something else in the snippets I've posted, they're probably unnecessary but I did just rip all of this code out of the bigger project like I mentioned :P
function setupTypewriter(t) {
var HTML = t.innerHTML;
t.innerHTML = "";
var cursorPosition = 0,
tag = "",
writingTag = false,
tagOpen = false,
typeSpeed = 1,
tempTypeSpeed = 0;
var type = function() {
if (writingTag === true) {
tag += HTML[cursorPosition];
}
if (HTML[cursorPosition] === "<") {
tempTypeSpeed = 0;
if (tagOpen) {
tagOpen = false;
writingTag = true;
} else {
tag = "";
tagOpen = true;
writingTag = true;
tag += HTML[cursorPosition];
}
}
if (!writingTag && tagOpen) {
tag.innerHTML += HTML[cursorPosition];
}
if (!writingTag && !tagOpen) {
if (HTML[cursorPosition] === " ") {
tempTypeSpeed = 0;
} else {
tempTypeSpeed = (Math.random() * typeSpeed) + 0;
}
t.innerHTML += HTML[cursorPosition];
}
if (writingTag === true && HTML[cursorPosition] === ">") {
tempTypeSpeed = (Math.random() * typeSpeed) + 0;
writingTag = false;
if (tagOpen) {
var newSpan = document.createElement("span");
t.appendChild(newSpan);
newSpan.innerHTML = tag;
tag = newSpan.firstChild;
}
}
cursorPosition += 1;
if (cursorPosition < HTML.length - 1) {
setTimeout(type, tempTypeSpeed);
}
};
return {
type: type
};
}
var typer = document.getElementById('typewriter');
typewriter = setupTypewriter(typewriter);
typewriter.type();
.colbtns {
left: 115px;
bottom: 37.5px;
position: relative;
width: 140px;
z-index: 3;
}
.colbtnd {
left: 115px;
bottom: 37px;
position: relative;
width: 140px;
z-index: 3;
}
.ecutext-container {
background-color: #000000;
border-radius: .25rem;
position: relative;
height: 235px;
width: 380px;
left: 413px;
bottom: 0px;
z-index: 1;
}
.col {
color: #fff;
}
.text-muted {
color: #fff!important;
}
.btn-success {
color: #fff;
background-color: #1a75ff;
border-color: #1a75ff;
}
.btn-success:hover {
color: #fff;
background-color: #005ce6;
border-color: #005ce6;
}
.btn-success:active {
color: #fff;
background-color: #005ce6;
border-color: #005ce6;
}
.btn-success:focus {
color: #fff;
background-color: #005ce6;
border-color: #005ce6;
}
.ui-widget-content {
border: 1px solid;
border-color: #fff;
background-color: #1a75ff;
background: none;
}
.ui-state-default,
.ui-widget-content .ui-state-default,
.ui-widget-header .ui-state-default {
border: 1px solid #fff;
}
.slider {
border: 1px solid;
border-color: #fff;
background-color: #fff;
}
#boost {
color: #fff;
}
.var-highlight {
color: #008ae6;
}
.string-highlight {
color: #008ae6;
}
#typewriter {
padding-top: 5px;
font-size: 10px;
color: #fff;
margin: 0;
overflow: hidden;
font-family: "Lucida Sans Typewriter", "Lucida Console", Monaco, "Bitstream Vera Sans Mono", monospace;
&:after {
content: "|";
animation: blink 500ms linear infinite alternate;
}
}
@-webkit-keyframes blink {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
@-moz-keyframes blink {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
@keyframes blink {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js" crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="index.css">
<link href="https://code.jquery.com/ui/1.10.4/themes/ui-darkness/jquery-ui.css" rel="stylesheet">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="custom.css">
<link rel="stylesheet" type="text/css" href="textanim.css">
</head>
<body>
<div class="ecutext-container">
<pre id="typewriter">
<span class="var-highlight">Init</span> lmECU.exe = {
<span class="string">--------------------------------</span>
lmECU:\ <span class="string">validating engineer key</span>
lmECU:\ <span class="string">validation success</span>
lmECU:\ <span class="string">accessing sensors</span>
lmECU:\ <span class="string">parsing senslog.xml</span>
lmECU-senslog:\ <span class="string-highlight">running diagnostics</span>
<span class="string-highlight">- {0 faults detected</span>
lmECU:\ <span class="string">applying Modifications...</span>
lmECU:\ <span class="string">generating senslog.xml</span>
lmECU:\ <span class="string">parsing senslog.xml</span>
lmECU-senslog:\ <span class="string-highlight">running diagnostics</span>
<span class="string-highlight">- {0 faults detected</span>
lmECU:\ <span class="string">ECU remap successful</span>
lmECU:\ <span class="string">end lmECU.exe</span>
<br></br>
</pre>
</div>
<div class="savebtn">
<div class="colbtns"><button class="btn btn-success form-control" id="savebtn">SAVE</button></div>
</div>
<div class="colbtnd"><button class="btn btn-success form-control" id="defaultbtn">DEFAULT</button></div>
</div>
</div>
</div>
<script src="config.js"></script>
<script src="index.js"></script>
<script src="textanim.js"></script>
</body>
</html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56749773",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dropzone JS not able to upload file I'm using Dropzone JS and from my frontend (localhost:9000), I'm calling a upload.php where I get the images and then upload it on the backend (localhost:80)in a folder.
here is my html :
<form action="localhost:80/ProgettoTimelinegit/api/upload.php" class="dropzone" id="my-dropzone" enctype="multipart/form-data">
</form>
my javascript :
Dropzone.autoDiscover = false;
$("#my-dropzone").options = {
maxFilesize: 4, // MB
url:"http://localhost:80/ProgettoTimelinegit/api/upload.php",
addRemoveLinks : true,
uploadMultiple:true,
paramName:"file",
parallelUploads: 2,
maxFiles: 10,
autoProcessQueue: true,
headers: {
// remove Cache-Control and X-Requested-With
// to be sent along with the request
'Cache-Control': null,
'X-Requested-With': null
}
};
and upload.php
$ds = DIRECTORY_SEPARATOR; //1
$storeFolder = '/xampp/htdocs/images/'; //2
if(!empty($_FILES)) {
// START // CREATE DESTINATION FOLDER
define('DESTINATION_FOLDER','../api/upload/');
if (!@file_exists(DESTINATION_FOLDER)) {
if (!mkdir(DESTINATION_FOLDER, 0777, true)) {
$errors[] = "Destination folder does not exist or no permissions to see it.";
}
// END // CREATE DESTINATION FOLDER
$temp = $_FILES['file[]']['tmp_name'];
$dir_seperator = "fold/";
//$destination_path = dirname(__FILE__).$dir_seperator.$folder.$dir_seperator;
$destination_path = DESTINATION_FOLDER.$dir_seperator;
$target_path = $destination_path.(rand(10000, 99999)."_".$_FILES['file']['name']);
move_uploaded_file($temp, $target_path);
}
}
If I upload the image, in console (for every browser)
it
POST localhost:80/ProgettoTimelinegit/api/upload.php net::ERR_UNKNOWN_URL_SCHEME
What I want to do is to load the image in localhost:80/progettoTimelinegit/api/upload/
A: Your upload.php-file is already in the api-folder, just change this line:
define('DESTINATION_FOLDER','../api/upload/');
to:
define('DESTINATION_FOLDER','upload/');
And it should work. You have quite a few weird variables, unused variables etc., so there might be other things wrong as well.
A: I've managed to make it work, it costed me 4 days of work but now it works :
you have to be careful in some part of your code :
Html
Do not add enctype="multipart/form-data" or if you do remember to add rewrite rule
"multipart/form-data" make dropzone AUTOMATICALLY set Options REQUEST
virtual host or a .ini / .htAccess with Xampp/wampp/vagrant
VirtualHost *:80>
DocumentRoot "#folderOfyourWebsite"
ServerName yoursite.name
<Directory "#path To The HTML of Your Index Page">
Options Indexes FollowSymLinks MultiViews ExecCGI
AllowOverride Authconfig FileInfo
Require all granted
</Directory>
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header set Access-Control-Max-Age "1000"
Header set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
</VirtualHost>
In rewrite engine we're telling him : ok,if you receive An options request, rewrite it with a 200 (successfull post)
So your TO-DO list can be recapped with this :
*
*check your html dropzone Form, if you have enctype you'll have to write
a Rewrite Rule in your vhost or htaccess
*Did you write a Rewrite Rule in order to make cors Successfull?
*Make sure your path have all permissions and your upload folder exists
*Check your static paths wherever you are doing an http request
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40586296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Vue : How to use async await accordingly in a function array of which can have two functions for Promise.all? I want to use await where I marked [here] in 1.vue. However, if I use await there then it emits error Unexpected reserved word 'await'. If I want to use async useFunctionToAllServers() sequentially after [Promise.all] then, where to put async or how to change async useFunctionToAllServers()? Or need to change submitToTheOthers()?
1.vue
<template>
<div>
<label for="imgUpload">
<button class="point">upload</button>
</label>
<input
type="file"
class="input-file"
ref="logo1"
id="imgUpload"
@change="sendFile('logo')"
/>
<div v-if="imageData" class="imgBox">
<img :src="imageData" />
</div>
<label for="imgUpload">
<button class="point">upload1</button>
</label>
<input
type="file"
class="input-file"
ref="logo1"
id="imgUpload"
@change="sendFile('logo1')"
/>
<div v-if="imageData1" class="imgBox">
<img :src="imageData1" />
</div>
<button @click="useFunctionToAllServers">BUTTON</button>
</div>
</template>
<script>
import {
updateGeneralInfo,
createUploadToOther,
updateGeneralInfoToOther,
} from '@/2'
export default {
data() {
return {
filename: '',
filename1: '',
originalFilename: '',
originalFilename1: '',
imageData: '',
imageData1: '',
serverNames: ['a server', 'b server'],
idxs: [0, 1],
serverFullAddress:['http://a.url', 'http://b.url'],
serverResCheck:[],
isLogoChanged:false,
isLogo1Changed:false,
}
},
methods: {
sendFile(type) {
let file = ''
if (type == 'logo') {
file = this.$refs.logo.files[0]
} else {
file = this.$refs.logo1.files[0]
}
const reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = (e) => {
if (type == 'logo') {
this.imageData = e.target.result
} else {
this.imageData1 = e.target.result
}
}
},
sendFileToOther(type, serverFullURL) {
let file = ''
if (type == 'logo') {
file = this.$refs.logo.files[0]
this.originalFilename = this.$refs.logo.files[0].name
} else {
file = this.$refs.logo1.files[0]
this.originalFilename1 = this.$refs.logo1.files[0].name
}
const reader = new FileReader()
reader.readAsDataURL(file)
const formdata = new FormData()
formdata.append('logo', file)
formdata.append('serverURL', serverFullURL)
return createUploadToOther(formdata)
},
async useFunctionToAllServers() {
let data = {
foo: this.foo,
bar: this.bar,
}
await updateGeneralInfo(data).then().catch()
await Promise.all(this.submitToTheOthers()).catch((err) =>{ // [Promise.all]
console.log('Promise.all err>>', err)
});
let notWorkingServers = []
for(let i=0; i< this.idxs.length ; i++){
if(!this.serverResCheck[i]){
notWorkingServers.push(this.serverNames[i])
}
}
if(Array.isArray(notWorkingServers) && notWorkingServers.length == 0){
alert('not working : ', notWorkingServers)
}else{
alert('all server works')
}
},
submitToTheOthers(){
let data = {
foo: this.foo,
bar: this.bar,
}
let logoData ={}
if(this.originalFilename){
data.logo = this.originalFilename
logoData.logo = true
}else if(this.isLogoChanged){
data.logo = this.logo
}
if(this.originalFilename1){
data.logo1 = this.originalFilename1
logoData.logo1 = true
}else if(this.isLogo1Changed){
data.logo1 = this.logo1
}
return this.idxs.map( (_entry, i) => {
return updateGeneralInfoToOther(1, data, this.serverFullAddress[i]).then((res) => { // [here2]
if (res.status == 200) {
this.serverResCheck[i] = true
if(logoData.logo){
this.sendFileToOther('logo', this.serverFullAddress[i]).then((res) => { // [here]
}).catch((err) => {
this.serverResCheck[i] = false
})
}
if(logoData.logo1){
this.sendFileToOther('logo1', this.serverFullAddress[i]).then((res) =>{ // [here]
}).catch((err) => {
this.serverResCheck[i] = false
})
}
}else{
this.serverResCheck[i] = false
}
}).catch((err) => {
this.serverResCheck[i] = false
})
})
},
},
}
</script>
2.js
import axios from 'axios'
export const headers = {
'Content-Type': 'application/json',
'header1' : 'header1',
'header2' : 'header2',
}
export function updateGeneralInfoToOther(id, data, serverAddress) {
data.serverAddress = serverAddress
return axios.put(`/u/r/l/${id}`, data, { headers })
}
export function updateGeneralInfo(id, data) {
return axios.put(`/extra/u/r/l/${id}`, data, { headers })
}
export function createUploadToOther(data) {
return axios.post('/u/r/l', data, { headers })
}
A: To use await in those callbacks, each callback function itself needs to be async:
export default {
methods: {
submitToTheOthers(){
⋮
return this.idxs.map( (_entry, i) => {
return updateGeneralInfoToOther(1, data, this.serverFullAddress[i]).then(async (res) => { // [here2]
✅
await someAsyncMethod()
if (res.status == 200) {
⋮
if (logoData.logo) {
this.sendFileToOther(/*...*/).then(async (res) => { // [here]
✅
await someAsyncMethod()
})
}
if (logoData.logo1) {
this.sendFileToOther(/*...*/).then(async (res) => { // [here]
✅
await someAsyncMethod()
})
}
}
})
})
},
},
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70343157",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to get a remote computer process and waitForInputIdle over it? c# So I would like to run something similar to the following on a remote computer:
process = Process.Start("notepad.exe");
process.WaitForInputIdle();
I have no problem connecting via WMI, executing processes and running query on them but I cant find a way to WaitForInputIdle on these remote processes. (or any other method that tells me that the process has finished loading)
Any ideas how it can be done?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42346179",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Remove changes from a commit hash in a given file git I have a 3 month old commit, lets say commit A which touchs 3 files
Over the last 3 months, a lot more commits have gone in, some of which have added new code below changes from commit A
I want to remove (not revert) the changes from commit A in 1 of the 3 files.
remove as in blank line instead of code
I tried
git show < commit hash of A > file_path | git apply -R -3
this removes extra code (which is outside the scope of commit A: details below if interested)
One way i can think of is using git blame on file, wherever hash matches, remove the lines
but seems to be very iterative process and time consuming.
Any pointers would be helpful..
Thanks in advance
Extra code removed from file which is out of scope of commit A:
*
*Commit A was added at the end of file
*New commits added more code after commit A (below changes from commit A) at the end of file
*now when we reverse the changes in commit A (using git apply -R -3), it cleans from start of commit A till end of file because to git, the code was originally added at the end of file
A: I would still try git-revert to remove lines in commit A.
Next you want to restore the other two files which don’t need revert. git checkout HEAD^ - file1 file2 is the way to recover to the original file content.
Finally commit amend to overwrite nicer message than “Revert …”
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69935733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a limit to the file size you can upload with GWT FormPanel and FileUpload? I recall seeing somewhere that there was a limit of 10MB upload in GWT when using FormPanel and FileUpload, but I can't seem to find any reference to a limit now. Is there one?
A: There is no reasonable limit* on the client side (or in GWT) of a <input type=file>. That said, it is quite likely that your server has a limit on the size of an upload, so be sure to configure whatever server (and optionally any reverse proxy in use) to use a high enough limit.
* technically, it appears there is a limit - the file cannot be larger than 2^64 bytes (about 18 million terabytes), at least according to MDN.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49235218",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android Switch widget inside AlertDialog, not showing thumb image (on/off instead) I have a rather simple dialog with an ArrayAdapter inside. The adapter inflates the following layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp">
<TextView
android:id="@+id/txt_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_toStartOf="@+id/calendar_selection_switch"
android:ellipsize="end"
android:text="test test"
android:textColor="@color/black"
android:textSize="20sp" />
<Switch
android:id="@id/calendar_selection_switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_gravity="end|center_vertical"
android:layout_marginStart="10dp"
android:minHeight="40dp"
android:minWidth="80dp" />
</RelativeLayout>
When I show this dialog, this is what I get:
Notice the words "on" and "off" in tiny letters. No custom graphics or classes here, just out-of-the-box.
When I do this in an Activity I don't get that. Instead I get the normal thumb image, which is exactly what I want:
Even if I grow the size of the Switch it doesn't make any difference. It just makes the list's rows larger.
Here's the code to build and show the dialog:
AlertDialog.Builder builderSingle = new AlertDialog.Builder(this);
builderSingle.setTitle(R.string.cal_title);
builderSingle.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
final CalendarListAdapter cla = new CalendarListAdapter(this, calendarList, null);
builderSingle.setAdapter(cla, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
cla.toggleSelect(which);
}
});
builderSingle.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (saveCalendars(cla)) {
dialog.dismiss();
}
}
});
AlertDialog dialog = builderSingle.create();
dialog.show();
The CalendarListAdapter is a simple ArrayAdapter:
public class CalendarListAdapter extends ArrayAdapter<Calendar> {
There's no difference between the Activity version and the AlertDialog version for this class though.
I'm puzzled. What I do here is not very complicated. Please help.
A: Try this:
<Switch
android:id="@+id/calendar_selection_switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_gravity="end|center_vertical"
android:layout_marginStart="10dp"
android:minHeight="40dp"
android:minWidth="80dp"
android:textOn=""
android:textOff=""
android:switchMinWidth="48.0sp"
android:thumb="@drawable/switch_selector"
android:track="@drawable/switch_track"
android:checked="false"/>
switch_selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true">
<shape
android:shape="rectangle"
android:visible="true"
android:useLevel="false">
<gradient
android:startColor="@color/white"
android:endColor="@color/white"
android:angle="270"/>
<corners
android:radius="14.0sp"/>
<size
android:width="28.0sp"
android:height="28.0sp" />
<stroke
android:width="4.0sp"
android:color="#11000000"/>
</shape>
</item>
<item android:state_checked="false">
<shape
android:shape="rectangle"
android:visible="true"
android:dither="true"
android:useLevel="false">
<gradient
android:startColor="@color/white"
android:endColor="@color/white"
android:angle="270"/>
<corners
android:radius="16.0sp"/>
<size
android:width="28.0sp"
android:height="28.0sp" />
<stroke
android:width="2.0sp"
android:color="#11000000"/>
</shape>
</item>
</selector>
switch_track.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
android:visible="true"
android:useLevel="false">
<gradient
android:startColor="@color/white"
android:endColor="@color/white"
android:angle="270"/>
<stroke
android:width="2.0sp"
android:color="#11000000"/>
<corners
android:radius="14.0sp"/>
<size
android:width="42.0sp"
android:height="28.0sp" />
</shape>
Then in code you can do:
aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
aSwitch.setTrackResource(R.drawable.switch_track_off);
} else {
aSwitch.setTrackResource(R.drawable.switch_track);
}
}
});
switch_track_off.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
android:visible="true"
android:useLevel="false">
<gradient
android:startColor="#00A4FD"
android:endColor="#00A4FD"
android:angle="270"/>
<stroke
android:width="2.0sp"
android:color="#00A4FC"/>
<corners
android:radius="14.0sp"/>
<size
android:width="42.0sp"
android:height="28.0sp" />
</shape>
You can change the colors and other styles as you wish.
As far as I know this is the only reliable way to make Switch look and feel same in all Android versions anywhere in the app.
Please leave a comment if there is any better suggestion.
A: Use this
<Switch
android:id="@+id/switchCalls"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:textOff=""
android:textOn=""
/>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46965393",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Redshift query results incorrect before VACUUM When Redshift uses an index to run a query (say counts), does it exclude counting the rows in the unsorted region?
I had copied a lot a data using the COPY command, but did not VACUUM the table afterwords. On running my query (involving joins with several tables), the results of the query were wrong - the newly copied rows in the unsorted region weren't counted.
Then, after vacuuming the table, the query began returning the correct results. Is this expected behavior, or is this a bug introduced by Amazon?
A: Vacuuming won't have any effect on COPYed rows, which are effectively inserts. Vacuum physically deletes rows previously deleted with an SQL delete statement, which only marks the rows as deleted, so they don't participate in subsequent queries but still consume disk space.
Redshift is an eventually consistent database, so even if your COPY command had completed, the rows may not yet be visible to queries.
Running vacuum is basically a defrag, which requires all rows to be reorganized. This (probably) causes the table to be brought into a consistent state, ie all rows are visible to queries.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46498667",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Google Chrome moves div out of document flow when using internal links Look at the two links below in Chrome:
Working: http://www.datesphere.com/boards/showthread.php?tid=46
Broken: http://www.datesphere.com/boards/showthread.php?tid=46&pid=345#pid345
Notice how the navigation breadcrumb and "thread rating" section render correctly in the "working" link, but are jammed up under the user panel in the "broken" link. I've spent a lot of time trying to figure out why this is happening (asked on mybb.com and a couple other forums, reported a bug to Google Chrome team, etc.) but haven't had any luck, so am hoping Stackoverflow comes through once again.
Here's what I know:
*
*This only happens in Google Chrome, and as far as I can tell only on permalinked posts where you have an internal link -- pages ending with "pid=[number]#pid[number]"
*I believe it's happening because the "wrapper" div that starts the content section is being rendered up at the same place as the user panel instead of below it, where it belongs in the document flow.
*Adding a clearing div ("style=clear:both;") before the "content" div fixes the problem in Chrome Developer Tools, but when you add it to the actual code nothing happens.
This is the most baffling and frustrating thing I've come across in html / css. Does anyone have any idea why this is happening, and how I might fix it?
Thanks,
Chris
A: Here's your culprit.
#content {
overflow: hidden;
}
This is exactly the reason why you shouldn't use overflow hidden for clearing floats. Anchor links will cause overflowed elements to scroll in certain situations.
Look into clearfix for clearing floats instead.
Run this javascript in your console for a demonstration on the problem:
document.getElementById("content").scrollTop = 0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5504724",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is there an easy way to include RackTest methods in Capybara tests? Capybara 2 removed these and suggests to separate them, but we have some situations where we'd like to use both in a test (enabling an api key through the view, then hitting the api, etc).
I tried including include ::Rack::Test::Methods but I'm getting:
undefined local variable or method `app' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1:0x007fb737932ba0>
A: I ran into the same error using Rails and RSpec to test an API. I found a helpful blog post for Rails 2.3: http://eddorre.com/posts/using-rack-test-and-rspec-to-test-a-restful-api-in-rails-23x
module ApiHelper
require 'rack/test'
include Rack::Test::Methods
def app
ActionController::Dispatcher.new
end
end
My solution for Rails 3.2 was (look in config.ru for MyAppName):
module ApiHelper
require 'rack/test'
include Rack::Test::Methods
def app
MyAppName::Application
end
end
A: try this
def app
Rails.application
end
A: For anyone else banging their heads against the wall getting the "NameError: undefined local variable or method `app'" error. It also happens when you are running all your tests at once (multiple files) and one of them does an include Rack::Test::Methods - the include "infects" the other tests. So the symptom is that all tests pass when the files are run individually, but then they fail with the "no app" error when run together. At least this happens with rails 3.0.9 and rspec 3.0
The solution to this issue is to remove the includes. Alternatively you might try something like @ultrasaurus' answer to make sure the includes are properly contained to only the examples that need it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15978587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: java.lang.RuntimeException: Could not inject members I'm trying since some time to get Arquillian running with JPA.
I had some DAO tests working, but while a continued to write the remaining tests this error started and affected both the ones I was writing and the ones that were fine before.
java.lang.RuntimeException: Could not inject members
at org.jboss.arquillian.testenricher.cdi.CDIInjectionEnricher.injectClass(CDIInjectionEnricher.java:117)
at org.jboss.arquillian.testenricher.cdi.CDIInjectionEnricher.enrich(CDIInjectionEnricher.java:71)
at org.jboss.arquillian.test.impl.TestInstanceEnricher.enrich(TestInstanceEnricher.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:103)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:90)
at org.jboss.arquillian.test.impl.TestContextHandler.createSuiteContext(TestContextHandler.java:69)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:95)
at org.jboss.arquillian.test.impl.TestContextHandler.createClassContext(TestContextHandler.java:83)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:95)
at org.jboss.arquillian.test.impl.TestContextHandler.createTestContext(TestContextHandler.java:116)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:95)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:133)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:105)
at org.jboss.arquillian.test.impl.EventTestRunnerAdaptor.before(EventTestRunnerAdaptor.java:115)
at org.jboss.arquillian.junit.Arquillian$4.evaluate(Arquillian.java:200)
at org.jboss.arquillian.junit.Arquillian.multiExecute(Arquillian.java:350)
at org.jboss.arquillian.junit.Arquillian.access$200(Arquillian.java:54)
at org.jboss.arquillian.junit.Arquillian$5.evaluate(Arquillian.java:215)
at org.jboss.arquillian.junit.Arquillian$7$1.invoke(Arquillian.java:279)
at org.jboss.arquillian.container.test.impl.execution.BeforeLifecycleEventExecuter.on(BeforeLifecycleEventExecuter.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:103)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:90)
at org.jboss.arquillian.test.impl.TestContextHandler.createSuiteContext(TestContextHandler.java:69)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:95)
at org.jboss.arquillian.test.impl.TestContextHandler.createClassContext(TestContextHandler.java:83)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:95)
at org.jboss.arquillian.test.impl.TestContextHandler.createTestContext(TestContextHandler.java:116)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:95)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:133)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:105)
at org.jboss.arquillian.test.impl.EventTestRunnerAdaptor.fireCustomLifecycle(EventTestRunnerAdaptor.java:159)
at org.jboss.arquillian.junit.Arquillian$7.evaluate(Arquillian.java:273)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.jboss.arquillian.junit.Arquillian$2.evaluate(Arquillian.java:166)
at org.jboss.arquillian.junit.Arquillian.multiExecute(Arquillian.java:350)
at org.jboss.arquillian.junit.Arquillian.access$200(Arquillian.java:54)
at org.jboss.arquillian.junit.Arquillian$3.evaluate(Arquillian.java:177)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.jboss.arquillian.junit.Arquillian.run(Arquillian.java:115)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at org.jboss.arquillian.junit.container.JUnitTestRunner.execute(JUnitTestRunner.java:61)
at org.jboss.arquillian.protocol.servlet.runner.ServletTestRunner.executeTest(ServletTestRunner.java:139)
at org.jboss.arquillian.protocol.servlet.runner.ServletTestRunner.execute(ServletTestRunner.java:117)
at org.jboss.arquillian.protocol.servlet.runner.ServletTestRunner.doGet(ServletTestRunner.java:86)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at io.undertow.servlet.handlers.ServletChain$1.handleRequest(ServletChain.java:68)
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:132)
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler.handleRequest(GlobalRequestControllerHandler.java:68)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
at org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1514)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1514)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1514)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1514)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1514)
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:360)
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:830)
at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1985)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1487)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1349)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.jboss.arquillian.test.spi.ArquillianProxyException: org.jboss.weld.exceptions.IllegalArgumentException : WELD-001408: Unsatisfied dependencies for type MorphologicalAnalysisPersistenceFacade with qualifiers @Default
at injection point [BackedAnnotatedField] @Inject br.com.cpmh.beacon.persistence.MorphologicalAnalysisPersistenceFacadeTest.morphologicalAnalysisPersistenceFacade
at br.com.cpmh.beacon.persistence.MorphologicalAnalysisPersistenceFacadeTest.morphologicalAnalysisPersistenceFacade(MorphologicalAnalysisPersistenceFacadeTest.java:0)
[Proxied because : Original exception caused: class java.lang.ClassNotFoundException: org.jboss.weld.exceptions.IllegalArgumentException]
at org.jboss.weld.manager.InjectionTargetFactoryImpl.createInjectionTarget(InjectionTargetFactoryImpl.java:83)
at org.jboss.weld.manager.InjectionTargetFactoryImpl.createInjectionTarget(InjectionTargetFactoryImpl.java:70)
at org.jboss.weld.manager.BeanManagerImpl.createInjectionTarget(BeanManagerImpl.java:1025)
at org.jboss.weld.util.ForwardingBeanManager.createInjectionTarget(ForwardingBeanManager.java:204)
at org.jboss.arquillian.testenricher.cdi.CDIInjectionEnricher.injectNonContextualInstance(CDIInjectionEnricher.java:124)
at org.jboss.arquillian.testenricher.cdi.CDIInjectionEnricher.injectClass(CDIInjectionEnricher.java:110)
... 135 more
Caused by: org.jboss.arquillian.test.spi.ArquillianProxyException: org.jboss.weld.exceptions.DeploymentException : WELD-001408: Unsatisfied dependencies for type MorphologicalAnalysisPersistenceFacade with qualifiers @Default
at injection point [BackedAnnotatedField] @Inject br.com.cpmh.beacon.persistence.MorphologicalAnalysisPersistenceFacadeTest.morphologicalAnalysisPersistenceFacade
at br.com.cpmh.beacon.persistence.MorphologicalAnalysisPersistenceFacadeTest.morphologicalAnalysisPersistenceFacade(MorphologicalAnalysisPersistenceFacadeTest.java:0)
[Proxied because : Original exception caused: class java.lang.ClassNotFoundException: org.jboss.weld.exceptions.DeploymentException]
at org.jboss.weld.bootstrap.Validator.validateInjectionPointForDeploymentProblems(Validator.java:378)
at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:290)
at org.jboss.weld.bootstrap.Validator.validateProducer(Validator.java:425)
at org.jboss.weld.injection.producer.InjectionTargetService.validateProducer(InjectionTargetService.java:36)
at org.jboss.weld.manager.InjectionTargetFactoryImpl.validate(InjectionTargetFactoryImpl.java:153)
at org.jboss.weld.manager.InjectionTargetFactoryImpl.createInjectionTarget(InjectionTargetFactoryImpl.java:81)
... 140 more
My tests look all the same:
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.UserTransaction;
@RunWith(Arquillian.class)
public class MorphologicalAnalysisPersistenceFacadeTest
{
@Inject
MorphologicalAnalysisPersistenceFacade morphologicalAnalysisPersistenceFacade;
@Inject
private UserTransaction userTransaction;
@PersistenceContext(unitName = "BeaconAnalysis")
EntityManager entityManager;
@Deployment
public static Archive<?> createDeployment()
{
JavaArchive archive = ShrinkWrap.create(JavaArchive.class, "morphological-analysis-data-access-object-test.jar");
archive.addPackages(true, "br.com.cpmh.beacon");
archive.addAsResource("test-persistence.xml", "META-INF/persistence.xml");
archive.addAsResource(EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml"));
return archive;
}
@Before
public void setUp() throws Exception
{
//morphologicalAnalysisPersistenceFacade = new MorphologicalAnalysisPersistenceFacade();
}
@After
public void tearDown() throws Exception
{
}
@Test
public void create()
{
}
A: I think the most important part in this stacktrace is:
WELD-001408: Unsatisfied dependencies for type MorphologicalAnalysisPersistenceFacade
This usually means that not all required dependencies for MorphologicalAnalysisPersistenceFacade are deployed to the Weld-container. To debug this I would suggest temporarily rewriting your deployment method to:
@Deployment
public static Archive<?> createDeployment() {
JavaArchive archive = ShrinkWrap.create(JavaArchive.class, "morphological-analysis-data-access-object-test.jar")
.addPackages(true, "br.com.cpmh.beacon")
.addAsResource("test-persistence.xml", "META-INF/persistence.xml")
.addAsResource(EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml"));
// print all included packages
System.out.println(archive.toString(true));
return archive;
}
This will print out all the classes which are deployed to the container. With that, you can investigate if any required class does not get deployed and include that class or package manually in your createDeployment method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51498210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: OAuth 2.0 In Microservices: When a resource server communicates with another resource server Currently, the user is passing the access token, with [Scope A] to the web portal.
Once the user requests to view a resource, the token is passed to the resource server [Web App A] to obtain the resource. However, to obtain the resource, the resource server must communicate with [Web App B] to obtain a subset of information, therefore it requires [Scope B]. Since the user only authorized [Scope A] the call will fail.
Below are scenarios of fixes that could be applied:
*
*Scenario 1: The user is requested to authorize [Scope A] and [Scope B]. The problem here is that the user might not want the [Web Portal] to access [Web App B] directly.
*Scenario 2: [Web App A] becomes the client of [Web App B], using it's own access token to request resources from [Web App B]. The problem here is that the user context is lost.
I am looking for the standard solution, I might be doing something wrong from my end.
A few other questions I would like to ask:
*
*Should the access token be passed around microservices?
*Should there be a different authorization framework for internal requests?
A: If these are different applications (to the user) then yes, user should be asked to confirm if he is willing to authorise A to access B. If he does not want to that, then A has no biz talking to B on behalf of the said user.
If this is set of microservices then user need to interact with via Web Page and any subsequent calls if being made to n different services is something that user should not be concerned with. As such he is trusting the web page and asking web page for some data. You have set of microservices sitting behind to answer that, is not of concern for user and his token.
So you can make use of second option. Talking about user context, well that can shared in some other forms like passing via headers.
Should the access token be passed around microservices?
Yes, there should be no harm in that. It adds to the payload but certainly can be done. Important thing to note is that users access token can be used by services to mimic a user call to another service. If such calls are threat to your design then you should reconsider. But mostly we feel that what ever you do within your boundary is safe and you can trust other services in that boundary and hence can pass it along.
Should there be a different authorization framework for internal requests?
It depends, if you want to separate it for security reason, you can, if you want to do it for load reason you can.
You can also think of stripping tokens at the gateway (verify the token at the entrypoint) and let go off it. For systems where you can trust other services (amongst your microservices) and ensure no on one can access them directly, other than the API gateways, you can just let the token go.
You loose authorization bit, but again our point is we trust services and believe they know what they are doing, so we do not put restrictions to such calls.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52290697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to change the default output folder for generated apk files? When I use the gradle task to create an android .apk file it outputs it the the build\javafxports\android folder of the project (both the regular and unaligned files). I couldn't find a setting to change the output folder.
When I export a jar in eclipse I can specify a destination folder. How can I do that with apk files too?
Here is my build.gradle file:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'org.javafxports:jfxmobile-plugin:1.1.1'
}
}
apply plugin: 'org.javafxports.jfxmobile'
repositories {
jcenter()
maven {
url 'http://nexus.gluonhq.com/nexus/content/repositories/releases'
}
}
mainClassName = 'com.gluonapplication.GluonApplication'
dependencies {
compile 'com.gluonhq:charm:4.0.1'
}
jfxmobile {
downConfig {
version = '3.0.0'
plugins 'display', 'lifecycle', 'statusbar', 'storage'
}
android {
compileSdkVersion = 24
manifest = 'src/android/AndroidManifest.xml'
androidSdk = 'C:/Users/Mark/AppData/Local/Android/sdk'
}
ios {
infoPList = file('src/ios/Default-Info.plist')
forceLinkClasses = [
'com.gluonhq.**.*',
'javax.annotations.**.*',
'javax.inject.**.*',
'javax.json.**.*',
'org.glassfish.json.**.*'
]
}
}
A: The jfxmobile plugin allows changing the path where the apk will be created.
Use installDirectory:
jfxmobile {
downConfig {
version = '3.0.0'
plugins 'display', 'lifecycle', 'statusbar', 'storage'
}
android {
installDirectory = file('/full/path/of/custom/folder')
manifest = 'src/android/AndroidManifest.xml'
}
}
Be aware that the folder should exist before running android task. Currently the plugin manages that for the default installation folder (removing it, and the apk, if exists and creating it again on every run). So you have to do it yourself, otherwise the task will skip it.
EDIT
The list of global variables that are intended to be modified if necessary are here, but the full list of variables currently included in the plugin can be found in the plugin source code.
Variables like installDirectory are used internally by the plugin and they are initialized with a default value, perform some actions like deleting the previous directory and creating it again (so Gradle performs the task). In case of overriding, these actions won't be executed, so you should take care of that yourself (or create a task for that).
A: This works for the standard android plugin to change the directory of the generated APKs:
android {
applicationVariants.all { variant ->
variant.outputs.each { output ->
output.outputFile = file("/some/dir/" + variant.name + "/" + archivesBaseName + ".apk")
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40518285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Location of the built python module Hey people I built caffe module for nvidia jetson tx2 succesfully. But when I import caffe python throws no module named caffe error. I have libcaffe.a libcaffe.so libcaffe.so.1.0.0 under the build directory. Where should I copy these files to make sure that python is able to import module.
A: When I have compiled from source, after running "cmake" I had to:
*
*cd into "python" folder (you shloud see the folder in the path you ran the "cmake") and run "pip install -e ."
*or, you will need to run make install.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64009534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Handling JavaScript exceptions from Silverlight I'm having trouble adding proper exception handling to existing code that makes heavy use of Silverlight - JavaScript interoperability. In this case, my JavaScript can throw an exception that I want to handle meaningfully in Silverlight.
From Silverlight, I'm creating an instance of a JavaScript object, then later I'm calling a method on that object:
public class MyWrapper
{
dynamic _myJSObject;
public MyWrapper()
{
_myJSObject = HtmlPage.Window.CreateInstance("MyJSObject");
}
public int MyMethod()
{
try
{
int result = (int)_myJSObject.MyMethod();
}
catch (Exception ex)
{
// I want to add meaningful exception handling here
}
}
}
Whenever MyJSObject.MyMethod throws an exception, there are two problems:
*
*The browser shows a message that an exception has occurred.
*Information about the exception is not passed to my managed code. Instead I get a RuntimeBinderException which just says "Cannot invoke a non-delegate type" and contains no other information whatsoever. This does not seem to match what is described here; I'd expect an InvalidOperationException.
I've tried avoiding to cast the returned value of the method:
object tmp= _myJSObject.MyMethod();
This makes no difference. Changing the type of exception thrown on the JavaScript side has no effect either.
MyJSObject.prototype.MyMethod = function ()
{
throw "Hello Silverlight!";
}
The only solution I can think of right now is abusing the function's return value to pass information about the exception, but that will make my code a whole lot uglier... so:
Why is the behavior I'm seeing different from what is described in documentation? Does it have to do with my use of dynamic somehow? How can I properly handle exceptions that occur in JavaScript in my managed code?
A: After quite a bit of experimentation, I concluded that there is no way to directly handle the JavaScript exception from Silverlight. In order to be able to process the exception, the JavaScript code needs to be changed slightly.
Instead of throwing the error, I return it:
function MyMethod()
{
try
{
// Possible exception here
}
catch (ex)
{
return new Error(ex);
}
}
Then on the Silverlight side, I use a wrapper around ScriptObject to turn the return value into an exception again. The key here is the TryInvokeMember method:
public class ScriptObjectWrapper : DynamicObject
{
private ScriptObject _scriptObject;
public ScriptObjectWrapper(ScriptObject scriptObject)
{
_scriptObject = scriptObject;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
result = _scriptObject.Invoke(binder.Name, args);
ScriptObject s = result as ScriptObject;
if (s != null)
{
// The JavaScript Error object defines name and message properties.
string name = s.GetProperty("name") as string;
string message = s.GetProperty("message") as string;
if (name != null && message != null && name.EndsWith("Error"))
{
// Customize this to throw a more specific exception type
// that also exposed the name property.
throw new Exception(message);
}
}
return true;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
try
{
_scriptObject.SetProperty(binder.Name, value);
return true;
}
catch
{
return false;
}
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
try
{
result = _scriptObject.GetProperty(binder.Name);
return true;
}
catch
{
result = null;
return false;
}
}
}
Potentially you could improve this wrapper so it actually injects the JavaScript try-catch mechanism transparently, however in my case I had direct control over the JavaScript source code, so there was no need to do this.
Instead of using the built in JavaScript Error object, it's possible to use your custom objects, as long as the name property ends with Error.
To use the wrapper, the original code would change to:
public MyWrapper()
{
_myJSObject = new ScriptObjectWrapper(
HtmlPage.Window.CreateInstance("MyJSObject"));
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10026571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: UITable View cellForRowAtIndexPath: How to return no cell I am trying to delete a cell from the table from the table view when no data is returned from Parse. But no matter what I try I can't find any solution to keep from having a blank cell (Cell when no data is passed) ahead of the cell with content.
Here is my code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object
static NSString *simpleTableIdentifier = @"RecipeCell";
NSString *identifier;
if (indexPath.row == 0) {
identifier = @"Cell";
} else if (indexPath.row == 1) {
identifier = @"Cell2";
}
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
// Configure the cell
if (![@"test" isEqual: [object objectForKey:@"teacher"]]){
UILabel *nameLabel = (UILabel*) [cell viewWithTag:101];
nameLabel.text = @"";
UILabel *prepTimeLabel = (UILabel*) [cell viewWithTag:102];
prepTimeLabel.text = @"";
return cell;
} else {
UILabel *nameLabel = (UILabel*) [cell viewWithTag:101];
nameLabel.text = [object objectForKey:@"message"];
UILabel *prepTimeLabel = (UILabel*) [cell viewWithTag:102];
prepTimeLabel.text = [object objectForKey:@"teacher"];
return cell;
}
}
Thanks for any help given!
A: You cannot control the number of cells in a UITableView from the cellForRowAtIndexPath method - You need to return the correct value from the numberOfRowsInSection method. Refer to the UITableViewDataSource protocol reference and the Table View Programming Guide
Addtionally, this code block -
if (indexPath.row == 0) {
identifier = @"Cell";
} else if (indexPath.row == 1) {
identifier = @"Cell2";
}
is somewhat redundant - all of your cells are UITableViewCellStyleDefault, so they are interchangeable. Using two different identifiers is not necessary - If you intend to use different custom cell types in the future then you can keep this concept, but you probably wouldn't use the indexPath.row directly, rather you would be driven by the data type in your model for the row in question.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22544447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Kendo Chart not performing as expected My understanding of Kendo bar charts in series is that the data value should sum up per item, but in this screen shot each set of bars is an interval, and based on interval 1 input data I should have 3 colors(services)summing to a total of 22, instead I just have the largest service displaying it's portion of the bar, what am I missing here?
Sandbox link: https://codesandbox.io/s/festive-saha-hg8oq3
Imgur link to image
A: Self solved, was grouping on wrong variable
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73239368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java - Check if user input partialy matches another string? I have a problem where i want to see if the input user has enterd partially matches, or as long as majority matches with the answer, if it does then it should print out "Almost correct".
For example lets say the answer is Football, but user instead puts in Footbol. It should then print out Almost correct.
here is what i tried. But the problem is that it just checks if the whole word is containd in ENG otherwise if even one Char is missing it doesnt work.
if (Answer.equalsIgnoreCase(ENG)){
r = "Correct";
}
else if (Answer.toLowerCase().contains(ENG.toLowerCase().)){
r = "Almost correct";
}
else {
r = "Wrong";
}
System.out.println(r)
A: This code is certainly not perfect, but it basically compares the Strings and saves how many characters matched the corresponding character in the other String. This of course leads to it not really working that well with different sized Strings, as it will treat everything after the missing letter as false (unless it matches the character by chance). But maybe it helps regardless:
String match = "example";
String input = "exnaplr";
int smaller;
if (match.length() < input.length())
smaller = match.length(); else smaller = input.length();
int correct = 0;
for (int i = 0; i < smaller; i++) {
if (match.charAt(i) == input.charAt(i)) correct++;
}
int percentage = (int) ((double) correct / match.length() * 100);
System.out.println("Input was " + percentage + "% correct!");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70455951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to debug with LD_preload I use LD_PRELOAD to override the MPI_Send function with my own function to do some debugging of the MPI_send function.
Here, myMPI_Send.c code:
#define _GNU_SOURCE
#include <stdio.h>
#include <dlfcn.h>
#include <mpi.h>
#include <stdlib.h>
int MPI_Send(const void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm)
{
int (*original_MPI_Send)(const void *, int, MPI_Datatype, int, int, MPI_Comm);
original_MPI_Send=dlsym(RTLD_NEXT, "MPI_Send");
printf(" Calling MPI_Send ************** \n");
return (*original_MPI_Send)(buf, count, datatype, dest, tag, comm);
}
In my project, I use an extern library which includes also MPI_Send functions. I need to debug the extern library to know the line and the number of calls of each call of MPI_Send.
I tried to use this code using macros:
fprintf (stderr,"MPI_Send, func <%s>, file %s, line %d, count %d\n",__func__, __FILE__, __LINE__, __COUNTER__);
But, it doesn't work, it prints always the line of MPI_Send in the myMPI_Send.so.
Could you help me please? Thank you in advance.
A: MPI covers most of your needs via the MPI Profiling Interface (aka PMPI).
Simply redifines the MPI_* subroutines you need, and have them call the original PMPI_* corresponding subroutine.
In you case:
int MPI_Send(const void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm)
{
printf(" Calling MPI_Send ************** \n");
PMPI_Send(buf, count, datatype, dest, tag, comm);
}
Since you want to print the line and file of the caller, you might have to use macros and rebuild your app:
#define MPI_Send(buf,count,MPI_Datatype, dest, tag, comm) \
myMPI_Send(buf, count, MPI_Datatype, dest, tag, comm, __func__, __FILE__, __LINE__)
int myMPI_Send(const void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm, char *func, char *file, int line)
{
printf(" Calling MPI_Send ************** from %s at %s:%d\n", func, file, line);
return PMPI_Send(buf, count, datatype, dest, tag, comm);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74389223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Finding Shortest Route Between 3 or more places (Google Map Route) i'm making app about trip planner where user favorite a few place in a city and i'm suppose to route that place for user.
i need to route each so i can calculate the shortest traveling time possible.
can anyone suggest me how to solve this ?
i know google API have a routing algorithm but that just take place 1 to place 2.
currently i'm thinking about implementing Dijkstra's algorithm to this routing problem.
any suggestion ?
thanks
A: *
*First you need latitude and longitude your places. If you don't have a latitude longitude your places then use Geocoder. Geocoder return latlng from city names. Add this latlng to list.
*Use distance matrix API for find distance/durations between your places. Send latlng list to distance matrix api. You will get the url for connect to API.
*Parse JSON objects and get durations/distances. Create matrix with durations/distances.
*Send your matrix to your algorithm(Dijikstra or prim)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57439853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to hook a conversion for the logical type in Avro deserializer? I am looking for the same information regarding how to hook the conversion. Currently the conversion is always null and I am not able to convert to BigDecimal when the logical type is being used. However, I can see following conversions in the auto-generated stub class. But the object type read by the deserializer is always ByteBuffer and it throws Class Cast Exception.
In the auto-generated stub file (formatted for clarity):
import org.apache.avro.data.Conversions
import org.apache.avro.data.TimeConversions
protected static final TimeConversions.DateConversion DATE_CONVERSION = new TimeConversions.DateConversion();
protected static final TimeConversions.TimeConversion TIME_CONVERSION = new TimeConversions.TimeConversion();
protected static final TimeConversions.TimestampConversion TIMESTAMP_CONVERSION = new TimeConversions.TimestampConversion();
protected static final Conversions.DecimalConversion DECIMAL_CONVERSION = new Conversions.DecimalConversion();
And, it is always NULL for the Conversion in the SpecificDatumReader readField().
Conversion conversion = ((SpecificRecordBase)).getConversion(f.pos());
Avro version is 1.8.2 now with Confluent Platform and Registry.
How can the conversion be set in the deserializer?
A: I'd need a little more context to say exactly what your problem is - you'd not generally call getConversion() yourself unless you were writing a serialiser.
The lookup for field -> converter is in the actual generated class; look for this: private static final org.apache.avro.Conversion<?>[] conversions
This conversion table seems to only be applicable to serialisation. When deserialising, you'll need to register the conversions. I'm not sure why this is the case, but you should be able to fix the issue by adding the following code at startup, which should register the conversions you need.
SpecificData.get().addLogicalTypeConversion(new Conversions.DecimalConversion());
SpecificData.get().addLogicalTypeConversion(new TimeConversions.DateConversion());
SpecificData.get().addLogicalTypeConversion(new TimeConversions.TimeConversion());
SpecificData.get().addLogicalTypeConversion(new TimeConversions.TimestampConversion());
Depending on the exact codepaths, you may also need to call that code on GenericData.get()...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58398816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: H265 codec changes from hvc1 to hev1 I try to copy mp4 file with hevc video.
Source file have hvc1 codec.
Stream #0:0(und): Video: hevc (Main) (hvc1 / 0x31637668)
After copying the codec gets the value of hev1
Stream #0:0(und): Video: hevc (Main) (hev1 / 0x31766568)
How can i get hvc1?
I found that ffmpeg can do it with "-tag:v hvc1"
(https://stackoverflow.com/questions/32152090/encode-h265-to-hvc1-codec)
And how to set tag in c++ code (FFMpeg copy streams without transcode)
But it does not effect
My code:
AVOutputFormat *ofmt = NULL;
AVFormatContext *ifmt_ctx = NULL, *ofmt_ctx = NULL;
AVPacket pkt;
const char *in_filename, *out_filename;
int ret, i;
int stream_index = 0;
int *stream_mapping = NULL;
int stream_mapping_size = 0;
if (argc < 3) {
printf("usage: %s input output\n"
"API example program to remux a media file with libavformat and libavcodec.\n"
"The output format is guessed according to the file extension.\n"
"\n", argv[0]);
return 1;
}
in_filename = argv[1];
out_filename = argv[2];
av_register_all();
if ((ret = avformat_open_input(&ifmt_ctx, in_filename, 0, 0)) < 0) {
fprintf(stderr, "Could not open input file '%s'", in_filename);
goto end;
}
if ((ret = avformat_find_stream_info(ifmt_ctx, 0)) < 0) {
fprintf(stderr, "Failed to retrieve input stream information");
goto end;
}
av_dump_format(ifmt_ctx, 0, in_filename, 0);
avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, out_filename);
if (!ofmt_ctx) {
fprintf(stderr, "Could not create output context\n");
ret = AVERROR_UNKNOWN;
goto end;
}
stream_mapping_size = ifmt_ctx->nb_streams;
stream_mapping = (int*)av_mallocz_array(stream_mapping_size, sizeof(*stream_mapping));
if (!stream_mapping) {
ret = AVERROR(ENOMEM);
goto end;
}
ofmt = ofmt_ctx->oformat;
for (i = 0; i < (int)ifmt_ctx->nb_streams; i++) {
AVStream *out_stream;
AVStream *in_stream = ifmt_ctx->streams[i];
AVCodecParameters *in_codecpar = in_stream->codecpar;
AVCodec *decoder = avcodec_find_decoder(in_stream->codecpar->codec_id);
AVCodec *encoder = avcodec_find_encoder(in_stream->codecpar->codec_id);
if (in_codecpar->codec_type != AVMEDIA_TYPE_AUDIO &&
in_codecpar->codec_type != AVMEDIA_TYPE_VIDEO &&
in_codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE) {
stream_mapping[i] = -1;
continue;
}
stream_mapping[i] = stream_index++;
out_stream = avformat_new_stream(ofmt_ctx, NULL);
if (!out_stream) {
fprintf(stderr, "Failed allocating output stream\n");
ret = AVERROR_UNKNOWN;
goto end;
}
ret = avcodec_parameters_copy(out_stream->codecpar, in_codecpar);
if (ret < 0) {
fprintf(stderr, "Failed to copy codec parameters\n");
goto end;
}
unsigned int tag = 0;
// for ffmpeg new api 3.x
AVCodecParameters *parameters = out_stream->codecpar;
if (av_codec_get_tag2(ofmt_ctx->oformat->codec_tag, encoder->id, &tag) == 0) {
av_log(NULL, AV_LOG_ERROR, "could not find codec tag for codec id %d, default to 0.\n", encoder->id);
}
parameters->codec_tag = tag;
out_stream->codec = avcodec_alloc_context3(encoder);
// more setting for stream->codec
avcodec_parameters_to_context(out_stream->codec, parameters);
}
av_dump_format(ofmt_ctx, 0, out_filename, 1);
if (!(ofmt->flags & AVFMT_NOFILE)) {
ret = avio_open(&ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE);
if (ret < 0) {
fprintf(stderr, "Could not open output file '%s'", out_filename);
goto end;
}
}
ret = avformat_write_header(ofmt_ctx, NULL);
if (ret < 0) {
fprintf(stderr, "Error occurred when opening output file\n");
goto end;
}
while (1) {
AVStream *in_stream, *out_stream;
ret = av_read_frame(ifmt_ctx, &pkt);
if (ret < 0)
break;
in_stream = ifmt_ctx->streams[pkt.stream_index];
if (pkt.stream_index >= stream_mapping_size ||
stream_mapping[pkt.stream_index] < 0) {
av_packet_unref(&pkt);
continue;
}
pkt.stream_index = stream_mapping[pkt.stream_index];
out_stream = ofmt_ctx->streams[pkt.stream_index];
log_packet(ifmt_ctx, &pkt, "in");
/* copy packet */
pkt.pts = av_rescale_q_rnd(pkt.pts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX));
pkt.dts = av_rescale_q_rnd(pkt.dts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX));
pkt.duration = av_rescale_q(pkt.duration, in_stream->time_base, out_stream->time_base);
pkt.pos = -1;
log_packet(ofmt_ctx, &pkt, "out");
ret = av_interleaved_write_frame(ofmt_ctx, &pkt);
if (ret < 0) {
fprintf(stderr, "Error muxing packet\n");
break;
}
av_packet_unref(&pkt);
}
av_write_trailer(ofmt_ctx);
end:
avformat_close_input(&ifmt_ctx);
/* close output */
if (ofmt_ctx && !(ofmt->flags & AVFMT_NOFILE))
avio_closep(&ofmt_ctx->pb);
avformat_free_context(ofmt_ctx);
av_freep(&stream_mapping);
if (ret < 0 && ret != AVERROR_EOF) {
fprintf(stderr, "Error occurred: %s\n", av_errTOstr(ret).c_str());
return 1;
}
After changes:
out_stream = avformat_new_stream(ofmt_ctx, NULL);
ret = avcodec_parameters_copy(out_stream->codecpar, in_codecpar);
AVCodecParameters *parameters = out_stream->codecpar;
unsigned int tag = 0;
av_codec_get_tag2(ofmt_ctx->oformat->codec_tag, encoder->id, &tag) == 0);
parameters->codec_tag = tag;
out_stream->codec = avcodec_alloc_context3(encoder);
avcodec_parameters_to_context(out_stream->codec, parameters);
if (in_codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
parameters->codec_tag = MKTAG('h', 'v', 'c', '1');
}
}
av_dump_format(ofmt_ctx, 0, out_filename, 1);
ret = avio_open(&ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE);
ret = avformat_write_header(ofmt_ctx, NULL);
if (ret < 0) {
fprintf(stderr, "Error write header: %s\n", av_errTOstr(ret). c_str());
goto end;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50565912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: na.rm and conversion related warnings Today I tried to finish my last R-study-exercises, but I failed. I`m not allowed to you show the precise instructions of my academic, but you may can help me with the warnings I get after sourcing. What do they mean? What doesn't fit?
I know, this question is very vague, but this is the only way to ask.
I believe its about "Aufgabe 3" and "Aufgabe 4"
This is my input:
x <- read.csv ("http://hci.stanford.edu/jheer/workshop/data/worldbank/worldbank.csv")
y <- (colnames (x) <- (c ("Country", "Year", "co2", "power","energy", "fertility", "gni", "internet", "life.expectancy","military", "population", "hiv.prevalence")))
y
####Aufgabe 1####
f1 <- min(x$fertility, na.rm=TRUE)
f1
####Aufgabe 2####
f2 <- max (subset(x, Country=="Australia" | Country=="Belarus" | Country=="Germany", select=fertility), na.rm=TRUE)
f2
####Aufgabe 3####
q1 <- quantile (subset(x, Year==2005, select=military), probs=c(.25), na.rm=TRUE)
q1
####Aufgabe 4####
q2 <- quantile (subset(x, Year==2001, select=population), probs=c(.05), na.rm=TRUE)
q2
####Aufgabe 4####
n <- length(which (is.na (subset (x, Year==2000, select=military))))
n
####Aufgabe 5####
library(psych)
mil<- skew (x$military)
coun<- skew(x$Country)
Ye<- skew(x$Year)
co<- skew(x$co2)
po<- skew(x$power)
en<- skew(x$energy)
fer<- skew(x$fertility)
gni<- skew(x$gni)
inertnet<- skew(x$internet)
life<- skew(x$life.expectancy)
pop<- skew(x$population)
hiv<- skew(x$hiv.prevalence)
mil
coun
Ye
co
po
en
fer
gni
inertnet
life
pop
hiv
ku1<- "co2"
ku1
...and these warnings I get after sourcing:
1. In var(as.vector(x), na.rm = na.rm : Na generated through conversion
2. n mean.default(x) : argument is not numeric or logical: returning NA
3. 3: In Ops.factor(x, mx) : - not meaningful for factors
4. In var(as.vector(x), na.rm =na.rm) : Na generated through conversion
A: *
*Means that the as.vector(x) operation resulted in one or more elements of x being converted to NA as the conversion for those components is not defined.
*When mean.default is called, x is neither numeric or logical and hence the function can't do anything with the data
*Means that x or mx or both are factors and - (and other mathematical operators) is not defined for factor objects.
*See 1. above.
All point to an issue with the input data, usually a factor has been created.
The warnings come from this line:
> coun <- skew(x$Country)
Warning messages:
1: In var(as.vector(x), na.rm = na.rm) : NAs introduced by coercion
2: In mean.default(x) : argument is not numeric or logical: returning NA
3: In Ops.factor(x, mx) : - not meaningful for factors
4: In var(as.vector(x), na.rm = na.rm) : NAs introduced by coercion
This is because x$Country is a factor:
> str(x)
'data.frame': 1362 obs. of 12 variables:
$ Country : Factor w/ 227 levels "","Afghanistan",..: 19 19 19 19 19 19 166 166 166 166 ...
....
Even if you made this a character you could compute the skewness of this variable. Just comment this line out.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14002345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Reverse Order of Properties Per Element in Http Response from JPA/Hibernate Query if I get a response returning a list of elements like the following:
[
{
"c": {
"c1": 4,
"c2": "5",
},
"b": {
"b1": 2,
"b2": "3",
},
"a": "1"
},
{
"cc": {
"cc1": 4,
"cc2": "5",
},
"bb": {
"bb1": 2,
"bb2": "3",
},
"aa": "1"
}
]
Is there a way I can reverse the order of the properties in each element, while maintaining the element order? I am using JPA/Hibernate. The result should be as follows:
[
{
"a": "1",
"b": {
"b1": 2,
"b2": "3",
},
"c": {
"c1": 4,
"c5": "5",
}
},
{
"aa": "1",
"bb": {
"bb1": 2,
"bb2": "3",
},
"cc": {
"cc1": 4,
"cc2": "5",
}
}
]
Thanks in advance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75238330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: what algorithm should I use? I'm fairly new to complex algorithms (been doing simple programs til now), and I'm trying to develop a program where the user can input a desired budget, and the program would search for the optimal products the user can purchase from each category.
example:
Products:
Shirt:
shirtA - $20
shirtB - $15
shirtC - $10
Pants:
pantsA - $30
pantsB - $25
pantsC - $20
Shoes:
shoesA - $20
shoesB - $15
shoesC - $10
User Input (budget): $60
Output:
shirtB - $15
PantsA - $30
shoesB - $15
total: $60
...or something like that. what kind of algorithm should I be researching for? I find this hard because I do not know where to begin in understanding what algorithm to use. See, this is for class, and our professor wants us to indicate what kind of algorithm we used. I think I can actually finish this if I just brute force trial and error this thing, but then I wouldn't know what algorithm I used. anyway, thanks guys.
A: The problem is a variation of the Knapsack problem; instead of choosing whether an item is to be included in the solution, a choice must be made which item to take from each category. Although not explicitly stated in the Wikipedia article, the formulation in the question can be solved within a pseudopolynomial runtime bound via Dynamic programming by modifying the recurrence relation for the basic formulation.
A: Just a fun with Python's itertools:
import itertools
def solutions(dicts, value):
return [keys for keys in itertools.product(*dicts) if sum(d[k] for d, k in zip(dicts, keys)) == value]
Shirt = {"shirtA": 20, "shirtB": 15, "shirtC": 10}
Pants = {"pantsA": 30, "pantsB": 25, "pantsC": 20}
Shoes = {"shoesA": 20, "shoesB": 15, "shoesC": 10}
print solutions([Shirt, Pants, Shoes], 60)
We generate all allowed combinations (one piece from each category) but we keep only these that give the required sum.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31431712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Neo4j Browser Crash grey screen MATCH (a:Doss)
MATCH (b:Doss)
WHERE a.Num=b.Num
return a,b
it takes long time and then no results, just the browser being crashed with grey screen.
NB:in this database i got 6M nodes.
A: You need an index on :Doss(Num) or this won't be able to finish in a reasonable amount of time.
The key is that most Cypher operations execute per row. So the second MATCH is being executed per each result from the first MATCH.
If you don't have an index, then this will likely be doing a NodeByLabelScan for a, and then another NodeByLabelScan per a node and filtering to find matches for b.
Basically, you will be performing a total of 6M + 1 label scans, and filtering across 6M * 6M rows, and that's just not a good idea.
If you add the index, then you will be doing only one NodeByLabelScan, and then 6M index seeks to find, per row, all b nodes with the same num as a.
You should be able to run an EXPLAIN on the query to confirm how the planner wants to execute this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67738035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In Visual Studio 2013, what does this black arrow-shaped symbol in the breakpoint bar mean? Somehow, one of the lines in my source code became marked with a black arrow-shaped icon pointing to the right. I'm familiar with bookmarks and breakpoints, but I can't find a clue about this one. It is the top-most icon in the screenshot below.
What is the purpose of this symbol?
A: That icon indicates that the line is a Find Result from the last time you did a "Find In Files."
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30915869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: One command to get output buffer and erase it in PHP? Is there any command to get the output and erase the buffer without turning it off?
eg.
ob_start();
include 'first_page.php';
$first_page = ob_get_clean();
ob_start();
include 'second_page.php';
$second_page = ob_get_clean();
ob_start();
....
Is there a function available so I don't have to turn on output buffering every time?
A: I know this is an old question but I was looking for an answer to this question and wanted to post the answer based on comments posted here.
It looks like the answer is no, there is no single command to get the output buffer and erase it without turning it off. However, instead of repeatedly starting a new buffer, you could just erase the current buffer with ob_clean() in between calls of ob_get_contents()
For example:
ob_start();
include 'first_page.php';
$first_page = ob_get_contents();
ob_clean();
include 'second_page.php';
$second_page = ob_get_contents();
ob_end_clean();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22372666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Setting Session State - APEX 21.1 Based on the documentation and examples I have come across, it seems that the way to set/pass session state between pages is via the URL. It got me thinking, is it ok to reference page items from a different page directly? Or are there downsides in doing this that someone new to APEX (like me) may not be aware of initially.
For example:
*
*there is an app with two pages PAGE 1 and PAGE 2
*PAGE 1 sets P1_SOME_VALUE = 'GREEN' (P1_SOME_VALUE now in session state)
*PAGE 2 needs access to P1_SOME_VALUE's value
Are there any reasons to not set up a BEFORE HEADER Computation on PAGE 2 that sets P2_SOME_VALUE = :P1_SOME_VALUE? (Assuming that P1_SOME_VALUE is a given to always be available in the session for PAGE 2)
If going from PAGE 1 to PAGE 2 is done using a hyperlink, then I understand it is easier to set the session state using the REDIRECT URL attribute method that I have seen. I have come across a situation in my app where a URL is generated dynamically after a chain of dynamic actions and using the BEFORE HEADER Computation seems like the cleaner/simpler solution for my given situation. Just want to make sure I am not overlooking anything.
A: The behaviour you describe, using a pl/sql process which references a page item from another page will work fine, but there are some things to take into account. Not sure if this list is exhaustive, others might comment:
*
*Personally I try to avoid references to items on other pages within a page, because that makes developing harder - when working on page x, you'll usually search for item occurences within page only . If there are occurences on other pages the application becomes less clean. I try to follow this as a best practice. The cleaner the app, the easier to maintain. When you have to work in this app 2 years from now, you won't remember that P1_SOME_VALUE is referenced on page 2. Or that other developer who works on it will hate you forever ;)
*This can possibly make debugging a lot harder. Suppose page is accessed via a url or branch that has the option "clear cache for pages" set to "page 1", then the value of P1_SOME_VALUE will be cleared because that item is defined on page 1. Debugging this issue will be a challenge.
*Passing a value in a url is very secure. If you use checksums, there is no way for a user to manipulate the value of the page item manually.
*Note that the DOM of the page only contains the page items that are defined on that page. This implies that you cannot use javascript on page 2 that references P1_SOME_VALUE or set the value of P1_SOME_VALUE using javascript on page 2. This doesn't matter in your use case.
An alternative to referencing page items in another page than the page they belong to is storing the data in a collection - that will exist for the duration of the session.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68530516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Get selected place data from multiple Google places autocomplete in Angularjs I have multiple input fields for getting location in a single page. I used $scope.on() event to get g-places-autocomplete selected data in my controller.
$scope.$on('g-places-autocomplete:select', function (event, place) {
console.log(place.formatted_address);
});
Html:
<input ng-model="locationGo" type="text" g-places-autocomplete>
<input ng-model="locationTop" type="text" g-places-autocomplete>
I am getting selected location from both input fields but I want to know which input filed was selected.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39222487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I get the area of each Voronoi Polygon in R? I have a set of coordinates X and Y for my points and used the deldir to create determine and plot the Voronoi Polygons. (I've used this tutorial here)
This is my plot: (sorry that its so small, but you get the idea).
I need to determine the area of each polygon. How can I do that?
I looked up in the deldirpackage page and couldnt find anything related to the Voronoi polygons, only about other
A: Based on the reference manual (https://cran.r-project.org/web/packages/deldir/index.html), the output of the deldir function is a list. One of the list element, summary, is a data frame, which contains a column called dir.area. This is the the area of the Dirichlet tile surrounding the point, which could be what you are looking for.
Below I am using the example from the reference manual. Use $ to access the summary data frame.
library(deldir)
x <- c(2.3,3.0,7.0,1.0,3.0,8.0)
y <- c(2.3,3.0,2.0,5.0,8.0,9.0)
dxy1 <- deldir(x,y)
dxy1$summary
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42787711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: React shows values in console but does not render them I am trying to load the options of a select depending on another select. I extract the data from an array (which will later have much more data).
My problem is that I can't render the second select. I get the data correctly filtered but the options are not added. In the two "console.log" of the code, you can see that I commented aside, the result shown in console.
Any idea what I'm failing? I am a newbie in react. I apologize if the code is very horrible! Any help will be welcome.
P.S. I don't know if it makes any difference in this case, but I'm using "Ant Design".
import React, { useState } from 'react';
import { Row, Col, Form, Select, Input } from 'antd';
export default function SelectPetZone(props) {
const { publicationData, setPublicationData } = props;
const { Option } = Select;
const arrayZones = [
{
departmentName: "Montevideo",
neighborhood: ['Centro', 'Cordón', 'Flor de Maroñas', 'Manga']
},
{
departmentName: "Canelones",
neighborhood: ['Las Piedras', 'El Dorado', 'Progreso', 'La Paz']
}
];
const optionsDepartments = [];
const [optionsNeighborhood, setoptionsNeighborhood] = useState([]);
for(const item of arrayZones) {
optionsDepartments.push(<Option key={item.departmentName} value={item.departmentName}> { item.departmentName } </Option>);
}
const chargeNeighborhood = e => {
// Set department
setPublicationData({ ...publicationData, department: e });
// Load neighborhood
for(const i of arrayZones) {
if(e === i.departmentName) {
for(const j of i.neighborhood) {
console.log(j);
setoptionsNeighborhood(...optionsNeighborhood, <Option>{j}</Option>);
}
}
}
}
return (
<>
<Row>
<Col lg={6}>
<Form.Item>
<Select placeholder='Departamento' onChange={chargeNeighborhood} value={publicationData.department} >
{optionsDepartments}
</Select>
</Form.Item>
</Col>
<Col lg={6} offset={3}>
<Form.Item>
<Select placeholder='Barrio' onChange={e => setPublicationData({ ...publicationData, neighborhood: e })} value={publicationData.neighborhood} >
{optionsNeighborhood}
</Select>
</Form.Item>
</Col>
</Row>
</>
)
}
A: In react, we have something called UseState()
First,
import React, { useState } from 'react';
Then Change
const optionsNeighborhood = [];
To
const [optionsNeighborhood, setoptionsNeighborhood] = useState([])
Then Change
for(const i of arrayZones) {
if(e === i.departmentName) {
for(const j of i.neighborhood) {
console.log(j); // ==> Print the correct data
optionsNeighborhood.push(j);
}
}
}
to
for(const i of arrayZones) {
if(e === i.departmentName) {
for(const j of i.neighborhood) {
console.log(j); // ==> Print the correct data
setoptionsNeighborhood([...optionsNeighborhood, j]);
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65486233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to insert a new line in a UILabel that uses NSString StringWithFormat I am using a UILabel in my storyboard to show a string of text. Then I am using dispatch_get_main_queue to change the text in the UILabel. The text is being cut off on-screen after dispatch_get_main_queue is being called. I have also tried \n which deletes the rest of the text completely.
/*slide*/
double delayInSecond8 = 5.0;
dispatch_time_t popTime8 = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSecond8 * NSEC_PER_SEC));
dispatch_after(popTime8, dispatch_get_main_queue(), ^(void){
hello.text = [NSString stringWithFormat:@"You can also share\n your email address here"];
});
How can I add a new line to this method?
A: If you want your label to display multiple lines you need to specify that in its numberOfLines property:
This property controls the maximum number of lines to use in order to fit the label’s text into its bounding rectangle. The default value for this property is 1. To remove any maximum limit, and use as many lines as needed, set the value of this property to 0.
You could set it either in code or in Attributes inspector in the storyoard:
Also make sure that the constraints of the label allows it to expand accordingly to its content.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69419331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to join 7 tables in SQL using INNER JOIN I am creating a stored procedure to join 7 tables in SQL using INNER JOIN, however I am getting an error about incorrect syntax.
I've tried to adjust formatting but I cannot get the syntax correct. Does anyone know where I've gone wrong? I get an error stating
Incorrect syntax near "WHERE"
My code:
CREATE PROCEDURE [dbo].[spInvoicing]
@InvoiceId INT
AS
BEGIN
SELECT
tblInvoices.InvoiceId, tblInvoices.InvoiceDate,
tblClients.Firstname, tblClients.Surname, tblClients.Address, tblClients.City,
tblClients.Postcode, tblClients.Email, tblClients.Phone,
tblAppointments.AppointmentId, tblAppointments.DateOfAppointment,
tblProductsUsed.ProductsUsedId, tblProducts.ProductName, tblProductsUsed.Quantity,
tblPointofSale.SaleId, tblPointOfSale.CostOfProducts, tblPointOfSale.CostOfServices,
tblPointOfSale.VAT, tblInvoices.SaleAmount, tblInvoices.PaymentMethod
FROM
tblClients
INNER JOIN
tblAppointments ON tblClients.ClientId = tblAppointments.ClientId
INNER JOIN
tblPointOfSale
INNER JOIN
tblInvoices ON tblPointOfSale.SaleId = tblInvoices.SaleId
INNER JOIN
tblProductsUsed
INNER JOIN
tblProducts ON tblProductsUsed.ProductId = tblProducts.ProductId
INNER JOIN
tblServicesRendered
INNER JOIN
tblServices ON tblServicesRendered.ServiceId = tblServices.ServiceId ON tblServicesRendered.AppointmentId = tblAppointments.AppointmentId
ON tblPointOfSale.AppointmentId = tblAppointments.AppointmentId
AND tblProductsUsed.SaleId = tblPointOfSale.SaleId
AND tblPointOfSale.ClientId = tblClients.ClientId
WHERE
tblInvoices.InvoiceId = @InvoiceId
END
A: Your JOINs got a bit scrambled. Try this below, and see if that fixes the syntax error.
Always try to get your JOINs to follow the format INNER JOIN [Table2] ON [Table2].[Field1] = [Table1].[Field1]
FROM tblClients
INNER JOIN tblAppointments ON tblClients.ClientId = tblAppointments.ClientId
INNER JOIN tblPointOfSale ON tblPointOfSale.AppointmentId = tblAppointments.AppointmentId
AND tblPointOfSale.ClientId = tblClients.ClientId
INNER JOIN tblInvoices ON tblPointOfSale.SaleId = tblInvoices.SaleId
INNER JOIN tblProductsUsed ON tblProductsUsed.SaleId = tblPointOfSale.SaleId
INNER JOIN tblProducts ON tblProductsUsed.ProductId = tblProducts.ProductId
INNER JOIN tblServicesRendered ON tblServicesRendered.AppointmentId = tblAppointments.AppointmentId
INNER JOIN tblServices ON tblServicesRendered.ServiceId = tblServices.ServiceId
A: I just copy and pasted your code into this website - http://poorsql.com/
and it hightlighted the error for you (you're missing AND in the joins).
As @DBro said - get in the habit of putting your JOINs on the new line and format it a little differently, and you'll have far less trouble.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55737664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Web service to web service calling in SAP PI I am doing a scenario called webservice to webservice in SAP PI.
I followed the following URL:
http://saptechnical.com/Tutorials/XI/WebService2WS/Page9.htm
I created the WSDL file at the end using tools->display WSDL.
I gave the following UR in the WSDL URL step:
http://BCHSAP003:55000/sap/xi/engine?channel=:SOAP_Request_BS_1:BS_Sender
The WSDL URL that got created in the file is :
http://bchsap003:55000/sap/xi/engine?channel=:soap_request_bs_1:BS_Sender&
When I open the URL in browser it is giving the following:
<SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP:Header></SOAP:Header>
<SOAP:Body>
<SOAP:Fault xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">
<faultcode>SOAP:Client</faultcode>
<faultstring>Empty HTTP request received</faultstring>
<faultactor>http://sap.com/xi/XI/Message/30</faultactor>
<detail>
<SAP:Error xmlns:SAP="http://sap.com/xi/XI/Message/30" SOAP:mustUnderstand="1">
<SAP:Category>XIProtocol</SAP:Category>
<SAP:Code area="MESSAGE">EMPTY_HTTP_REQUEST_RECEIVED</SAP:Code>
<SAP:P1/>
<SAP:P2/>
<SAP:P3/>
<SAP:P4/>
<SAP:AdditionalText/>
<SAP:Stack>
Empty HTTP query received; message processing not possible
</SAP:Stack>
</SAP:Error>
</detail>
</SOAP:Fault>
</SOAP:Body>
</SOAP:Envelope>
When I am testing the WSDL file from my SOAP UI, it is not returning any response.
I changed the authentication in SOAP to preemptive, and after that getting the following response:
<SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP:Body>
<SOAP:Fault>
<faultcode>SOAP:Server</faultcode>
<faultstring>System Error</faultstring>
<detail>
<s:SystemError xmlns:s="http://sap.com/xi/WebService/xi2.0">
<context/>
<code>MESSAGE.GENERAL</code>
<text/>
</s:SystemError>
</detail>
</SOAP:Fault>
</SOAP:Body>
</SOAP:Envelope>**strong text**
I think there is some issue with the WSDL.
Can anyone help me out?
A: I was writing the hostname in the target URL which PI was not able to recognise.
I changed it to IP.
It's working fine now.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34719704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Array with elements from MySQL I want to get random numbers with exceptions (for example, I want a number from 500 to 550 without 505, 512, 525, etc).
I found here one code like this:
function randWithout($from, $to, array $exceptions) {
sort($exceptions); // lets us use break; in the foreach reliably
$number = rand($from, $to - count($exceptions)); // or mt_rand()
foreach ($exceptions as $exception) {
if ($number >= $exception) {
$number++; // make up for the gap
} else {
break;
}
}
return $number;
}
If I use something like:
$nr = randWithout(500, 550, array(505, 512, 525));
everything it's fine, but in array I want to put elements from mysql, so I have created:
$query = mysql_query("SELECT `site_id` FROM `table` WHERE `user_id`='{$data->id}'");
$data = array();
while ($issues_row = mysql_fetch_array($query, MYSQL_ASSOC)) {
$data[] = $issues_row['site_id'];
}
$result = implode(",", $data);
Now, if i use:
$nr = randWithout(500, 550, array($result));
it's not working, so my problem is array($result)
What is wrong here?
A: I think the problem is:
$result = implode(",", $data);
$nr = randWithout(500, 550, array($result));
while you should do is remove the implode and send the $data array directly.
$randWithout(500, 550, $data);
A: Tim is right, do not implode results in a string.
But that is the quite odd function for getting random number with exceptions. Try something like:
function getRndWithExceptions($from, $to, array $ex = array()) {
$i = 0;
do {
$result = rand($from, $to);
} while( in_array($result, $ex) && ++$i < ($to - $from) );
if($i == ($to - $from)) return null;
return $result;
}
<...>
$nr = getRndWithExceptions(500, 550, $data); // $data is array
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6622663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Admob interstitials not clickable on Nexus 5 (Android 4.4.2) Do you know of a problem with Admob interstitial Ads not being clickable and therefore not bringing any revenue on Nexus 5 devices?
Facts:
*
*It does not happen with all interstitial ads - some are clickable, but most are not.
*It happens both with the old standalone Google Admob SDK and with the new Google Play Services SDK.
*It happens on Nexus 5 with Android 4.4.2, but maybe it's possible that other devices are affected too.
*It happens in many programs in the Google Play Store that I've tested with - not only with my application. For example, you can check CPU-Z
*It does not happen on Galaxy Nexus (Nexus 3), Galaxy S, HTC One.
*Below is a screenshot of the Ad. The little INFO button in the bottom is clickable and opens ok, the X close button is also working ok, however clicking on the Ad does not do anything - as if it does not exist or there is something above it.
Do you know of any workaround or possible solution to the problem?
Thank you!
--- UPDATE ---
This is the activity declaration:
<activity
android:name="com.middlehut.android.belot.BelotActivity"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:hardwareAccelerated="true"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Interstitial loading, no special code here:
adMobInterstitial = new InterstitialAd(this);
adMobInterstitial.setAdUnitId(AdsConstants.AdMob.INTERSTITIAL_ID);
adMobInterstitial.loadAd(adRequest);
if(adMobInterstitial.isLoaded()) {
adMobInterstitial.show();
}
A: I just solved this issue.
It was due to the flag android:launchMode="singleInstance" on the activity presenting the interstitial.
i think it is an adMob bug, so please check and in case just remove this flag to get interstitial working.
A: I finally figured out the problem. There was no problem; it is by design. The ads load if clicked near the middle but not if clicked near the corners. That's why sometimes they seemed to randomly not click through. Took me a while to figure that out.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23205456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Using Google directions API I am new to JAVA and the android studio ide platform and I need some assistance with using the google directions API.
I have a general idea but I don't know how to implement it in code. At the moment my app has a particular screen that shows a map fragment, a search bar, and button to move the map camera to the searched location. There are some basic permission checks as well and two other items related to another function of the app(at the moment I am focused on being able to use the direction API)
Below is the code I have for that screen related to the map, it would be a great help if someone can help me out with this problem.
(https://github.com/davidR01/EVDASH1.0.0)
public class MainDASH extends AppCompatActivity implements OnMapReadyCallback {
ImageView imageView_Battery;////////////////////////////////////////
TextView textView_Battery;/////////////////////////////////////////
Handler handler;///////////////////////////////////////////
Runnable runnable;///////////////////////////////////////
GoogleMap dashGoogleMap; /// create google map variable
private final static int MY_PERMISSION_FINE_LOCATION = 101; //required to point to which runtime permissions to access
@Override
protected void onCreate(Bundle savedInstanceState) { // creates the main activity screen
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_dash);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); /// sets the orientation of the app to landscape at runtime reguagrdless if screen rotation is enabled
if (googleServicesAvaliable()) {///the map requires play services this call the function to checks to see if it is avaliable
Toast.makeText(this, "Checking for play_services", Toast.LENGTH_SHORT).show(); /// if it is avaliable a message is diplayed this is for testing purposes
}
initMap();
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
imageView_Battery = (ImageView) findViewById(R.id.imageView_Battery);///////////////////
textView_Battery = (TextView) findViewById(R.id.textView_Battery);///////////////////////
runnable = new Runnable() {
@Override
public void run() {
int level = (int) batterylevel();
textView_Battery.setText("BATTERY: " + level + "%");
if (level > 75) {
imageView_Battery.setImageResource(R.drawable.battery_full);
}
if (level > 50 && level <= 75) {
imageView_Battery.setImageResource(R.drawable.battery_eighty);
}
if (level > 25 && level <= 50) {
imageView_Battery.setImageResource(R.drawable.battery_fifty);
}
if (level <= 25) {
imageView_Battery.setImageResource(R.drawable.battery_twentyfive);
}
handler.postDelayed(runnable, 5000);
}
};
handler = new Handler();
handler.postDelayed(runnable, 0);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
private void initMap() { ////initializes the map fragmant
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapFragment);
mapFragment.getMapAsync(this);
}
public void onButtonClick(View v) { ////Gives functionality to the diagnostic button on the home screen
if (v.getId() == R.id.DiagnosticButton) ;
Intent i = new Intent(MainDASH.this, loginTSO.class); //when click goes to the login screen
startActivity(i);
}
public boolean googleServicesAvaliable() { // method to check for Google play services
GoogleApiAvailability api = GoogleApiAvailability.getInstance(); // gets instance of google api avaliability
int isAvaliable = api.isGooglePlayServicesAvailable(this);
if (isAvaliable == ConnectionResult.SUCCESS) { // if it is avaliable return true
return true;
} else if (api.isUserResolvableError(isAvaliable)) { // if not avaliable display an error dialog in the form of a popup msg
Dialog dialog = api.getErrorDialog(this, isAvaliable, 0);
dialog.show();
} else {
Toast.makeText(this, "Cannot connect to play services", Toast.LENGTH_LONG).show(); // display message if cannot connect to google play services
}
return false;
}
@Override
public void onMapReady(GoogleMap googleMap) {
dashGoogleMap = googleMap; ////// links the variable created to the google map
goToLocationZoom(10.6918, -61.2225, 9); ///////////// calls the gotolocationZoom function that take co-ordinates and moves the camera to that location at the zoom level set
dashGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); // changes the default map type to hybrid
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
dashGoogleMap.setMyLocationEnabled(true);
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_FINE_LOCATION);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSION_FINE_LOCATION:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
dashGoogleMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(getApplicationContext(), "The MAP requires Location Permissions to be granted", Toast.LENGTH_LONG).show();
}
break;
}
}
private void goToLocation(double latitude, double longitude) {
LatLng ll = new LatLng(latitude, longitude);
CameraUpdate update = CameraUpdateFactory.newLatLng(ll);
dashGoogleMap.moveCamera(update);
}
private void goToLocationZoom(double latitude, double longitude, float zoom)//zooms in to the set coordinates in map view
{
LatLng ll = new LatLng(latitude, longitude);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
dashGoogleMap.moveCamera(update);
}
public void geoLocate(View view) throws IOException {
EditText et = (EditText) findViewById(R.id.txtSearchLocation);
String location = et.getText().toString(); /// what user enters as string
Geocoder geocode = new Geocoder(this); //takes any string and converts into latitude and long
List<Address> list = geocode.getFromLocationName(location, 1);
Address address = list.get(0);
String locality = address.getLocality();
Toast.makeText(this, locality, Toast.LENGTH_LONG).show();
double latitude = address.getLatitude();
double longitude = address.getLongitude();
goToLocationZoom(latitude, longitude, 13);
}`
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47371861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: not working batch file to rewrite txt file Im creating a file with devcon utility in order to list all usb devices that were connected to a PC since I need to delete hidden devices(not in use). In this moment I want to rewrite the strings in the created file but adding "@ to the begining and " till the endo of the string, so this would be an example
devcon obtained string
USB\VID_8087&PID_0025\7&21809D95&0&2
desired rewrite
"@USB\VID_8087&PID_0025\7&21809D95&0&2"
not sure if can be done in this same lines or if it needs to be added separately
setlocal
cmd /c "for /f delims^=^ eol^= %%I in ('findstr /c:"USB\VID" DevicesExist.txt') do @for %%a in (%%I) do @echo %%a"| findstr /c:"USB\VID">DevicesExist2.txt
any ideas?, thank you
A: @ECHO OFF
SETLOCAL
rem The following settings for the source directory, destination directory, target directory,
rem batch directory, filenames, output filename and temporary filename [if shown] are names
rem that I use for testing and deliberately include names which include spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.
SET "destdir=u:\your results"
SET "outfile=%destdir%\outfile.txt"
(
FOR /f "tokens=1delims= " %%b IN ('devcon findall *^|find "USB\VID"') DO (
ECHO "@%%b"
)
)>>"%outfile%"
GOTO :EOF
Not really sure why your code is so complex or why you haven't posted a small sample of your DevicesExist.txt file.
This code executes devcon and appends the processed extracted data to a destination file. Use > in place of >> to replace any existing content of the destination file with the output from this batch.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66067145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails ruby-mechanize how to get a page after redirection I want to collect manufacturers and their medicine details from http://www.mims.com/India/Browse/Alphabet/All?cat=Company&tab=company.
Mechanize gem is used to extract content from html page with help of ryan Tutorial
I can login successfully but couldn't reach desination page http://www.mims.com/India/Browse/Alphabet/All?cat=Company&tab=company.
I have tried so far
require 'rubygems'
require 'nokogiri'
require 'open-uri'
require 'mechanize'
agent = Mechanize.new
agent.user_agent = 'Individueller User-Agent'
agent.user_agent_alias = 'Linux Mozilla'
agent.get("https://sso.mims.com/Account/SignIn") do |page|
#login_page = a.click(page.link_with(:text => /Login/))
# Submit the login form
login_page = page.form_with(:action => '/') do |f|
f.SignInEmailAddress = 'username of mims'
f.SignInPassword = 'secret'
end.click_button
url = 'http://www.mims.com/India/Browse/Alphabet/A?cat=drug'
page = agent.get url # here checking authentication if success then redirecting to destination
p page
end
Note: I have shared dummy login credential for your testing
After clicks on 'CompaniesBrowse Company Directory' link, page redirecting with flash message "you are redirecting...", Mechanize gem caches this page.
Question:
1) How to get the original page(after redirection).
A: I found problem cases that MIMS site auto submit form with page onload callback for checking authentication. It is not working with machanize gem.
Solution
Manually submitting the form two times solves this issue. Example
url = 'http://www.mims.com/India/Browse/Alphabet/A?cat=drug'
page = agent.get url # here checking authentication if success then redirecting to destination
p page
page.form.submit
agent.page.form.submit
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19271622",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Django: EmailMessage not raising exception when only one of two recipients fail I have a piece of code similar to this:
from django.core.mail import EmailMessage
from smtplib import SMTPException
try:
email = EmailMessage(subject, body, "[email protected]", recipients)
email.content_subtype = 'html'
email.send(fail_silently=False)
except SMTPException as e:
print e.recipients
If I set recipients = ["[email protected]"], the server responds with a "unknown user" message, and the exception is raised.
But if I set recipients = ["[email protected]", "[email protected]"], the message is delivered to [email protected], which is an existing user, but no exception is raised because of foo being an unexistent user.
Is there a way to raise the exception if at least one of the recipients fails?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29133291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to access array value inside PromiseValue? I'm new to React-Redux. I am making an api call to a json file and would like to return the contents of this file as an array. I haven't dealt with Promises very much, so my knowledge of accessing them is a little foggy. Basically, there's what I have:
const fetchData = () => {
return fetch('endpoint.json')
.then(results => results.json())
}
getProducts: (cb, timeout) => setTimeout(() => cb(fetchData().then(response => response)), timeout || TIMEOUT)
getProducts currently returns the following, which I can open up to look at in the console:
action {type: "RECEIVE_PRODUCTS", products: Promise}
products: Promise
__proto__ :Promise
[[PromiseStatus]] :"resolved"
[[PromiseValue]]: Array(3)
How can I access the PromiseValue? I need to get the JSON array directly!
A: After a heated discussion, it has been suggested that you rewrite your getProducts method to be more Promise-like. Don't mix callbacks with promises, put your code inside the then methods. Chain promises where you can.
Either of these solutions described here should suffice
You have to write your getProducts inside a then
fetchData().then((jsonResults)=> {
// put the code surrounding getProducts here
return {
getProducts: jsonResults
}
})
Or, you could use await (see async functions):
let products = await fetchData();
return {
getProducts: products
}
Example
> console.log(Promise.resolve([1,2,3]))
Promise {<resolved>: Array(3)}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Array(3)
> Promise.resolve([1,2,3]).then((jsonResults) => {
console.log(jsonResults);
})
(3) [1, 2, 3]
A: You can use await or you can return the promise and handle the callback
reference : https://softwareengineering.stackexchange.com/questions/279898/how-do-i-make-a-javascript-promise-return-something-other-than-a-promise
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49642363",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to cache pages using background jobs? Definitions: resource = collection of database records, regeneration = processing these records and outputting the corresponding html
Current flow:
*
*Receive client request
*Check for resource in cache
*If not in cache or cache expired, regenerate
*Return result
The problem is that the regeneration step can tie up a single server process for 10-15 seconds. If a couple of users request the same resource, that could result in a couple of processes regenerating the exact same resource simultaneously, each taking up 10-15 seconds.
Wouldn't it be preferrable to have the frontend signal some background process saying "Hey, regenerate this resource for me".
But then what would it display to the user? "Rebuilding" is not acceptable. All resources would have to be in cache ahead of time. This could be a problem as the database would almost be duplicated on the filesystem (too big to fit in memory). Is there a way to avoid this? Not ideal, but it seems like the only way out.
But then there's one more problem. How to keep the same two processes from requesting the regeneration of a resource at the same time? The background process could be regenerating the resource when a frontend asks for the regeneration of the same resource.
I'm using PHP and the Zend Framework just in case someone wants to offer a platform-specific solution. Not that it matters though - I think this problem applies to any language/framework.
Thanks!
A: With Varnish you can proactively cache page content and use grace to display stale, cached content if a response doesn't come back in time.
Enable grace period (varnish serves stale (but cacheable) objects while retriving object from backend)
You may need to tweak the dials to determine the best settings for how long to serve the stale content and how long it takes something to be considered stale, but it should work for you. More on the Varnish performance wiki page.
A: I recommend caching in webserver level rather than the application
A: I have done just this recently for a couple of different things, in each case, the basics are the same - in this instance the info can be pre-generated before use.
A PHP job is run regularly (maybe from
CRON) which generates information into
Memcached, which is then used
potentially hundreds of times till
it's rebuilt again.
Although they are cached for well-defined periods (be it 60 mins, or 1 minute), they are regenerated more often than that. Therefore, unless something goes wrong, they will never expire from Memcache, because a newer version is cached before they can expire. Of course, you could just arrange for them to never expire.
I've also done similar things via a queue - you can see previous questions I've answered regarding 'BeanstalkD'.
A: Depending on the content the jQuery.load() might be an option.
(I used it for a twitter feed)
Step 1
Show the cached version of the feed.
Step 2
Update the content on the page via jQuery.load() and cache the results.
.
This way the page loads fast and displays up2date content (after x secs offcourse)
But if rebuilding/loading a full page this wouldn't give a nice user experience.
A: You describe a few problems, perhaps some general ideas would be helpful.
One problem is that your generated content is too large to store entirely so you can only cache a subset of that total content, you will need: a method for uniquely identifying each content object that can be generated, a method for identifying if a content object is already in the cache, a policy for marking data in the cache stale to indicate that background regeneration should be run, and a policy for expiring and replacing data in the cache. Ultimately keeping the unique content identification simple should help with performance while your policy for expiring objects and marking stale objects should be used to define the priority for background regeneration of content objects. These may be simple updates to your existing caching scheme, on the other hand it may be more effective for you to use a software package specifically made to address this need as it is not an uncommon problem.
Another problem is that you don't want to duplicate the work to regenerate content. If you have multiple parallel generation engines with differing capabilities this may not be so bad of a thing and it may be best to queue a task to each and remove the task from all other queues when the first generator completes the job. Consider tracking the object state when a regeneration is in progress so that multiple background regeneration tasks can be active without duplicating work unintentionally. Once again, this can be supplanted into your existing caching system or handled by a dedicated caching software package.
A third problem is concerned with what to do when a client requests data that is not cached and needs to be regenerated. If the data needs to be fully regenerated you will be stuck making the client wait for regeneration to complete, to help with long content generation times you could identify a policy for predictive prefetching content objects into cache but requires a method to identify relationships between content objects. Whether you want to serve the client a "regenerating" page until the requested content is available really depends on your client's expectations. Consider multi-level caches with compressed data archives if content regeneration cannot be improved from 10-15 seconds.
Making good use of a mature web caching software package will likely address all of these issues. Nick Gerakines mentioned Varnish which appears to be well suited to your needs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2836365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: picking a DataRow Based on maximum of certain field and criteria using LINQ here is my code (which doesn't work, obviously) .But, Could not figure out how to achieve this...
DataRow dRow = dsMain.tblStudentMaster.Select("stM_ClassNo=VI")).Max<DataRow>(row => row["StudentRollNo"]);
In a particular ClassRoom, I want to pick up student having Maximum Roll No.
Well, I want that DataRow and not the RollNo (which is obviously available once I get that row).
A: You have to order the rows accordingly:
DataRow dRow = dsMain.tblStudentMaster.AsEnumerable()
.OrderByDescending(r => r.Field<int>("StudentRollNo"))
.FirstOrDefault();
(assuming that the type of the column StudentRollNo is int)
A: You can also try MaxBy extension method from MoreLINQ
dsMain.tblStudentMaster.MaxBy(item => item.FieldYouWantMaxFrom);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16789603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Allowing Ping from Mininet to External VM how do I allow pinging from hosts inside Mininet to External VM using RYU controller.
In terms of pinging, i am able to ping as the following:
*
*hosts to hosts
*hosts to switches
*RYU controllers / S1-3 Switches to internet
*RYU controllers / S1-3 Switches to External VM.
Hence, I am looking for solutions on how to allow host (h1-6) to connect to the internet or external vm.
enter image description here
A: This is possible via configuring VirtualBox (if you are using it). There are more than one way to do it, but take a look at this tutorial
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73152418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Tarfile recursively opens in windows, but not in Linux [Python] I have a Python program which extracts a zip file. The zip file looks like this:
a.zip
|
|
--- b.tar.gz
. |
. |
. --- c.tar
Here is my code:
with zipfile.ZipFile("a.zip", 'r') as zipRef:
with zipRef.open("b.tar.gz") as x:
x_filedata = io.BytesIO(x.read())
with tarfile.open(fileobj=x_filedata) as tarRef:
tarFiles = tarRef.getmembers()
for fileInTar in tarFiles:
print(fileInTar)
In Windows, this code recursively opens c.tar too and prints the contents of c.tar file. But in Centos, it prints c.tar. Why is this happening?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71554457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: WPF - DataGridColumnHeader text does not bind I am trying to initiate a DataGrid in C#/WPF and have the text of the respective column headers bind to a value in the ViewModel. However, this does not seem to work. Here is the xaml for the DataGrid:
<DataGrid ItemsSource="{Binding Measurements}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Timestamp}" Width="Auto">
<DataGridTextColumn.Header>
<TextBlock Foreground="Black" Text="{Binding Text_Header1}"/>
</DataGridTextColumn.Header>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
And here is the value in my ViewModel
public string Text_Header1 { get { return local.Header1Text; } }
All the other Databinding for the DataGrid works just fine. It's just the title of the headers that doesn't seem to work.
I tried changing the Text property to a non-binding value and that one shows. So this seems to be the right way to set the text. I also tried having the Text_Header1 just return "Test" or bind it to other values that I know word in other elements and that did not work either. The column header just appears as empty when the Binding is set.
I have also tried setting the Binding up like this
<TextBlock Text="{Binding Text_Time, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" Foreground="Black"/>
and it has also not worked. The header stays blank.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75624721",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Creating Google Maps Control that you can drag and drop markers onto map to get their coordinates I am creating a GoogleMaps v3 Custom Control that is similar the the little yellow man on google maps. The control has an icon in the top left corner of maps. The user will drag and drop that icon onto the map. Then I just want to get the latlng for that location.
It is not the same as a marker even though it seems like one.
here is what I have so far:
var draggableMarkerControl = document.createElement('div');
draggableMarkerControl.setAttribute('class', 'gm-draggable-container'); //h&w of 75px
map.controls[google.maps.ControlPosition.TOP_LEFT].push( draggableMarkerControl );
Does anyone have any thoughts on what to do next? Maybe help find some similar code to work from?
A: I found your question whilst looking for essentially the same thing for my own project. I did find https://groups.google.com/forum/#!topic/google-maps-js-api-v3/7oWus3T5Ycw which I'm sure could be adapted, but if you look at the source of the example it says the code "is available for a fee".
My approach was going to be to place a temporary marker on the map at a certain position in the window, but then it would have to be recalculated and moved each time the map was moved or zoomed.
A: An alternative approach is to use the Drawing Library, as suggested on my post by Suvi Vignarajah
Positioning a draggable map marker at top-left of map window (there's a jsFiddle in the comments that shows my final solution)
I'm still thinking your idea of a custom control is actually the best in terms of intuitive UX
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19431184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits