text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: Android Studio- Attempt to invoke interface method 'android.graphics.Canvas android.view.SurfaceHolder.lockCanvas()' on a null object reference Very much a newbie to Android Studio and StackOverflow, so please forgive me in advance.
I've tried to make a simple android program that outputs its own framerate.
When I run it I get this error:
Attempt to invoke interface method 'android.graphics.Canvas android.view.SurfaceHolder.lockCanvas()' on a null object reference
I'm fairly certain this is the problem area for the program:
while(running){
startTime=System.nanoTime();
canvas=null;
try{
canvas=this.surfaceHolder.lockCanvas();
synchronized(surfaceHolder){
this.gamePanel.update();
this.gamePanel.draw(canvas);
}
}catch(Exception e) {
e.printStackTrace();
}finally{
if(canvas!=null){
try{
surfaceHolder.unlockCanvasAndPost(canvas);
}catch(Exception e) {
e.printStackTrace();}
}
}
I've copied it directly from this tutorial: https://www.youtube.com/watch?v=OojQitoAEXs and as far as I can tell I copied it line for line. Do you know how I can fix this error?
Here is the whole program if it helps (sorry for the dump):
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.view.Window;
import android.view.WindowManager;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(new GamePanel(this));
}
}
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.MotionEvent;
import android.graphics.Canvas;
import android.content.Context;
import java.lang.Thread;
public class GamePanel extends SurfaceView implements SurfaceHolder.Callback
{
private MainThread thread;
public GamePanel(Context context){
super(context);
getHolder().addCallback(this);
thread=new MainThread(getHolder(), this);
setFocusable(true);
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height){
}
public void surfaceCreated(SurfaceHolder holder){
thread=new MainThread(getHolder(), this);
thread.setRunning(true);
thread.start();
}
public void surfaceDestroyed(SurfaceHolder holder){
boolean retry=true;
while(true){
try{
thread.setRunning(false);
thread.join();
}catch(Exception e){
e.printStackTrace();}
retry=false;
}
}
public boolean onTouchEvent(MotionEvent event) {
return super.onTouchEvent(event);
}
public void update(){
}
public void draw(Canvas canvas) {
super.draw(canvas);
}
}
import android.view.SurfaceHolder;
import android.graphics.Canvas;
public class MainThread extends Thread {
public static final int MAX_FPS = 30;
private double averageFPS;
private SurfaceHolder surfaceHolder;
private GamePanel gamePanel;
private boolean running;
public static Canvas canvas;
public void setRunning(boolean running){
this.running=running;
}
public MainThread(SurfaceHolder surfaceholder, GamePanel gamepanel){
super();
this.surfaceHolder=surfaceHolder;
this.gamePanel=gamePanel;
}
public void run(){
long startTime;
long timeMillis=1000/MAX_FPS;
long waitTime;
int frameCount=0;
long totalTime=0;
long targetTime=1000/MAX_FPS;
while(running){
startTime=System.nanoTime();
canvas=null;
try{
canvas=this.surfaceHolder.lockCanvas();
synchronized(surfaceHolder){
this.gamePanel.update();
this.gamePanel.draw(canvas);
}
}catch(Exception e) {
e.printStackTrace();
}finally{
if(canvas!=null){
try{
surfaceHolder.unlockCanvasAndPost(canvas);
}catch(Exception e) {
e.printStackTrace();}
}
}
timeMillis=(System.nanoTime()-startTime)/1000000;
waitTime=targetTime-timeMillis;
try{
if(waitTime>0){
this.sleep(waitTime);
}
}catch(Exception e) {
e.printStackTrace();
}
totalTime+=System.nanoTime()-startTime;
frameCount++;
if(frameCount==MAX_FPS){
averageFPS=1000/(totalTime/frameCount)/1000000;
frameCount=0;
totalTime=0;
System.out.println(averageFPS);
}
}
}
}
A: you need to change the following line
canvas=this.surfaceHolder.lockCanvas();
to
canvas=surfaceHolder.lockCanvas();
for simple reason. Scope of the variable
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49740383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Python Stock Portfolio Rebalancing based on Factors (excel Solver imitation) Would like to calculate optimal weights and stock combo to add to portfolio to minimize certain exposures.
For example, I have below portfolio of stocks with stock sensitivity to 5 factors and sumproduct to get total portfolio sensitivities.
I want to pull the right combo of stocks from below list to minimize the difference in sensitivities between the portfolio and benchmark. The addition would need certain constraints such as: WGT cannot be negative, SUM of WGT have to equal to 1, each ticker cannot have WGT exceed 20% (0.2)
The list of stocks are narrowed down to 5 for example purposes.
What would be the best way to go about coding this in python?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75537342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C++ aligned unaligned property of arrays EDIT:This is from a working project of mine. Working.
I declared some char arrays at the beginning of .cpp file(even before the #include parts). Then i could use these arrays with "instructions for 16-Byte aligned variables".
Question: what happens if i use this .cpp file in another .cpp file as an include? Could i use that arrays for aligned operations in another projects too?
Question-2: is there a short-cut for this? I dont want to place all my variables in the beginning.
Some of the code:(i worked on some 16-Byte-aligned arrays)
//I put these arrays at the beginning, so they are aligned
//for the movaps instructions(x2 speed for reading and writing memory)
float v1[16];
float v2[16];
char counters[32];
char array_of_ones[32];
char source_array[4096];
char destination_array[4096];
struct bit_field
{
bf1:32;
bf2:32;
bf3:32;
bf4:32;
}some_area;
struct bit_mask_x
{
bf1:32;
bf2:32;
bf3:32;
bf4:32;
}some_mask;
float var_fast[16];
char alignment_purge[5]; //for the unalignment tests
char unaligned_source_array[4096];
char unaligned_destination_array[4096];
#include <math.h>
#include<stdlib.h>
#include<stdio.h>
#include<time.h>
.....
.....
What happens if i include this program in another like this:
#include <math.h>
#include<my_aligned.h> <-------- or my_aligned.cpp
#include<stdio.h>
#include<time.h>
Do i have to use a .h file for this?
Thanks...
A: Have you actually tried if this aligns your variables correctly? When you compile, the executable always has a header whose size may not be a multiple of 16. Also, alignment_purge may not really get the variables following it out of alignment, because the compiler may add padding. Finally, the headers don't introduce variables, so if you put your variables above or below headers, that doesn't change anything.
You can take a look at this question to see how to request aligned memory.
As a side note, normally you wouldn't want to include source files into another file. See this question on this subject.
A: Putting variable declarations at the top of a file is not required to enforce any specific alignment. You may just be getting lucky here, or it may be an idiosyncrasy of your compiler.
If you're using gcc, you can use the aligned attribute to request the correct alignment - other compilers probably have equivalent extensions or #PRAGMAs.
eg. your variable declarations with gcc's extension would look like:
float v1[16] __attribute__ ((aligned (16)));
float v2[16] __attribute__ ((aligned (16)));
If you need it to be entirely portable, I think your only solution is to dynamically allocate a large block of memory, and then manage the alignment of allocated blocks within it yourself.
Note that the alignment only needs to be enforced where the variables are actually stored, in the .cpp file. You can just forward declare them in a header, and that will let you refer to them in your other files. #includeing the .cpp file is not only unnecessary, it will cause a link error as every file has its own copy of the variables with the same names.
OP is using Digital Mars (if you'd mentioned this right away, I would have looked it up).
Searching for digital mars alignment, the first hit is the pragma documentation. I looked at align first, and it referred me to pack.
Using this, your code would look like:
#pragma pack(push, 16)
float v1[16];
float v2[16];
// ... any other aligned variables defined here
#pragma pack(pop)
However, pack affects the alignment of members inside structures - it's not clear what it does for global variables.
I think, to be certain, you need to write an aligned allocator: start by searching _aligned allocation C++` for example, and post a dedicated question if you can't figure it out.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11645596",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Does scoping in julia 1.0.0 with for-loops make sense to beginners? In julia 1.0.0, I get the following for-loop scoping behavior:
julia> counts = 0
0
julia> for i in 1:10
counts += 1
end
ERROR: UndefVarError: counts not defined
I found the solution was to make the counts variable global inside the for loop.
julia> for i in 1:10
global counts += 1
end
julia> counts
10
However, as a newcomer to julia this behavior almost made me quit the language because it seems so different from other languages.
Now that I see the solution above, I wonder if this is intuitive to beginning julia users. It was not intuitive to me, though I was finally able to solve it after quite a bit of time.
Here is the confusing part. I thought making a variable global when it was initialized would solve the problem. It does not:
julia> global c = 0
julia> for i in 1:10
c += 1
end
ERROR: UndefVarError: c not defined
It would seem natural that the global scope of c above would flow down into the for-loop, but the first initialization of c in the for-loop apparently creates a different for-loop local c.
Does this make sense to experienced julia developers?
A: I think there is agreement that, for interactive usage, this behavior is not optimal and it is likely going to change to the expected behavior in the REPL, IJulia etcetera soon. You can find the discussion here: https://github.com/JuliaLang/julia/issues/28789
Note, however, that everything works as expected once you wrap it into a local scope, such as a function or a let block for example.
See my answer here: Scope of variables in Julia for some more information/references.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52187073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: Twilio 11200 errors in sms status callback We are using node.js to send SMS to customers, and recently added the status callback to log sent and delivered statuses. We are also now seeing a ton of 11200 errors in our Twilio logs on calls that apparently were successful. Looking at the debugger, I see this in the response body:
Twilio was unable to fetch content from:
https://api.mycompany.com:443/api/1.0/sms/response Error: Error
reading response: Response does not contain content type
and the message text has:
Msg "Request to StatusCallback URL was unsuccessful."
httpResponse "502"
On our side, the handler for /api/1.0/sms/response takes the MessageSid sent with the response, matches it to one in the database, then looks at the MessageStatus. For "sent" it logs the current time in a sent field and saves it back to the database, likewise for delivered. At the end, it just does a res.end() as shown in the node.js example.
Here's the code:
app.post('/api/1.0/sms/response', function(req, res) {
var post_id = req.body.MessageSid || "";
var status = req.body.MessageStatus || "";
var item = Item.create(globals);
if (post_id === "") {
globals.logger.error(moduleName, "POST sms/response", "Missing MessageSid: " + JSON.stringify(req.body), true);
res.end();
return;
}
item.loadFromPostId(post_id).then(function() {
if (status.toLowerCase() === "sent") {
item.sent = new Date();
}
else if (status.toLowerCase() === "delivered") {
item.delivered = new Date();
}
item.save().then(function() {
res.end();
});
});
});
Looking at a couple of the errors, they are when Twilio is trying to send a "delivered" status to us. Checking our database for the MessageSids from these errors, the matching item has a timestamp in the "delivered" column, so it made it all the way through the code to the save.
We also have nothing but 200 responses in our nginx log (which we are using in front of node) for this endpoint, no upstream timeouts and no 502s. So I don't know where this error is coming from, or how to get rid of it.
And yes, we should be handling undelivered, etc., but this was just a quick pass at getting some responses in.
A: Twilio developer evangelist here.
First up, you have nothing to worry about here. As you say, you are receiving the callbacks and doing what you need to. You probably want to stop the debugger icon flashing at you in your Twilio console though.
From what I can see, this is a small oversight in the case of the Node.js example that you linked to.
Just calling res.end() closes the stream. It appears that if nothing else has been set, this means the response will get a status code of 200 and no body. While Twilio doesn't expect a response to callbacks like this, it seems it still wants to know something happened.
The error message says that the response didn't have a content type. You can remedy this by setting a content type on the response by calling res.set('Content-Type', 'text/plain') before you call res.end() and that seems to please the Twilio HTTP client.
Alternatively, you can use the express response method sendStatus to set the status and content type of the response in one call. Just call res.sendStatus(200) and the response will be set to text/plain, the status will be 200 and there will be a body of "OK". The Twilio HTTP client will happily accept all of that.
I recommend you change your calls to res.end() to res.sendStatus(200) and I'm going to go fix that in the Node.js example too.
A: You should respond with HTTP status code 204:
res.status(204).end();
The 204 status is still a success, like 200, but specifically means you are not sending any content back (https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html).
Note that the following also works, and doesn't need the end():
res.sendStatus(204);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49289113",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Insert into else update from array Hoping someone can point me in the right direction with this as i'm not able to get this working.
This is what happens:
My client uploads a (Rightmove) .blm file to server, Script unpacks the zip file and using a parser gets the properties into an array.. From here I'm able to INSERT into the database no problem however, i need this to update information in the database if exists otherwise insert as the blm file may contain New properties or existing ones editted.
The blm file only contains property information, there is no id etc so once inserted into the database i give it an id (propid) by means of auto incriment.
Please view the code below and hopefully you may have a suggestion that i could use to get this doing what i need it to do :)
foreach ($rmdata as $key => $properties) {
$fields = array();
$values = array();
foreach ($rmdata[$key] as $field=>$value) {
if (!isset($value)) {
}
if (isset($value)) {
$sql_props = mysql_query("SELECT propid FROM epsales");
while($row = mysql_fetch_array($sql_props)){
$propid = $row["propid"];
}
$fields[] = $field;
$values[] = "'".$value."'";
$array1 = array($field);
$array2 = array($value);
$sqlupdate = array_combine($array1, $array2);
foreach ($sqlupdate as $field=>$value) {
$sql_update = "$field='$value', ";
}
}
}
$sql_fields = implode(', ', $fields);
$sql_values = implode(', ', $values);
$sqlPropInsert = mysql_query('INSERT INTO epsales ('. $sql_fields .') VALUES ('. $sql_values .') ON DUPLICATE KEY UPDATE SET '. $sql_update .'');
Thank you for your time it's greatly appriciated!
A: Several notes:
*
*foreach ($rmdata[$key] as $field=>$value) is the same as foreach ($properties as $field=>$value) in this context
*the whole if(isset($value)) thing can be avoided by starting that loop with if(!$value) continue;
*When you select for the propid, you are selecting every row in the table, surely this is not what you intend to do, since you loop through them all and only every use the last one.
*the section building the update section is flawed in a few ways. The simplest fix is to realize that you can achieve the correct result by re-combining the $fields and $values arrays after the loop (as shown later)
*I can't readily see where you would get the conflict of keys, unless $rmdata will contain a propid if it's an update instead of an insert, or else if there is some other key and it's just being handled without explicitly seeing it in the code, which would be fine.
Below is code which I copied directly from yours and just modified to address these issues:
foreach ($rmdata as $properties) {
$fields = array();
$values = array();
$updates = array();
foreach ($properties as $field=>$value) {
if (!$value) continue;
$fields[] = $field;
$values[] = "'".$value."'";
$updates[] = $field . '="'.$value.'"';
}
$sql_fields = implode(', ', $fields);
$sql_values = implode(', ', $values);
$sql_updates = implode(', ', $updates);
$sqlPropInsert = mysql_query('INSERT INTO epsales ('. $sql_fields .') VALUES ('. $sql_values .') ON DUPLICATE KEY UPDATE SET '. $sql_updates .'');
}
note that this technique requires something in the data to have a conflicting key in order for the ON DUPLICATE KEY to trigger. If there is some value in the data array which you can uniquely identify these rows by, that field should be a UNIQUE KEY in the database, which will 'cause this conflict to occur quite nicely.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11498536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Mercurial hg status displaying ignored files Can anyone tell me why mercurial is displaying ignored files for the 'hg status' command?
Here's the confirmation that mercurial is indeed ignoring the files:
$ hg addremove
$ hg commit
nothing changed
Now, have a look at the status output. I ran this immediately after the lines above. (Prinout is partial, with identifiable text removed)
$ hg status
? Core/target/Core-0.0.1-SNAPSHOT-tests.jar
? Core/target/Core-0.0.1-SNAPSHOT.jar
? Core/target/classes/META-INF/MANIFEST.MF
? Core/target/classes/xxx/yyy/zzz/X.class
? Core/target/classes/xxx/yyy/zzz/XBackup.class
? Core/target/classes/xxx/yyy/zzz/XBackupInput.class
? Core/target/classes/xxx/yyy/zzz/XBackupOutput.class
? Core/target/classes/xxx/yyy/zzz/XImpl$GetResultsAndStatistics.class
? Core/target/classes/xxx/yyy/zzz/XImpl$MonitoringMode.class
? Core/target/classes/xxx/yyy/zzz/XImpl$UpdateMode.class
? Core/target/classes/xxx/yyy/zzz/XImpl.class
? Core/target/classes/xxx/yyy/zzz/XIsFullException.class
? Core/target/classes/xxx/yyy/zzz/XSource.class
? Core/target/classes/xxx/yyy/zzz/XUsageException.class
? Core/target/classes/xxx/yyy/zzz/CheckResults.class
? Core/target/classes/xxx/yyy/zzz/Noise.class
? Core/target/classes/xxx/yyy/zzz/core/DateTimeGenerator$TemporalMeasure.class
? Core/target/classes/xxx/yyy/zzz/core/DateTimeGenerator.class
? Core/target/classes/xxx/yyy/zzz/core/LoggingConfigurator.class
? Core/target/classes/xxx/yyy/zzz/core/ManagedIterator.class
? Core/target/classes/xxx/yyy/zzz/core/NetworkUtils.class
? Core/target/classes/xxx/yyy/zzz/core/StackTraceUtils.class
? Core/target/classes/xxx/yyy/zzz/core/Summarisable.class
? Core/target/classes/xxx/yyy/zzz/core/TimingUtils.class
? Core/target/classes/xxx/yyy/zzz/core/XMLStaticStringUtils.class
? Core/target/classes/xxx/yyy/zzz/core/Zipper.class
...
There's something like a thousand lines of these ignored files showing in the status printout; that's some serious guff.
How can I get rid of this?
Thanks
UPDATE:
Here's my .hgignore file.
syntax:glob
.metadata*
syntax:regexp
^target.*$
^[^/]*/target.*$
^[^/]*/[^/]*/target.*$
^bin.*$
^[^/]*/bin.*$
^[^/]*/[^/]*/bin.*$
UPDATE:
Modified regexps a wee bit * -> .*
A: Your regexp syntax is wrong. You have this:
syntax:regexp
^target*$
which means "ignore anything beginning with target and ending with an asterisk
Which fails to ignore these:
Core/target/classes/META-INF/MANIFEST.MF
Core/target/classes/xxx/yyy/zzz/X.class
for two reasons -- they begin with Core/ not target and they don't end with an asterisk.
What you probably meant was this:
syntax:regexp
^.*/target/.*$
which matches anything that has /target/ in it (notice it's .* in a regexp * is for glob style). However the ^ and $ only serve to root your regex and you don't want it rooted -- you want to find it anywhere in the string, so just do this:
syntax:regexp
/target/
The clue in all this was that the files were marked with ? which means not ignored and not added, if they were ignored you wouldn't see them at all without adding --ignored to the status command.
A: I got similar issue because I changed letter case for some files. So previously I got file called "sitenav.ext", renamed it to "siteNav.ext" and started to have same sort of issues - when I tried to "hg st" I got "? siteNav.ext".
Fix was easy
rename to "_siteNav.ext",
addremove,
commit,
rename back to "siteNav.ext",
addremove,
commit -> profit!
A: As commented by Jerome in the question, providing your config might help.
One (admittedly strange) reason for your problem could be a permission issue with the .hgignore file combined with exclude defaults for the addremove command.
I could reproduce your situation by revoking any read permission from the ignore file and by using -X "**/target/**" as a default option for the addremove command (which might be set in any of the possible Mercurial configuration files):
$ hg st
# no output, as expected
$ chmod 000 .hgignore
$ hg addremove # with '-X "**/target/**"' set as default somewhere
$ hg commit
nothing changed
$ hg st
? Core/target/Core-0.0.1-SNAPSHOT-tests.jar
? Core/target/Core-0.0.1-SNAPSHOT.jar
...
hg fails in reading the ignore file and thus does not know that the target stuff should be ignored. A corresponding warning from hg would be helpful here.
This question has been updated in response to Jerome's comment.
A: Many thanks for everyone's help on this. I haven't found an answer to the problem but I did find a workaround that got rid of it. So I'm assuming that at some point when modifying the hgignore regexps mercurial got confused and corrupted it's internal data... or something. I don't know enough internals to know what this could have been.
Anyway, should you find yourself in the same boat, here's what I did:
*
*Make sure your .hgignore file says what you want it to and that all the files turning up in the hg status are the ones you want to ignore.
*Add all the files to be ignored. hg addremove doesn't work because it does honour the hgignore contents, so I used Eclipse's hg plugin and did each file manually (well, I selected them all and Eclipse applied the add to them all individually).
*Revert all added files. I used the following because I'm on linux. (thanks to another poster on a separate question here on SO - which I can now no longer find unfortunately)
hg status -an0 | xargs -0 hg revert
*repeat the above step until it no longer works. In my case this was sometimes up to as many as 3 reverts in a row! (No idea what it was actually doing though :( )
*commit
You should now no longer see the ignored files in the hg status output.
I'm sorry, I have no idea why this worked, or what the original problem was. If anyone does, I'd be very interested to know your thoughts.
Many thanks again to everyone :)
A: ? does not mean ignored.
It just means that mercurial is not tracking the file.
If you don't want to see them just do
hg status -mard
i.e. only show modified, added, removed, deleted
A: Your .hgignore file says "^target" is ignored, but the files are in Core/target. So the ignore line should rather be "target" (without the ^) or "^Core/target".
Or am I missing sth here?
(Note: ^ implies that regex matching starts from the beginning of the path, i.e. only paths starting with target would be matched!)
A: Had the same problem and Bob's answer did the trick for me.
If you are using TortoiseHg you can select "edit ignore filter" in the context menu (windows) to verify and change your .hgignore settings there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5390129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: AS3 - Show splash screen until all is code is loaded I am developing an adobe air mobile app and after I launch it, if I click the buttons right away, the sound does not play. If I wait a few seconds, the buttons function normally. How do I have a movie clip/splash screen show on top until all is loaded so I don't have this problem? thanks for your help.
A: Are your sounds embedded in the app or are you loading them at runtime? I assume embedded, but in that case it shouldn't take time before they are available.
If loading sounds at runtime, just respond to Event.COMPLETE to hide your splash screen. Or use setTimeout with a suitable delay if you have no events to respond to:
//wait 5000ms
setTimeout(hideSplashScreenFunction, 5000);
....
function hideSplashScreen():void
{
//hide splash screen
}
A: You can set splashScreenMinimumDisplayTimeproperty you can achieve. Like this
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
splashScreenImage="@Embed('assets/icons/chrome/logo.png')"
splashScreenMinimumDisplayTime="4000" splashScreenScaleMode="none">
Hope it will help you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13907661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: woocommerce product with multiple categories, active category in sidebar I need some food for thought on this because I have had trouble finding a decent solution here.
There is a woocommerce shop, categories on the left side (sidebar) and on the right side products. A product can have multiple categories; for example, the product "Burger" is in the categories "Food" and "Fastfood".
Now on the left side we have the categories "Food" and "Fastfood" with both "Burger" in them.
I go to category "Food". On the left side in the sidebar I highlight the category food with:
(start loop going through categories)
if(get_query_var('product_cat') == $cat->slug) - echo <li class="active">
else - echo <li class="active">
(end loop)
so the category "Food" is highlighted. Then I select the product "Burger".
Now, because the product "Burger" is also in the category "Fastfood", the category "Fastfood" is displayed as active.
The active category should be based on the category that the product was selected from originally ("Food"). If you go to the category "Fastfood" and select "Burger", then "Fastfood" should be active. Open "Burger" from "Food", "Food" should be the active category.
My attempt is to change the category in the permalink (<?php the_permalink(); ?>) to the current category when displaying all the products, but it just doesn't feel like the right way.
Maybe someone has a better solution.
Wish you a good day!
EDIT:
I've managed to create the permalink with the right category:
$custom_permalink = get_settings('siteurl')."/".get_query_var('product_cat')."/".basename(get_permalink());
Sadly this does not work.. (redirects me to the "wrong" category) but I don't like this hack anyways :)..
A: I got it working. This is what I did:
In your custom template file /yourtheme/woocommerce/content-product.php you will change the a href.
Code that generated the new permalink (using the current selected category):
// HOOK FOR CORRECT ACTIVE SIDEBAR ELEMENT WHEN PRODUCT HAS MULTIPLE CATEGORIES
if(get_query_var('product_cat') == ""){
$product_categries = get_the_terms( $post->ID, 'product_cat' );
foreach ($product_categries as $category) {
$cur_cat = $category->slug;
}
$custom_cat = $cur_cat;
}else{
$custom_cat = get_query_var('product_cat');
}
$custom_permalink = get_permalink(5).$custom_cat."/".basename(get_permalink());
I also check if a category is set (because there is none if you are viewening "All Products", in this case I loop through the Products and get their category to use it in the permalink).
The get_permalink with the id 5 is basically my shop-page, so it stays dynamic when you change the permalink from your shop. Don't like hardcoded stuff here because it's already an ugly hack.
Place this code before the a href that wraps your Product, in my case this was on line 42 (Woocommerce V2.0.10).
Then change this a href from
<a href="<?php the_permalink(); ?>">
to
<a href="<?php echo $custom_permalink; ?>">
I hope this will help you when you face the same issue!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17490933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Re-design suggestions for the attached code segment My program needs to run like this:
./myprogram inputType [Can be I1, I2 or I3]
Most of the functions of this program are like:
void Foo::foo (IType inputType) {
// Some common code
if (inputType == I1) ... // some I1 specific code
if (inputType == I2) ... // Some I2 specific code
...// similarly for I3
}
These checks of inputType are scattered over multiple places and with time have became increasingly difficult to manage. I have thought of refactoring this code to something like :
InputType* iType = new InputTypeI1(); // or I2 or I3
void Foo::foo (IType inputType) {
// Some common code
iType.DoSomething(this, arg1, arg2,..)
}
class InputType1 : public InputType
{
// Virtual functions.. (with default implementations)
}
InputType1::DoSomething(Foo* f, Arg1* arg1, Arg2* arg2)
{
f->DoSomethingFor1(arg1, arg2);
}
This results in organizing things for I1, I2 or I3 as well as automatically call relevant function based upon the input type.
However, I feel this could be done better. Any suggestions?
A: Difficult to tell from the snippet you provide, but I'd consider having three derived foo classes, FooI1, FooI2 and FooI3, and constructing the appropriate one with a factory based on InputType.
Then all the specializations just get implemented in virtual methods for each of the new classes.
class FooI1: public Foo {
void doSomething() {...};
}
ditto for I2/I3..
Foo * fooFactory(InputType iType)
{
return new FooX - depending on iType
};
Foo *f = fooFactory(i)
f->doSomething();
A: your current code couples Foo and InputType:
1. Foo creates InputType Object
2. InputType calls Foo function
Suggested solution is:
1. Decouple InputType and Foo by using composites mode
Foo could hold a pointer to `InputType*` then call InputType `virtual` function.
2. To make InputType, a factory will simple enough.
Sample code:
class InputType
{
public:
virtual ~InputType();
virtual void DoSomething();
};
InputType* MakeInputObject(const IType& inputType)
{
return new InputTypeX;
}
class Foo
{
public:
Foo(const InputType& input) : input_type_ptr(MakeINputObject(input) {}
void DoSomething() { input_type_ptr->DoSomeThing(); }
private:
std::unique_ptr<InputType> input_type_ptr;
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14436789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What happens after modifying Kafka topic replication factor? According to the docs, you just modify a topic to increase the replication factor.
> bin/kafka-topics.sh --zookeeper zk_host:port/chroot --create --topic my_topic_name
--partitions 20 --replication-factor 3 --config x=y
Unfortunately, it doesn't specify what happens then after you modify the topic. Do existing log segments get replicated to the new replicas, or only new messages?
A: For kafka 10 you need to invoke the kafka-reassign-partitions.sh script to change the replication factor of the topic.
Here is a demo of a script that will display the topic before and after the change:
updateTopicReplication() {
TOPIC_NAME=$1
REPLICAS=$2
echo "****************************************"
echo "describe $TOPIC_NAME"
bin/kafka-topics.sh --zookeeper localhost:2181 --describe --topic $TOPIC_NAME
JSON_FILE=./configChanges/${TOPIC_NAME}-update.json
echo $JSON_FILE
[ -e $JSON_FILE ] && rm $JSON_FILE
touch $JSON_FILE
echo -e "{\"version\":1, \"partitions\":[{\"topic\":\"${TOPIC_NAME}\",\"partition\":0,\"replicas\":[${REPLICAS}]}]}" >> $JSON_FILE
echo "****************************************"
echo "updateing $TOPIC_NAME"
bin/kafka-reassign-partitions.sh --zookeeper localhost:2181 --reassignment-json-file $JSON_FILE --execute
echo "****************************************"
echo "describe $TOPIC_NAME"
bin/kafka-topics.sh --zookeeper localhost:2181 --describe --topic $TOPIC_NAME
}
A: It seems that kafka actually doesn't support increasing (or decreasing) the replication factor for a topic, according to the same docs I mentioned in the question.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31194995",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Unit Testing for the following : Tring to set up a unit testing for the following code, but I keep getting this: Comparing two different types of values. Expected string but received undefined. as an error
Test :
import {prepadSigned} from './utils';
describe('prepadSigned', () => {test('should prepend `00` to the input <', () => {
const str = '-10';
const actual = prepadSigned(str);
const expected = '00-10';
expect(actual).toEqual(expected);
})
Code:
function prepadSigned(hexStr) {
const msb = hexStr[0];
if (msb < '0' || msb > '7') {
return `00${hexStr}`;
}
return hexStr;
}
I expect a unit test to pass with some input/output.
I keep getting the following :
expect(received).toEqual(expected)
Expected value to equal:
"00-10"
Received:
undefined
A: Unless you deliberately left out export when you wrote,
changing
function prepadSigned(hexStr) {
...
}
to
export function prepadSigned(hexStr) {
...
}
may fix the problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53935426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Task. How to find out the amount that will remain on the user's wallet after js purchases There are three arrays, the data comes from the back-end and we do not know exactly which names or products will come, we need to calculate how much the user has spent and how much he has left in his wallet. It should be borne in mind that when the user does not have enough money, he can use a loan, this money will go to his wallet additionally.
I tried to solve through a huge number of loops, going through each array and comparing the values, but I need a solution with the algorithmic complexity On.
var product = [
{'name':'пряник', 'price':10},
{'name':'кофе', 'price':2},
{'name':'мороженное', 'price':4},
{'name':'макароны', 'price':5},
{'name':'персик', 'price':6},
{'name':'ананас', 'price':15},
]
var purse = [
{'name':'Катя', 'cash':100},
{'name':'Даня', 'cash':200},
{'name':'Ваня', 'cash':400},
{'name':'Саня', 'cash':500},
{'name':'Маня', 'cash':600},
{'name':'Кира', 'cash':150},
]
var purchases = [
{'name':'Катя', 'item':'пряник'},
{'name':'Даня', 'item':'макароны'},
{'name':'Даня', 'item':'кофе'},
{'name':'Даня', 'item':'кофе'},
{'name':'Маня', 'item':'ананас'},
{'name':'Катя', 'item':'мороженное','credit': 20},
]
A: Maybe something like this would help? I briefly considered merging the objects into one big set of objects that had all the information, which would make it easier to format. However, I decided instead to re-lookup the information on each loop. This should be a good start, I hope it helps!
var product = [
{'name':'пряник', 'price':10},
{'name':'кофе', 'price':2},
{'name':'мороженное', 'price':4},
{'name':'макароны', 'price':5},
{'name':'персик', 'price':6},
{'name':'ананас', 'price':15},
];
var purse = [
{'name':'Катя', 'cash':100},
{'name':'Даня', 'cash':200},
{'name':'Ваня', 'cash':400},
{'name':'Саня', 'cash':500},
{'name':'Маня', 'cash':600},
{'name':'Кира', 'cash':150},
];
var purchases = [
{'name':'Катя', 'item':'пряник'},
{'name':'Даня', 'item':'макароны'},
{'name':'Даня', 'item':'кофе'},
{'name':'Даня', 'item':'кофе'},
{'name':'Маня', 'item':'ананас'},
{'name':'Катя', 'item':'мороженное','credit': 20},
];
function displayInfo(name, walletVal) {
const displayArea = document.querySelector("#display");
const spendSummary = document.createElement("div");
spendSummary.classList.add("spendSummary");
const nameEle = document.createElement("div");
nameEle.classList.add("name");
nameEle.innerText = name;
spendSummary.appendChild(nameEle);
const walletEle = document.createElement("div");
walletEle.classList.add("wallet");
walletEle.innerText = walletVal;
spendSummary.appendChild(walletEle);
displayArea.appendChild(spendSummary);
}
const names = [...new Set(purchases.map(e => e.name))];
for (const name of names) {
const filteredPurchases = purchases.filter(e => e.name == name);
const costs = filteredPurchases.map(
({item: itemName}) =>
product.find(item => item.name == itemName).price
);
const creditsArr = filteredPurchases.filter(e => e.credit)
.map(e => e.credit);
const totalCredit = creditsArr.reduce((a,b) => a + b, 0);
const totalCost = costs.reduce((a,b) => a + b, 0);
const cash = purse.find(e => e.name == name).cash;
const currentWallet = cash + totalCredit - totalCost;
displayInfo(name, currentWallet);
}
#display {
display: flex;
justify-content: space-around;
font-family: arial;
}
.spendSummary {
display: flex;
flex-direction: column;
align-items: center;
}
.name {
box-shadow: 0 2px 2px -2px black;
}
<div id="display">
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69754807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How to set default value of select box with non-existed value in Angularjs Maybe this can has duplicated or maybe there's a way to solve this,
but I couldn't find any way to solve this.
So please don't be angry with my silly question and give me some information or way to solve this.
Please see this fiddle.
Set default value of select box
What I want is, when I get array from http call,
how to set default value of select box with the value which is not in array.
I've used ng-init but it didn't work.
I know there are other ways to solve this like using <options> tag and put first value of option or
using selected but I want to use ng-options.
No matter what you give is a link, doc, or something, it'll be great help to me.
I'll wait for your any comments or answers. :)
A: First solution you can add one more option tag for default value
Html Code
<div ng-app="MyApp">
<div ng-controller="MyCtrl">
<select ng-options="opt as opt for opt in testOpt"
data-ng-model="resultOpt"
data-ng-change="checkResultOpt(resultOpt)">
<option value=''>Choose Category </option>
</select>
</div>
</div>
Controller Code
var MyApp = angular.module('MyApp', [])
.controller('MyCtrl', ['$scope', function ($scope) {
$scope.testOpt = [
'ID',
'Name',
'Email',
'Address'
];
$scope.resultOpt = '';
}]);
Working code
Second Solution : you just add one more item in your array list after get from http call
Html Code
<div ng-app="MyApp">
<div ng-controller="MyCtrl">
<select ng-options="opt as opt for opt in testOpt"
data-ng-model="resultOpt"
data-ng-change="checkResultOpt(resultOpt)">
</select>
</div>
</div>
Controller Code :
var MyApp = angular.module('MyApp', [])
.controller('MyCtrl', ['$scope', function ($scope) {
$scope.testOpt = [
'ID',
'Name',
'Email',
'Address'
];
$scope.testOpt.splice(0, 0, 'Choose Category');
$scope.resultOpt = 'Choose Category';
}]);
Working Code
hope this will help you
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46480744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to temporarily override import behavior? I am using a module, module_1, that is able to use module_2 if it is installed on the system, but falls back on other implementation if it is not. The way it checks if module_2 is:
# module_1.__init__.py
try:
import module_2
_MODULE2 = True
except ImportError:
_MODULE2 = False
I have module_2 installed in the same environment but I don't want module_1 to use it.
Is there a way to import module_1 but override the import mechanism to make the import of module_2 specifically raise an ImportError?
What I've tried:
import sys
class hide_module_2:
def __enter__(self):
class HideModule2(dict):
def __init__(self, *args, **kwargs):
self.update(*args, **kwargs)
def __getitem__(self, key):
if key == 'module_2':
raise ImportError('Module 2 de')
super().__getitem__(key)
sys.modules = NoPandas(**sys.modules)
def __exit__(self, exc_type, exc_value, traceback):
# revert to regular dictionary
sys.modules = dict(**sys.modules)
with hide_module_2():
import module_1
I thought this would work since sys.modules is a dictionary of currently imported modules and I thought it would be referenced in the import.
A: I was able to devise a sort of hacky solution since the import system throws an ImportError if something is imported and sys.modules has a None in it:
class hide_module_2:
def __enter__(self):
self.module_2 = sys.modules.get('module_2')
sys.modules['module_2'] = None
def __exit__(self, exc_type, exc_value, traceback):
if self.module_2 is None:
sys.modules.pop('module_2')
else:
sys.modules['module_2'] = self.module_2
with hide_module_2():
import module_1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50883988",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: RocketMq:how can get RocketMQ topic and tags using Api How can I get all the tags in the topic of RocketMQ
A: it seems cannot be done for now.
when consumeing the topic, consumers would get all tags
A: Tags are only stored in messages, there is no global place to store all tags of a topic, so only consumers can specify tags for filtering and consumption
A: You can't! Since there are no ways to save all tags in the broker.
Actually, you need not know all the tags when you consume. You should only care about the tag you know. If there are some tags that a consumer does not know, which means the messages with that tag should not be consumed by it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72642387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: iphone sdk 4.3 - Skip through a list of images by using accelerometer Firstly, I wanted to say hello to the community. I have been a passive reader for a couple of weeks and have to say that stackoverflow is a great resource to learn. Recently, I am playing around with developing small iphone apps for myself in order to learn more about the SDK.
I'm getting familiar with the basic functions right now. One of my first projects was to skip through a list of images by using my finger. I am wondering now if this is possible with the motion sensor/ accelerometer as well.
Let's assume I have 4 distinct images (image1, image2, image3, image4). I want to display the image on my iphone and show the next or previous image by tilting my iphone to the right and left.
How would I start doing that? I am not sure if this is even possible.
Thanks for your help. Have a great day
Rachel
A: You can use an UIScrollView (what you assumably already did for touch control) and control it using acceleration.
In
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
See UIAccelerometer and UIScrollView here on StackOverflow.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7051345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: find duplicate 1kb chunks from a file TL;DR: How to identify duplicate non overlapping 1kb chunks from a file which is large and can be binary file too?
I recently came across this question in one of the challenges.
We are given a file name. This file's size will be in multiples of 1kb. We have to perform dedup operation on this file and write the modified content in another file. The dedup operation finds and removes the duplicate, non-overlapping 1kb chunks from the file. The file can be very large file and it can also be a binary file.
The second part of the question involved reversing the dedup operation and regenerating the original file from the deduped file.
My approach: I tried to use hashing as suggested in Adam Horwath's this blog. I calculated hash of each 1kb byte of data and stored it in a hashtable with hash as key and index of the chunk in consideration as value. here is my code to calculate the hash for 1kb of data (similar to inithash in the blog):
//implement hashing used in Rabin-Karp algorithm
// sum of p^n * a[x]
//hconst = 69069; //good multiplier for mod 2^32;
public static long calculateHash(int [] data, int chunkSize){
long hash = 1;
for(int i =0; i < chunkSize; i++)
{
int c = data[i];
hash *= hconst; //multiply with const
hash += c; //add the byte to hash
}
return hash;
}
There is something wrong (obviously) with my understanding or implementation that it didn't give the correct result. My questions are:
*
*Is the hashing approach correct to identify duplicate chunks?(Comparing each byte is costly process)
*Is there any better way to identify duplicate chunks?
A: Is there a better way than an in-core hash table? Yes. Especially if input files are larger than RAM.
You explained that you have a very large number of 1 KiB documents, a large number of file segments. Pre-process them by reading each segment and writing one line per segment to a temporary segments.txt file containing two columns. First column has a copy of segment contents, or SHA224 hash of contents. Second column has segment index number, which is a serial number starting with zero. Feel free to use just the first few bytes of the hash, depending on your sensitivity to hash collisions.
Now use /usr/bin/sort (out-of-core mergesort) to create segments_sorted.txt. At this point, your problem is trivial. Simply read each line, while remembering previous hash. If cur_hash == prev_hash you have identified duplicate chunks. The associated index lets you rapidly seek() to find the original contents in case ruling out potential collisions is important in your application.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48276187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do you integrate the new Google Sign-In on a Xamarin.Android app? I am attempting to follow Google's instructions on how to add the new Google Sign-In (not the old Google+ Sign-In) to my Xamarin.Android app. For the life of me, I cannot find the correct Google Play Services NuGet package or Xamarin component that supports the new sign-in system.
When I add the following code to the activity, I get "The type or namespace 'GoogleSignInOptions' could not be found. Are you missing an assembly reference?" build error.
// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
Here are the Xamarin.GooglePlayServices NuGet packages that are include in the project:
<package id="Xamarin.GooglePlayServices.Ads" version="27.0.0.0" targetFramework="MonoAndroid50" />
<package id="Xamarin.GooglePlayServices.Analytics" version="27.0.0.0" targetFramework="MonoAndroid50" />
<package id="Xamarin.GooglePlayServices.AppIndexing" version="27.0.0.0" targetFramework="MonoAndroid50" />
<package id="Xamarin.GooglePlayServices.Base" version="27.0.0.0" targetFramework="MonoAndroid50" />
<package id="Xamarin.GooglePlayServices.Basement" version="27.0.0.0" targetFramework="MonoAndroid50" />
<package id="Xamarin.GooglePlayServices.Identity" version="27.0.0.0" targetFramework="MonoAndroid50" />
<package id="Xamarin.GooglePlayServices.Location" version="27.0.0.0" targetFramework="MonoAndroid50" />
<package id="Xamarin.GooglePlayServices.Maps" version="27.0.0.0" targetFramework="MonoAndroid50" />
<package id="Xamarin.GooglePlayServices.Plus" version="27.0.0.0" targetFramework="MonoAndroid50" />
Is the new Google Sign-In system not yet supported on Xamarin or am I missing something?
A: Enable pre-release nugets and search for:
Xamarin.GooglePlayServices.Identity 29.0.0-beta1
packages.config:
<packages>
<package id="Xamarin.Android.Support.v4" version="23.1.1.0" targetFramework="MonoAndroid44" />
<package id="Xamarin.GooglePlayServices.Auth" version="29.0.0-beta1" targetFramework="MonoAndroid44" />
<package id="Xamarin.GooglePlayServices.Base" version="29.0.0-beta1" targetFramework="MonoAndroid44" />
<package id="Xamarin.GooglePlayServices.Basement" version="29.0.0-beta1" targetFramework="MonoAndroid44" />
<package id="Xamarin.GooglePlayServices.Identity" version="29.0.0-beta1" targetFramework="MonoAndroid44" />
</packages>
C# version of Integrating Google Sign-In into Your Android App
SignInButton button = FindViewById<SignInButton> (Resource.Id.sign_in_button);
gso = new GoogleSignInOptions.Builder (GoogleSignInOptions.DefaultSignIn)
.RequestEmail ()
.Build ();
mGoogleApiClient = new GoogleApiClient.Builder (this)
.EnableAutoManage(mLoginFragment, failedHandler)
.AddApi (Auth.GOOGLE_SIGN_IN_API)
.Build ();
button.Click += delegate {
signIn();
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34639015",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Why is a Segmentation fault (core dumped) happening in my doubly linked list? So from what I've read from other seg fault errors, it deals with accessing memory you shouldn't have access to (bad memory, or didn't use malloc()). For some reason there is no seg fault error when I make 2 nodes, but anything else gets a seg fault error. If someone one could please explain where I am going wrong in this program that would be extremely helpful. Thanks.
#include "header.h"
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main(int argc, char *argv[]) {
int N;
//int oddsonly = (BITS_PER_SEG*2) - 1;
int NSegs;
int numOfPrimes;
if (argc == 2) sscanf(argv[1],"%d",&N);
else scanf("%d",&N);
NSegs = (int)ceil(N/(float)odds_only);
printf("This is the number of segments made: %d\n", NSegs);
//this is how we make a doubly linked list
//void makelinkedlist(){
//this is how we make a doubly linked list
//void makelinkedlist(){
int i;
seg *node;
seg *current;
//head = (seg*)malloc(sizeof(seg));
head = NULL;
for(i = 1; i < NSegs; i++ ) {
if(i == 1) {
node = (seg*)malloc(sizeof(seg));
node->prev = NULL;
node->next = NULL;
head = node;
}//if
else{
current = (seg*)malloc(sizeof(seg));
current = head;
while(current->next != NULL){
current = current->next;
}//while
node = current->next;
node->prev = current;
node->next = NULL;
}//else
}//for
printf("Done allocating %d nodes\n",i); '
and my header file has this:
#ifndef EXTERN
#define EXTERN extern
#endif
#define SIZE_OF_SEG 256 // 256 int per segment
#define odds_only 16383
#define BITS_PER_SEG (8*SIZE_OF_SEG*sizeof(int))
typedef struct _seg { /* definition of new type "seg" */
int bits[256];
struct _seg *next,*prev;
}seg ;
EXTERN int NSegs;
EXTERN seg *head; // This variable will point to the
// start of the linked list of segments !!!
//EXTERN void clearAll( ); // Uses head to find the "bit array" (list)
EXTERN void sieveOfE( int N ); // Uses head to find the "bit array" (list)
EXTERN int countPrimes( int N ); // Uses head to find the "bit array" (list)
EXTERN void printPrimes( int N ); // Uses head to find the "bit array" (list)
A: In your for-loop, in the first iteration head is set to a new node.
In the second iteration, something strange is done:
current = (seg*)malloc(sizeof(seg));
current = head;
Now you've allocated some space, but you have overwritten the pointer to it (this is a memory leak). Afterwards it goes wrong:
while(current->next != NULL){
current = current->next;
}//while
node = current->next;
node->prev = current;
Here, node is set to NULL so you're writing into the null address, hence the core dump.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32673833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to make a view 100% window height? I'm brand new to react native. I'm trying to figure out how to make a box full height.
I have tried to add flex property to both container and view, but the height is not 100%.
export default class LinksScreen extends React.Component {
render() {
return (
<ScrollView style={styles.container}>
<View style={{ flex: 1, backgroundColor: '#fff', flexGrow: 1 }}>
<Text>Hallo</Text>
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
padding: 20,
backgroundColor: 'blue',
},
});
A: You need to wrap the ScrollView with a View that has height. ScrollViews must have a bounded height in order to work. You can read more details about that here: https://facebook.github.io/react-native/docs/scrollview
Do it something like below:
render() {
return (
<View style={styles.container}>
<View style={{height: 80}} >
<ScrollView
...
EDIT
Your code actually works. Maybe you just want to see if your scrollview works when the whole screen is occupied. Try this below and you will see, I simply multiplied the text contents 80 times:
render() {
return (
<ScrollView style={styles.container}>
<View style={{ flex: 1, backgroundColor: "#fff", flexGrow: 1 }}>
{Array(80)
.fill(1)
.map((item, index) => (
<Text>Hallo {index}</Text>
))}
</View>
</ScrollView>
);
}
A: Remove flex:1
Give height:"100%"
width: "100%"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55309458",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: grep'ing the files output from a previous grep I don't know if this is possible, or if grep is the wrong tool, or what, but what I want to do is this:
grep -rsI "some_string" *.c
Then pipe the list of files where were results were found into a second grep:
grep -rsI "second_string" <list of files from first grep>
I know I can pipe the exact lines to a second grep via:
grep -rsI "some_string" *.c | grep "second_string"
but that's not what I'm looking for, I don't want to just search the lines where previous hits were, but the entire file those lines were in. Is that even possible? Any ideas?
A: Use -l option to list files that match then xargs command to apply grep on those files.
grep -l -rsI "some_string" *.c | xargs grep "second_string"
A: grep -rsIl "some_string" *.c | xargs grep -sI "second_string"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12465867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Create XML doc with Linq to XML I have an ASP .Net site where i am attempting to create a page to allow the user to create an XML document. New with XML so I'm not sure if im missing something here but all i am trying to do is create an XML document using Linq to XML.
I saw this example as part of my research
Dim xmlDoc As XDocument = _
<?xml version="1.0" encoding="utf-16"?>
<!-- This is comment by you -->
<Employees>
<Employee id="EMP001">
<name>Wriju</name>
<![CDATA[ ~~~~~~~...~~~~~~~~]]>
</Employee>
</Employees>
xmlDoc.Save("somepath\somefile.xml")
but i just dont seem to be able to get it working in VS 2010 or VS 2013. As soon as i enter <?xml and enter to the next line i just get errors that the syntax is incorrect. Reading further i have seen some C# examples but they dont seem to be "readable" in VB .Net.
I've tried using online converters but again no luck in that either. Could anyone guide me or point me to the right direction to create an XML document with elements etc using Linq to XML? I think i can use XDocument but i'm a little confused if that would allow me to use Linq to XML or if this is an old concept.
Thanks
A: Use this
Dim xmlDoc As XDocument = <?xml version="1.0" encoding="utf-16"?>
<!-- This is comment by you -->
<Employees>
<Employee id="EMP001">
<name>Wriju</name>
<![CDATA[ ~~~~~~~...~~~~~~~~]]>
</Employee>
</Employees>
'it assume that /youfolder is in the root and it has read and write permission
xmlDoc.Save(Server.MapPath("/yourfolder/somefile.xml"))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23372547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: mailboxer mark message as read Using the rails gem mailboxer
I have just started using it but I see that the SocialStream code base is quite heavy and doesnt provide a simple overview
I'd like to know how to properly work with notifications, so that if a message is sent, the receiver user clicks the message (in part of a conversation) so that it marks the message as read, this in turn will show the sender that the message is read by the receiver
Using the examples I cant seem to get it working. If I use
current_user.mailbox.inbox.unread_messages_count
I seem to get a static number that doenst change, even if I mark all my messages as read
Does anyone have a view on how to do this?
Also how do I empty all messages, conversations, receipts etc
A: As per the Mailboxer readme, I saw this as the recommended way:
current_user.mailbox.inbox({:read => false}).count
I think that should update every time you refresh
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19347096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: AndroidStudio 2.1.1 changes made in xml doesn't get updated on run I am now using AndroidSudio 2.1.1 for my android development.
When I make any changes in xml files (layout , color, string, drawable etc) and then run my app, I don't see any changes in my output.
I have to clean or re-build my project to see the changes made in xml files.
I have already turned off instant-run still no use.
A: You should try to clean and Rebuild the project.
Then go to File/InValidate Caches and Restart and select Restart. It should solve your problem.
I've had the same error and I think this happened because of cache memory store value in Android Studio.
A: Try this button :
Or simlpy do clean , rebuild .
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37967556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Weighted effect coding in R I have a data set with a categorical variable and a continuous dependent variable, and I want to know the effect of deviation of mean of each category from the overall mean.
str(dat)
'data.frame': 380 obs. of 2 variables:
$ Pgene_3X : num 0 0 0.08 0 0.048 ...
$ CT : Factor w/ 22 levels "1:ATG1","10:ATC3",..: 15 15 21 21 21 21 21 21 21 15 ...
As the groups in the categorical variable are not balanced I want to use weighted effect coding in R.
I tried the package "wec".
dat$CTatg1 <- contr.wec("dat$CT",ref="1:ATG1")
But it gives me an error:
Error in contr.treatment(n.cat, base = ref) : not enough degrees of freedom to define contrasts
This function works on the dummy BMI data provided with R but not on my data.
Is there any other way to approach this problem. How can I compare the mean of each "CT" level with the overall weighted mean?
A: I just checked the manual of "wec" package.
I suspect that you may need to replace your argument "ref" with "omitted".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37394126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get averages from a dictionary in Python Get averages from a python dictionary for example if i have the next dictionary:
students={'Dan':(5,8,8), 'Tim':(7), 'Richard':(9,9)}
And i would like to print de dictionary in the next form:
results={'Dan':(7), 'Tim':(7), 'Richard':(9)}
is there any function that i can use? Im new coding in python so dictionaries are a bit confusing for me.
A: If you want that the avg values will be a tuple element (I don't see any reason to do so but maybe I don't have enough context), try:
results={k: (sum(v)/len(v),) for k,v in students.items()}
A: I was trying this but realized we had a problem summing a tuple of length 1. So you can do it this way.
results = {}
for k, v in students.items():
print(v)
if (isinstance(v, int)):
results[k] = v
else:
results[k] = sum(v) / len(v)
A: I'd do:
result = {}
for k, v in students.items():
if type(v) in [float, int]:
result[k] = v
else:
result[k] = sum(v) / len(v)
A: A pythonic solution would be to use dictionary comprehension to create the results dictionary.
def avg(l):
return sum([l]) / len(l)
results = {key: (avg(val)) for (key, val) in students.items()}
You need brackets around the l in sum so the tuple is treated as a list. I would further change the data structure to a list instead of tuple.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61218789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Coordinates intersecting with bounding box after forcing right hand rule I am trying to query for locations within a bounding box. The bounding box of the country Russia renders east-to-west, covering basically all of Canada and none of Russia (which is obviously incorrect) and returns cities in Canada, Poland, and Slovakia.
I used ForceRHR (Django 1.11) and ForcePolygonCW (Django 2.2) to force the right-hand-rule, and it appears to order the bounding box coordinates properly, but I get the same query results for the regular bounding box and the RHR bounding box.
Here are the relevant fields in the Location model...
from django.contrib.gis.db import models as gis_models
point = gis_models.PointField(blank=True, null=True, geography=True)
bounding_box = gis_models.PolygonField(blank=True, null=True)
And here's what I've tried...
from locations.models import Location
from django.contrib.gis.db.models.functions import ForceRHR, ForcePolygonCW
russia = Location.objects.annotate(rhr=ForcePolygonCW('bounding_box')).get(pk=1646)
print(russia.bounding_box)
in_russia = Location.objects.filter(point__intersects=russia.bounding_box)
print(in_russia)
print(russia.rhr)
in_russia2 = Location.objects.filter(point__intersects=russia.rhr)
print(in_russia2)
Here are the results of the code above:
SRID=4326;POLYGON ((19.638861 41.185902, 19.638861 81.856903, -168.997849 81.856903, -168.997849 41.185902, 19.638861 41.185902))
<QuerySet [<Topic: 00-001 Warsaw, Poland>, <Topic: 048 01 Rožňava, Slovakia>, <Topic: 053 51 Richnava, Slovakia>, <Topic: 50.2112, -170.2624>, <Topic: 50.9566, -170.7638>, <Topic: 51.5734, -170.2439>, <Topic: 51.7759, -169.4604>, <Topic: 51.8281, -170.4743>, <Topic: 51.9097, -170.0422>, <Topic: 51.9108, -169.5701>, <Topic: 51.9771, -169.6288>, <Topic: 51.9782, -169.3368>, <Topic: 52.0036, -170.8657>, <Topic: 52.0231, -170.4362>, <Topic: 52.0362, -170.5883>, <Topic: 52.0641, -169.6883>, <Topic: 52.1027, -170.0871>, <Topic: 52.1242, -170.4661>, <Topic: 52.1272, -170.5383>, <Topic: 52.1295, -170.4205>, '...(remaining elements truncated)...']>
SRID=4326;POLYGON ((19.638861 41.185902, -168.997849 41.185902, -168.997849 81.856903, 19.638861 81.856903, 19.638861 41.185902))
<QuerySet [<Topic: 00-001 Warsaw, Poland>, <Topic: 048 01 Rožňava, Slovakia>, <Topic: 053 51 Richnava, Slovakia>, <Topic: 50.2112, -170.2624>, <Topic: 50.9566, -170.7638>, <Topic: 51.5734, -170.2439>, <Topic: 51.7759, -169.4604>, <Topic: 51.8281, -170.4743>, <Topic: 51.9097, -170.0422>, <Topic: 51.9108, -169.5701>, <Topic: 51.9771, -169.6288>, <Topic: 51.9782, -169.3368>, <Topic: 52.0036, -170.8657>, <Topic: 52.0231, -170.4362>, <Topic: 52.0362, -170.5883>, <Topic: 52.0641, -169.6883>, <Topic: 52.1027, -170.0871>, <Topic: 52.1242, -170.4661>, <Topic: 52.1272, -170.5383>, <Topic: 52.1295, -170.4205>, '...(remaining elements truncated)...']>
I expect to get locations in Russia, so am I doing something wrong or is the entire approach wrong?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58189965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Akeneo error after installation / Cache Error My akeneo installation works very fine and without any error. But when I want to start the application, the following error occurs:
Warning:
require(web/akeneo/pim-community-standard/var/cache/prod/doctrine/orm/Proxies/__CG__PimBundleCatalogBundleEntityLocale.php):
failed to open stream: No such file or directory in
web/akeneo/pim-community-standard/vendor/doctrine/common/lib/Doctrine/Common/Proxy/AbstractProxyFactory.php
on line 209
Fatal error: require(): Failed opening required 'web/akeneo/pim-community-standard/var/cache/prod/doctrine/orm/Proxies/__CG__PimBundleCatalogBundleEntityLocale.php'
(include_path='.:/usr/local/lib/php') in
web/akeneo/pim-community-standard/vendor/doctrine/common/lib/Doctrine/Common/Proxy/AbstractProxyFactory.php
on line 209
Fatal error: Uncaught Symfony\Component\Debug\Exception\FatalErrorException: Compile Error:
require(): Failed opening required
'web/akeneo/pim-community-standard/var/cache/prod/doctrine/orm/Proxies/__CG__PimBundleCatalogBundleEntityLocale.php'
(include_path='.:/usr/local/lib/php') in
web/akeneo/pim-community-standard/vendor/doctrine/common/lib/Doctrine/Common/Proxy/AbstractProxyFactory.php:209
Stack trace: #0 {main} Next RuntimeException: Failed to start the
session because headers have already been sent by
"web/akeneo/pim-community-standard/vendor/doctrine/common/lib/Doctrine/Common/Proxy/AbstractProxyFactory.php"
at line 209. in
web/akeneo/pim-community-standard/vendor/symfony/symfony/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php:141
Stack trace: #0
web/akeneo/pim-community-standard/vendor/symfony/symfony/src/Symfony/Component/HttpFoun
in
web/akeneo/pim-community-standard/vendor/symfony/symfony/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php
on line 141
Can someone help me?
A: Did you clean your cache?
With the command
bin/console cache:clear --env=prod (or env=dev)
or the more "hard" way
rm -rf var/cache/*
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60447878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Display a tool tip on current document I am developing a code editor like VS. I want to display a tool tip window when mouse cursor lands on a text. The ToolTip.Show() method asks for a IWin32Window parameter...
Please tell me how to display the tool tip in the current document just as Visual Studio Intellisense works.
A: ToolTip.Show Method (String, IWin32Window)
The second argument is the control for which the tool tip is to be shown.
toolTip1.Show("Test 123", button1, Int32.MaxValue);
Visual Studio tracks the word underneath the mouse and displays tooltips/intellisense accordingly. One way for you to do the same could be to:
*
*Track the mouse movements
*Get the text under mouse
*Show tooltip.
A: The ToolTip.Show method also has other more appropriate overloads, like this one.
You can pass the edit control (that is, your text box) that you want to be associated with the tooltip as the IWin32Window parameter.
Then, you can specify the current coordinates of the mouse cursor as the X and Y arguments:
*
*If you're trying to show this tooltip in one of the mouse event handlers (like MouseMove), the current coordinates of the mouse cursor are passed in as part of the MouseEventArgs—just use the e.X and e.Y properties.
*Otherwise, you'll need to use the Control.MousePosition property to get its current location, which will return a Point representing its current location relative to screen coordinates. Another one of the overloads to the ToolTip.Show method accepts a Point parameter that you can use here instead of separate X and Y coordinates
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4264144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: export Intellij project including libraries to Eclipse I have an intellij project which is using log4j and junit libraries (in my external libraries section). I need to export the project to Eclipse project including the libraries. The intellij option for exporting to eclipse is just generating the .project and .classpath files and nothing else. How would I export that project so that it will contain all dependencies and someone using eclipse would be able to compile and run the program without additional work?
Also this is a normal java project (not maven)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44447330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Youtube iFrame player in IOS Webview loads very slowly I'm using the standard YouTube iFrame player as defined here within a Webview on IOS. Everything works as it should, except the videos consistently take over 6 seconds to load on a broadband network. When I use Safari to load the exact same video on the Youtbue.com, on the same network, using the same iPad, the video consistently loads in under 3 seconds.
Does anyone know why the IOS Webview videos are taking twice as long to load ?
Or is YouTube (owned by Google) deliberately loading videos on their website faster than apps using their player apis ?
A couple other data points as to my methodology:
1) I'm only measuring the time for a video to load in my app, not the loading of the webview or even the html page within the webview that contains the Youtube iframe. I start measuring after the webview has loaded the Youtube iFrame.
2) The Youtube App performs similarly to the YouTube website using Safari. I assume Youtube App uses a Webview.
3) The results seem to vary on different days. YouTube Website and App videos are always faster on average, but the amount varies by days.
A: I feel the "(owned by Google)" comment suggests some alterer motive which I don't believe exists..
There are several different issues which may be at work here:
1) You seem to be testing Youtube.com using Mobile Safari, and testing the embedded player using a webview:
This is not a fair comparison, as the webview has been shown to be very significantly slower than safari. (e.g. http://www.guypo.com/mobile/ios-browsers-speed-bakeoff/ )
2) You do not make it clear exactly what load time you are measuring
Are you creating the webview in this time and setting up the browser environment?
Are you loading the document which includes the script tag for the embedded player code in this time?
Did Safari have a hot cache for youtube.com at the time you loaded the video?
Many browsers start loading requests in the background as you type, before you tap to load a page - these kind of performance tweaks can significantly reduce apparent time to load a site, but make comparisons difficult.
3) The common user story they are optimising for is different
In almost all situations where the YouTube player API is inserted into a page or a website, the video does not automatically start playing.
By comparison, almost every YouTube watch page load begins playing the video automatically.
One of the optimisations which YouTube have discussed in presentations before is in-lining the first part of the video stream into the page even before the video player loads.
This is a trade-off of extra user bandwidth for faster video playback which makes sense when you know the user is going to definitely play the video: however if they were to do this for embedded videos then it would significantly slow down the loading time for players with videos which did not always start playing - which is a fairly significant percentage of all of the websites in the world!
4) YouTube get involved at different points in the two cases, and can only start optimising the experience later for embedded players.
YouTube is able to do optimisations on youtube.com which it is unable to do on third party sites/apps using their html5 player API.
In the case of watching a video on youtube.com: YouTube are involved right from the first http request - they know which video you are playing, and they know which browser you say you are on (so can optimise the experience as much as possible to pre-load the correct video and/or video player).
In the case of embedding an iframe:
*
*The browser first loads your page, which it then has to parse and extract urls from.
*Then it makes a request for javascript from YouTube (note that if you are using the javascript player API rather than the embedded iframe direct then that needs to be cached on the browser, so YouTube still can't optimise performance of this video at this point)
*Once your entire page has finished loading, it can create an iframe pointing to YouTube (all of this takes time on the CPU and memory management time)
*At this point, YouTube can start optimising things to try to make the experience faster.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23919633",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Wordpress get_avatar function not correct working My code doing this, listing which author have posted in the current category. But get_avatar function not correct working. Im Using Simple Local Avatar Plugin. It is working author.php don't have any problem. But when i use it my this code, it is listing same and wrong author picture(My latest author picture. You can look this picture)
My Code:
<?php if (is_category()) {?>
<?php
$current_category = single_cat_title(“”, false);
$author_array = array();
$args = array(
'numberposts' => -1,
'category_name' => $current_category,
'orderby' => 'author',
'order' => 'ASC'
);
$cat_posts = get_posts($args);
foreach ($cat_posts as $cat_post) :
if (!in_array($cat_post->post_author,$author_array)) {
$author_array[] = $cat_post->post_author;
}
endforeach;
foreach ($author_array as $author) :
$auth = get_userdata($author)->display_name;
$autid= get_userdata($author)->ID;
echo get_avatar( get_the_author_email(), '32' );
echo "<a href='?author=";
echo $autid;
echo "'>";
echo $auth;
echo "</a>";
echo "<br />";
endforeach;
?>
<?php }?>
A: change this echo get_avatar( get_the_author_email(), '32' ); to echo get_avatar( $autid, '32' );
get_the_author_email() returns email of the author in the current loop of wordpress and not from your foreach loop.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14309952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How / Where does Adonis cache views? I am learning adonisjs. The .env file has an option to set CACHE_VIEWS=true. What exactly does this do? Some frameworks store the cached views in a file, and some in memory, but how does Adonis cache views?
A: This variable is readed in your configuration file. Then it's used in the wrapper around Nunjucks (in View/index.js).
You can find more information about Nunjucks Cache in the documentation of loaders.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42987679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Qmake scope syntax with "contains" function I wrote some qmake which looked like this:
contains( DEFINES, SOME_DEF ): DEFINES+=SOME_OTHER_DEF
The result was to ALWAYS execute what I thought was conditional, i.e. DEFINES+=SOME_OTHER_DEF
I changed the line to:
contains( DEFINES, SOME_DEF ){ DEFINES+=SOME_OTHER_DEF }
And it works as I expected now. The thing is, I don't understand why I could not use the original syntax?
Here's the contains documentation (which doesn't address this detail regarding the use of :)
http://doc.qt.io/qt-5/qmake-test-function-reference.html#contains-variablename-value
Here is the scope documentation which seems to support what I was trying to do:
http://doc.qt.io/qt-5/qmake-language.html#scopes-and-conditions
It says:
You may... use the : operator to perform single line conditional
assignments.
I've definitely used the : in this manner before (but I guess not with contains?). What am I failing to understand?
Additional info (responding to comment in a readable manner):
Test ran:
DEFINES+=A
DEFINES+=B
contains( DEFINES, A ) : contains( DEFINES, B ) : message( 1 )
contains( DEFINES, A ) : contains( DEFINES, C ) : message( 2 )
contains( DEFINES, A ):contains( DEFINES, B ):message( 3 )
contains( DEFINES, A ):contains( DEFINES, C ):message( 4 )
Result:
Project MESSAGE: 1
Project MESSAGE: 3
So it's not white space.
I think my question was invalid.
A: Looks like it's about space. Seems following should work but I'm not sure
contains( DEFINES, SOME_DEF ):DEFINES+=SOME_OTHER_DEF
As I got it it's designed to be used as logical AND operator.
conditionA:conditionB {
...
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46078270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Process not working I have tried calling a Process(console application) using the following code:
ProcessStartInfo pi = new ProcessStartInfo();
pi.UseShellExecute = false;
pi.RedirectStandardOutput = true;
pi.CreateNoWindow = true;
pi.FileName = @"C:\fakepath\go.exe";
pi.Arguments = "FOO BAA";
Process p = Process.Start(pi);
StreamReader streamReader = p.StandardOutput;
char[] buf = new char[256];
string line = string.Empty;
int count;
while ((count = streamReader.Read(buf, 0, 256)) > 0)
{
line += new String(buf, 0, count);
}
It works for only some cases.
The file that does not work has a size of 1.30 mb,
I don't know if that is the reason for it not working correctly.
line returns an empty string.
I hope this is clear.
Can someone point out my error? Thanks in advance.
A: A couple thoughts:
*
*The various Read* methods of streamreader require you to ensure that your app has completed before they run, otherwise you may get no output depending on timing issues. You may want to look at the Process.WaitForExit() function if you want to use this route.
Also, unless you have a specific reason for allocating buffers (pain in the butt IMO) I would just use readline() in a loop, or since the process has exited, ReadToEnd() to get the whole output. Neither requires you to have to do arrays of char, which opens you up to math errors with buffer sizes.
*If you want to go asynchronous and dump output as you run, you will want to use the BeginOutputReadLine() function (see MSDN)
*Don't forget that errors are handled differently, so if for any reason your app is writing to STDERR, you will want to use the appropriate error output functions to read that output as well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7211942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: var_dump returns NULL Json object after json_decode Hello I make a curl POST action in terminal(i tried also in POSTMAN) for post some data in a php file
The curl call is :
curl -iX POST http://localhost/rest_api/index.php
-H 'Content-Type: application/json'
-d '{
"id": "urn:ngsi-ld:Building:store005",
"type": "Building"
}'
The response is :
HTTP/1.1 200 OK
Date: Sun, 09 Aug 2020 14:14:37 GMT
Server: Apache/2.4.43 (Unix) OpenSSL/1.1.1g PHP/7.2.32 mod_perl/2.0.11 Perl/v5.32.0
X-Powered-By: PHP/7.2.32
Access-Control-Allow-Origin: *
Content-Length: 105
Content-Type: application/json;charset=utf-8;
array(2) {
["id"]=>
string(29) "urn:ngsi-ld:Building:store005"
["type"]=>
string(8) "Building"
}
Also my index.php file is:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json;charset=utf-8;');
$json = file_get_contents('php://input');
$object = json_decode($json, true);
die(var_dump($object));
?>
The problem is that in the website the var_dump is NULL,while it should print the json object.
Where is my false?
A: Look at the response body:
array(2) {
["id"]=>
string(29) "urn:ngsi-ld:Building:store005"
["type"]=>
string(8) "Building"
}
That isn't JSON. It looks like a var_dump(). Check the endpoint you call!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63327439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to upload file to S3 (digital ocean) without saving temp file in node.js I need to save file in S3 Digital Ocean space by URL. It can't be downloaded and then saved to S3, because we use firebase-functions, and there restricted to use file system. Is there way to save it directly from url or other ways? For example by stream?
const fileName = 'image.jpg';
const url = 'imageUrl';
const res = await https.get(url, (stream) => stream.pipe(res));
await s3
.upload({
Bucket: 'name',
Key: `content/${fileName}`,
Body: res,
ACL: 'public-read'
})
.promise();
A: All problem were in wrong path to /tmp directory.
Docs. Final code for Firebase functions:
const fs = require('fs');
const s3 = require('../../services/storage');
const download = require('download');
const saveMediaItemToStorage = async (sourceId, item) => {
// * creating file name
const fileName = `${item.id}.${item.extension}`;
// * saving file to /tmp folder
await download(item.originalMediaUrl, '/tmp', { filename: fileName });
const blob = fs.readFileSync(`/tmp/${fileName}`);
// * saving file to s3
await s3
.upload({
Bucket: 'name',
Key: `content/${sourceId}/${fileName}`,
Body: blob,
ACL: 'public-read'
})
.promise();
// * remove file from temp folder
fs.unlink(`/tmp/${fileName}`, function (err) {
if (err) return console.log(err);
console.log('file deleted successfully');
});
};
module.exports = saveMediaItemToStorage;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73973806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Angular 2 FlexLayout - Change page content with breakpoints I'm learning Angular and right now I'm to make a login form, similar to Gmail page using Angular2, Angular Material and Flex-Layout (all from Angular).
So far everything is fine the only problem is I don't know how to change the card div so it fills the entire screen when using fxFlex.lt-sm like on the Gmail page.
How can I achieve this?
What I've done so far:
https://plnkr.co/edit/X8Rs7QHaMG9XzB1LTkbR?p=preview
Normal card
No card
A: If the container of your form has the width of the page then setting fxFlex.lt-sm="100%" should work. But if you're using fxLayout=column instead of row then it will set your max-height to 100% so you would need to set the width manually.
If this doesn't help, please post your html code and I'll update my answer
EDIT
<!-- Card -->
<div style="width: 100%" fxLayoutAlign="center center">
<md-card fxFlex="448px" fxFlex.lt-sm="100%">
Seems to work if you modify like that
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45622730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: whats the best way to model dependencies in SQL relational database if i have a table called projects and a project can have a dependency on one or many other projects, what is the best way to model this in db tables.
i have one table called Projects with columns: ID, Name
i was thinking of having a new column called Dependencies and just store the ID of another project but i just realized that there can be many project dependencies so i can store this as a comma delimited list of project IDs but i wanted to get opinions on any other way to model this in a relational db.
A: Create a new table called Dependencies. It should have two ID fields (both are Foreign Keys): Project1ID and Project2ID. You can include whatever other columns in this table you feel are relevant.
Create one record in the new table for each dependency between one project and another.
A: Hope this is self-explanatory.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1818101",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PBEWithSHAAnd128BitRC4 implementation in java I am using IBM JRE and i want to implement PBEWithSHAAnd128BitRC4 algorothm for my cipher so which alorithm should i use for my SecretKeyFactory and SecretKeySpec ,below is the secret key supporting algos which i got from provider.getInfo() methode for IBMJCE provider.
Cipher algorithms : Blowfish, AES, DES, TripleDES, PBEWithMD2AndDES,
PBEWithMD2AndTripleDES, PBEWithMD2AndRC2,
PBEWithMD5AndDES, PBEWithMD5AndTripleDES,
PBEWithMD5AndRC2, PBEWithSHA1AndDES
PBEWithSHA1AndTripleDES, PBEWithSHA1AndRC2
PBEWithSHAAnd40BitRC2, PBEWithSHAAnd128BitRC2
PBEWithSHAAnd40BitRC4, PBEWithSHAAnd128BitRC4
PBEWithSHAAnd2KeyTripleDES, PBEWithSHAAnd3KeyTripleDES
Mars, RC2, RC4, ARCFOUR
RSA, Seal
Key agreement algorithm : DiffieHellman
Key (pair) generator : Blowfish, DiffieHellman, DSA, AES, DES, TripleDES, HmacMD5,
HmacSHA1, Mars, RC2, RC4, RSA, Seal, ARCFOUR
Algorithm parameter generator : DiffieHellman, DSA
Algorithm parameter : Blowfish, DiffieHellman, AES, DES, TripleDES, DSA, Mars,
PBEwithMD5AndDES, RC2
Key factory : DiffieHellman, DSA, RSA
Secret key factory : Blowfish, AES, DES, TripleDES, Mars, RC2, RC4, Seal, ARCFOUR
PKCS5Key, PBKDF1 and PBKDF2(PKCS5Derived Key).
Below is my code which is giving java.security.InvalidKeyException: Missing password exception.
Decrypter(String passPhrase) throws Exception {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount, keyStrength);
SecretKey tmp = factory.generateSecret(spec);
key = new SecretKeySpec(tmp.getEncoded(), "RC4");
dcipher = Cipher.getInstance("PBEWithSHAAnd128BitRC4");
}
public String encrypt(String data) throws Exception {
dcipher.init(Cipher.ENCRYPT_MODE, key);
AlgorithmParameters params = dcipher.getParameters();
System.out.println("getAlgorithm : "+params.getAlgorithm());
iv = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] utf8EncryptedData = dcipher.doFinal(data.getBytes());
String base64EncryptedData = new sun.misc.BASE64Encoder().encodeBuffer(utf8EncryptedData);
System.out.println("IV " + new sun.misc.BASE64Encoder().encodeBuffer(iv));
System.out.println("Encrypted Data " + base64EncryptedData);
return base64EncryptedData;
}
public String decrypt(String base64EncryptedData) throws Exception {
dcipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
byte[] decryptedData = new sun.misc.BASE64Decoder().decodeBuffer(base64EncryptedData);
byte[] utf8 = dcipher.doFinal(decryptedData);
return new String(utf8, "UTF8");
}
One more question ,Which are the most secure algorithm amoung default java provider because i can not use thrid party like BouncyCastleProvider ?
Thanks .
A: Secure is a bit of a moving target. Secure against what and for how long. If you are encrypting transaction data that has no value an hour later, almost anything will do. If you need to keep something secure for a long time, you want a long key for your PK systems, the longer the better. But you really pay the price on key generation and some types of stream encryptions/decryptions.
The number one failure of encryption systems is not the algorithm itself, but the implementation of the system, usually how the keys are either generated or stored. That said, Blowfish and AES are both well regarded and when properly implemented should be everything you need. I can't recommend http://www.schneier.com/ highly enough. Applied Cryptography is a bit dated, 10 years or so, but is a cogent explaination of the field specifically geared to programmers. And his blog is a wealth of information. Go there and search if you need more details on algorithms. Won't be a ton of help in java implementation, but you can get that here on SO.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16085467",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to match values from one file to another in Python I have two files:
values_list.txt
val1, "Sean"
val11, "Smith"
val111, "25"
val2, "Bob"
val22, "Rogers"
val222, "30"
val3, "Michael"
val33, "Jones"
val333, "40"
val4, "Aaron"
val44, "Michaels"
val444, "41"
val5, "John"
val55, "Brown"
val555, "26"
insert_values.sql
insert into users(fname,lname,age) values(val1,val11,val111)
insert into users(fname,lname,age) values(val2,val22,val222)
insert into users(fname,lname,age) values(val3,val33,val333)
insert into users(fname,lname,age) values(val4,val44,val444)
insert into users(fname,lname,age) values(val5,val55,val555)
I need to generate a third file like so ....
insert into users(fname,lname,age) values("Sean","Smith","25")
insert into users(fname,lname,age) values("Bob", "Rogers", "30")
insert into users(fname,lname,age) values("Michael","Jones","40")
insert into users(fname,lname,age) values("Aaron","Michaels","41")
insert into users(fname,lname,age) values("John","Brown","26")
This is what I have so far ...
#Read each line of the text file
valsfile = open('values_list.txt')
valscontents = valsfile.read()
valsline = valscontents.splitlines()
#Read each line of the sql file
sqlfile = open('insert_values.sql')
sqlcontents = sqlfile.read()
sqlline = sqlcontents.splitlines()
Now I need to get each individual word from sqlline - and if it contains "val" - then grab the word and get the matching value from valsline - and write/append a new insert statement to a new file
Any help would be appreciated.
Thanks
A: First, we create a dictionary to lookup values using values_list.txt then we iterate over all the lines in the sqlfile and replace the dictionary keys with their values. The code is as follows:
valsfile = open('values_list.txt')
valsline = valsfile.read().splitlines()
d = {}
for i in valsline:
i = i.split(',')
d[i[0]] = i[1]
sqlfile = open('insert_values.sql')
sqlcontents = sqlfile.read()
sqlline = sqlcontents.splitlines()
text = []
for i in sqlline:
for word, initial in d.items():
i = i.replace(word, initial)
text.append(i+'\n')
f = open("final_sqlfile.sql", "a")
f.writelines(text)
f.close()
The contents of final_sqlfile.sql are given below:
insert into users(fname,lname,age) values( "Sean", "Sean"1, "Sean"11)
insert into users(fname,lname,age) values( "Bob", "Bob"2, "Bob"22)
insert into users(fname,lname,age) values( "Michael", "Michael"3, "Michael"33)
insert into users(fname,lname,age) values( "Aaron", "Aaron"4, "Aaron"44)
insert into users(fname,lname,age) values( "John", "John"5, "John"55)
A: This presupposes that the values are grouped in threes. Try this:-
with open('values_list.txt') as vlist:
with open('insert_values.sql', 'w') as sql:
vals = []
for line in vlist.readlines():
v = line.strip().split(',')
if len(v) == 2:
vals.append(v[1])
if len(vals) == 3:
sql.write(f'insert into users(fname,lname,age) values({vals[0]},{vals[1]},{vals[2]})\n')
vals=[]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69201845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: Highstock dataGrouping option I have gone through the highstock datagrouping documenation(https://api.highcharts.com/highstock/series.column.dataGrouping), But little unclear about this data grouping option, Things I have noticed is, Data grouping is enabled by default in highstock, I n which we can force the datagrouping by giving custom datagrouping option through units option in datagrouping, The doubt I got is which is the default data grouping(default unit option) in highstock, another one is do we need to tell the datagrouping units for each time interval by which we are gonna show in chart(eg, if the datarange chosen is one month the grouping should by 1 day, If the daterange chosen is one day means the datagrouping units should be by hour),
units: [[
'millisecond', // unit name
[1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples
], [
'second',
[1, 2, 5, 10, 15, 30]
], [
'minute',
[1, 2, 5, 10, 15, 30]
], [
'hour',
[1, 2, 3, 4, 6, 8, 12]
], [
'day',
[1]
], [
'week',
[1]
], [
'month',
[1, 3, 6]
], [
'year',
null
]]
Do we need to specify each unit or do we need to change the units dynamically based on the daterange chosen?
This is what I have done, The based on the daterange the user chosen the grouping units should be changed, Do we need to specify the units based on the daterange chosen and what the units array specifies (Is Giving only one unit as option to the grouping is the functionality, Or the units array options can be chosen based on the timestamps)
Highcharts.stockChart('chart', {
chart: {
zoomType: false
},
legend: {
enabled: true
align: 'right',
verticalAlign: 'top',
x: 0,
y: -20
},
navigator: {
enabled: false
},
rangeSelector: {
enabled: false
},
scrollbar: {
enabled: false
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
day:"%b %e"
}
},
yAxis: {
opposite : false
},
series: [{
data: data ,
marker: {
enabled: true
},
dataGrouping: {
forced: true,
approximation: "sum"
}
}]
EDIT
While forced option is set to false
A:
which is the default data grouping(default unit option) in highstock
There's a little flaw in the API (https://api.highcharts.com/highstock/series.column.dataGrouping.units) in units section. First it says that it defaults to:
units: [[
'millisecond', // unit name
[1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples
], [
'second',
[1, 2, 5, 10, 15, 30]
], [
'minute',
[1, 2, 5, 10, 15, 30]
], [
'hour',
[1, 2, 3, 4, 6, 8, 12]
], [
'day',
[1]
], [
'week',
[1]
], [
'month',
[1, 3, 6]
], [
'year',
null
]]
and after that "Defaults to undefined." line appears. The first one is correct.
Highcharts automatically finds the best grouping unit from units array. So, in other words: units specifies which groupings can be applied if Highcharts decides that applying data grouping is a good idea.
Enable dataGrouping.forced and use only one key-value pair in units array if you want to make sure that this grouping will be used no matter what e.g.:
units: [[
'hour',
[3]
] // Data will always be grouped into 3 hours periods
These're just general rules - they should be enough to use data grouping successfully.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50960966",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Security break to shell Our server had a break-in and the hacker left this trail (my server hang with this message on the screen)
sh-4.2# eboot
sh: eboot: command not found
sh-4.2# rebooot
sh: rebooot: command not found
sh-4.2# reboot
sh: reboot: command not found
sh-4.2# restart
sh: restart: command not found
sh-4.2# logout
sh: logout: not login shell: use 'exit'
sh-4.2# ^C
sh-4.2# ^C
sh-4.2# ^C
sh-4.2# exit
exit
My 'lastb' and 'last' show nothing wrong/peculiar except my fail2ban block few IP addresses.
We are using Centos7. Any advice how to prevent this from happening in the future?
Thanks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40234265",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Use Leanback UI on Mobile/Tablet for Android I am currently developing a mobile app for phone/tablet devices that looks like the Leanback sample app. I really like the Leanback UI used for Android TV.
Unfortunately, on Android studio, I can't use Leanback with mobile projects.
Is there some kind of customized version of Leanback than can be used on other devices?
*P.S *: I found this project, but I enable to import it on Android Studio, it tells me that I don't have the right SDK version.
A: It looks like this project you found is fairly old and is using older dependencies. You would need to go into your SDK manager and install SDK version 22 (Lollipop MR1).
You could also fork the project and update it to use API version 24 so it works with your project.
A: <uses-feature
android:name="android.software.leanback"
android:required="false" />
<uses-feature
android:name="android.hardware.touchscreen"
android:required="true" />
Just place this, it runs in mobile devices.
A: Please check my fork, I fixed the build issue and updated the build configuration to android 30.
https://github.com/moaz-cliqz/MaterialLeanBack
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38458142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Access children of a custom element shadow dom I have a custom element using mr. Ruyadornos simple-slider element.
(I am working on chrome)
won-thumbnail.html
<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="SimpleSlider/simple-slider.html">
<polymer-element name="won-thumbnail" noscript>
<template>
<simple-slider style="width:200px; height: 100px;">
<img src="http://placekitten.com/g/612/613" />
<img src="http://placekitten.com/g/612/614" />
</simple-slider>
</template>
</polymer-element>
When I place the simple-slider element directly into index.html, everything works well and I see 2 pictures of beautiful kittens sliding perfectly.
When I place the element into a custom element - as above - the slider does not work at all.
I dug a bit into the code of the slider and localized the problem:
console.log( this.containerElem ); // -> prints the simple-slider element correctly
console.log( this.containerElem.children ); // -> prints an array containing both images as expected
console.log( this.containerElem.children.length ); // -> prints 0 ???SOS???
console.log( JSON.stringify( this.containerElem.children ) ); // -> prints { "length": 0 }
Would anyone like to explain this behavior, please? :)
EDIT
I compared the output of console.log( this.containerElem.children ); for the slider being directly in the index.html and then as a part of the custom element. In the index.html it is a circular structure, while in the other one it seems to be a standard array.
Output from simple-slider element being called directly in index.html
Output from simple-slider while it resides in the custom element called in index.html
A: I'm not sure why you are importing SimpleSlider/simple-slider.html, you should import ../bower_components/polymer-simple-slider/src/simple-slider.html
I have created example project where it's working:
https://github.com/mkubenka/polymer-simple-slider-example
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28191102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Create custom IN-function t-sql depending levenshtein distance I am actually not good in functions in SQL, i am more a java/android programmer. But for a school project i need to check if a String is in some array in T-SQL.
But i am comparing data from two different companies, and they both have some flaws in their data. The data of one of the companies is in a Database, the other from excel.
One way to do this is using the LIKE function from SQL ofcourse, but i am not very sure what the criteria are. What would be perfect is a function like the sql function IN, but that requires a perfect match...
So what i did is the following:
Create a T-SQL function that gives the Levenshtein distance , it compares two strings and gives the Levenshtein distance.
This function works good.
The next step for me is to create a function with the following parameters:
*
*input string - the string to check
*levdist int - the minimal levenstein distance to give a match
(perfect match would be 0)
*arr array/table/llist (cant find how a comma separated string (like
you put in the IN function) is called - where to check
What i have so far is this:
CREATE FUNCTION inArrayWithLevenstheinDist
(
-- Add the parameters for the function here
@stringToCheck varchar,
@levDist int,
@arr TABLE ???
)
RETURNS Boolean
AS
BEGIN
-- Declare the return variable here
DECLARE @Result bool
SET @Result = FALSE
-- Add the T-SQL statements to compute the return value here
DECLARE @intFlag INT
SET @intFlag = 1
WHILE (@intFlag <=5)
BEGIN
IF [100].dbo.LEVENSTEINDIST(@stringToCheck,arr(@intFlag) < @levDist
SET @Result = TRUE
END //end if
SET @intFlag = @intFlag + 1
IF @intFlag = arr.size ??????
BREAK;
END //end while
GO
-- Return the result of the function
RETURN @Result
END //end function
GO
This doesnt work and gives compile errors.
So my two questions are (what i think are the points my code is wrong)
*
*how to return a boolean value in a function (i cant find it :S )? Offcourse i can return an in integer and use 0 for false and 1 for true or so, but it should be possible
*how to use an array/list/table like in the standard T-SQL IN-function?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16524131",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ionic do action when all images and content loaded Creating an Ionic app but need a way to show a loading spinner until everything is 100% loaded.
I currently have in my controller:
$ionicLoading.show();
I then do an API call and will remove the ionic loader in the promise. However, images are still being loaded etc.
Is there a way I can wait until everything is 100% loaded then perform an action? And then if possible, a way to make this affect every route.
A: I use it like this,
$ionicLoading.show();
$ionicPlatform.ready(function() {
/* insert your code here */
$ionicLoading.hide().then(function(){
console.log("The loading indicator is now hidden");
});
$state.go("tab.dash");
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35873750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Access static method on generic class I'd like to access a static method on a class, but have that class passed in a generic.
I've done the following:
class Base{
public static String getStaticName(){
return "Base";
}
}
class Child extends Base{
public static String getStaticName(){
return "Child";
}
}
class StaticAccessor{
public static <T extends Base>String getName(Class<T> clazz){
return T.getStaticName();
}
}
StaticAccessor.getName() // --> "Base"
This will return "Base" but what i'd like is "Child" anybody a suggestion without reflections?
A: You can't do that without reflection, because the type T is erased at runtime (meaning it will be reduced to its lower bound, which is Base).
Since you do have access to a Class<T> you can do it with reflection, however:
return (String) clazz.getMethod("getStaticName").invoke(null);
Note that I'd consider such code to be code smell and that it is pretty fragile. Could you tell us why you need that?
A: If it is OK for you to pass an object instance rather than Class in your static accessor, then, there is a simple and elegant solution:
public class Test {
static class Base {
public static String getStaticName() { return "Base"; }
public String myOverridable() { return Base.getStaticName(); };
}
static class Child extends Base {
public static String getStaticName() { return "Child"; }
@Override
public String myOverridable() { return Child.getStaticName(); };
}
static class StaticAccessor {
public static <T extends Base>String getName(T instance) {
return instance.myOverridable();
}
}
public static void main(String[] args) {
Base b = new Base();
Child c = new Child();
System.out.println(StaticAccessor.getName(b));
System.out.println(StaticAccessor.getName(c));
}
}
The output is:
Base
Child
A: I don't believe you can do this without reflection.
It appears you should be doing is not using static methods. You are using inheritance but static methods do not follow inheritance rules.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5897446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: No valid local directories in property: mapred.local.dir I am running the VM in pseudo mode.
Due to some resource related issues (Name Node in safe mode, not able to leave) I had to format and restart the namenode of my Cloudera 4.x. I didn't have any other choice.
I used the steps provided here:
Writing to HDFS could only be replicated to 0 nodes instead of minReplication (=1)
After that I am able to properly use get/put command in hdfs which means I have read/write permission.
Now, when I try to submit the job, I am getting following exception.
Exception in thread "main"org.apache.hadoop.ipc.RemoteException(java.io.IOException): java.io.IOException: No valid local directories in property: mapred.local.dir
at org.apache.hadoop.mapred.JobTracker.submitJob(JobTracker.java:3491)
at org.apache.hadoop.mapred.JobTracker.submitJob(JobTracker.java:3459)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.hadoop.ipc.WritableRpcEngine$Server$WritableRpcInvoker.call(WritableRpcEngine.java:474)
at org.apache.hadoop.ipc.RPC$Server.call(RPC.java:898)
at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:1693)
at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:1689)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:396)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1332)
at org.apache.hadoop.ipc.Server$Handler.run(Server.java:1687)
Caused by: java.io.IOException: No valid local directories in property: mapred.local.dir
at org.apache.hadoop.conf.Configuration.getLocalPath(Configuration.java:1678)
at org.apache.hadoop.mapred.JobConf.getLocalPath(JobConf.java:500)
at org.apache.hadoop.mapred.JobInProgress.<init>(JobInProgress.java:409)
at org.apache.hadoop.mapred.JobTracker.submitJob(JobTracker.java:3489)
... 13 more
at org.apache.hadoop.ipc.Client.call(Client.java:1160)
at org.apache.hadoop.ipc.WritableRpcEngine$Invoker.invoke(WritableRpcEngine.java:225)
at org.apache.hadoop.mapred.$Proxy10.submitJob(Unknown Source)
at org.apache.hadoop.mapred.JobClient$2.run(JobClient.java:973)
at org.apache.hadoop.mapred.JobClient$2.run(JobClient.java:896)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:396)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1332)
at org.apache.hadoop.mapred.JobClient.submitJobInternal(JobClient.java:896)
at org.apache.hadoop.mapreduce.Job.submit(Job.java:531)
at org.apache.hadoop.mapreduce.Job.waitForCompletion(Job.java:561)
at clustering.mapreduce.KMeansClusteringJob.main(KMeansClusteringJob.java:69)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.hadoop.util.RunJar.main(RunJar.java:208)**
When I searched for above exception I found multiple links stating that mapred.local.dir should be properly defined and if not set then hadoop.tmp.dir is used.
I explicitly set mapred.local.dir in mapred-site.xml and given full permission to the default folder (/var/lib/hadoop-hdfs/cache).
The problem still persists.
Can someone please help in solving the issue?
Regards
A: Didn't give proper permission to the local directory -- Marking as Community wiki as answer was provided in the comments
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31427241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: NullPointerException for progressbar in fragment for Universal Image Loader in onActivityCreated I'm getting a strange NPE which I'm unable to diagnose. I know that it is coming from referencing my ProgressBar spinner, but I can't figure out why, because I am instantiating it in onCreateView for the fragment.
Below is the code for my fragment. Before you look, I am using universal image loader to load images. The images load, if I completely remove my lines of code for the spinner E.G. spinner.setVisibility(View.GONE); spinner.setVisibility(View.VISIBLE);
import android.app.Activity;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
*
* to handle interaction events.
* Use the {@link ImageFragment#newInstance} factory method to
* create an instance of this fragment.
*
*/
public class ImageFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private int mImageNum;
private ImageView imageDisplay;
private TextView textTest;
public ProgressBar spinner;
private String mUrl;
private ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @return A new instance of fragment ImageFragment.
*/
// TODO: Rename and change types and number of parameters
public static ImageFragment newInstance(int position, String url)
{
ImageFragment fragment = new ImageFragment();
Bundle args = new Bundle();
args.putInt(ARG_PARAM1, position);
args.putString(ARG_PARAM2, url);
fragment.setArguments(args);
return fragment;
}
public ImageFragment()
{
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mImageNum = getArguments() != null ? getArguments().getInt(ARG_PARAM1) : -1;
mUrl = getArguments() != null ? getArguments().getString(ARG_PARAM2) : null;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_image, container, false);
imageDisplay = (ImageView) v.findViewById(R.id.imageView);
spinner = (ProgressBar) imageDisplay.findViewById(R.id.loading);
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error)
.resetViewBeforeLoading(true)
.cacheOnDisk(true)
.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565)
.considerExifParams(true)
.displayer(new FadeInBitmapDisplayer(300))
.build();
return v;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
imageLoader.displayImage(mUrl, imageDisplay, options, new SimpleImageLoadingListener() {
@Override
public void onLoadingStarted(String imageUri, View view) {
spinner.setVisibility(View.VISIBLE);
}
@Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
String message = null;
switch (failReason.getType()) {
case IO_ERROR:
message = "Input/Output error";
break;
case DECODING_ERROR:
message = "Image can't be decoded";
break;
case NETWORK_DENIED:
message = "Downloads are denied";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}
spinner.setVisibility(View.GONE);
}
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
}
});
}
}
Please help! I'm not good with fragments, and I can't figure out why it's not working
A: final View v = inflater.inflate(R.layout.fragment_image, container, false);
imageDisplay = (ImageView) v.findViewById(R.id.imageView);
spinner = (ProgressBar) imageDisplay.findViewById(R.id.loading);
Is this "spinner" a child of your fragment view or "imageDisplay"?
Perhaps, it should be spinner = (ProgressBar) v.findViewById(R.id.loading);
A: You should change this
spinner = (ProgressBar) imageDisplay.findViewById(R.id.loading);
with
spinner = (ProgressBar) v.findViewById(R.id.loading);
You should find View from inflated view in Fragment.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24357669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Php how to display the video? I have a code and I would like to edit it so that the video uploaded shows up on my webpage and is then stored in the upload folder.
Code:
<?php
$allowedExts = array("jpg", "jpeg", "gif", "png", "mp3", "mp4", "wma");
$allowType = array("video/mp4","audio/mp3","audio/wma","image/png","image/gif","image/jpeg");
$maxSize = 20000000000000;
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$pathToUpload = 'upload/';
if( in_array($_FILES["file"]["type"], $allowType) && in_array($extension, $allowedExts) && $_FILES["file"]["size"] <= $maxSize)
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
if (file_exists($pathToUpload . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"], $pathToUpload . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
I am not looking for someone to give me the code but to point me in the right direction.
A: At the point where the video is moved and you are echo'ing its location:
"Stored in: " . "upload/" . $_FILES["file"]["name"];
instead of echo'ing where it's stored you could add it to a videos table of some sort:
$videoLocation = "upload/".$_FILES['file']['name'];
// now insert $videoLocation into a database table
//so you can fetch it on whatever page you feel like
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22618352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: DOM GetElementByTagName I am attempting to collect all the H1 tags from a block of code. I am attempting to use this within a class and im keep getting errors and im unsure if it is because of the insertion into the class or if im coding it wrong as i am new to DOM coding.
Error: Fatal error: Call to undefined method DOMDocument::getElementByTagName() This error refers to:
$head1 = $this->doc->getElementByTagName('H1');
File calling the class
<?php
include('../includes/configuration.php');
include('../functions/class.php');
$reports=new Functions();
$sql = mysql_query("SELECT * FROM user_urls LIMIT 1") or die(mysql_error());
if (mysql_num_rows($sql) > 0){
$recc = mysql_fetch_array($sql);
$id=$recc['id'];
$content=$recc['content'];
$reports->content=$content;
$test=$reports->collectHeadings();
print_r($test);
}
?>
Class File
class Functions{
var $content;
var $doc;
public function collectHeadings(){
$this->loadContent();
$head1 = $this->doc->getElementByTagName('H1');
return $head1;
}
public function loadContent(){
$this->doc = new DOMDocument();
$this->doc->loadHTML($this->content);
}
}
A: Ok it turns out you spelt it getElementByTagName, whereas the method is actually getElementsByTagName.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12848483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to populate TextFields with data from network calls in SwiftUI? I get User Profile information from a API call and want to populate the existing data (like name, gender etc) into my user profile field. However, I have no idea how to assign the state variables (fullName) of TextFields.
The following code is a sub view of the full form view. I make the network call on the parent view .onAppear{}.
Here is my Code:
import SwiftUI
struct FormPartOneView: View {
@State var fullName: String = ""
@ObservedObject var userProfile = UserProfileViewModel()
var body: some View {
GeometryReader { geometry in
VStack {
TextField("Full Name", text: self.$fullName)
.padding(.horizontal)
}
.font(.system(size: 13))
.frame(width: geometry.size.width/1.2, height: 40)
.overlay(
RoundedRectangle(cornerRadius: 5)
.stroke(Color("Border2"), lineWidth: 1)
)
.onAppear {
self.userProfile.fetchWithAF()
}
}
}
}
struct FormPartOneView_Previews: PreviewProvider {
static var previews: some View {
FormPartOneView()
}
}
This below code contains Full Name from decoded json data:
self.userProfile.userProfileModel?.payload[0].fullName ?? ""
So I would like to know how can I populate the Full name into the full name TextField in the form.
Here is the form view:
A: If I correctly understood your model you can set it in .onReceive modifier, like
.onAppear {
self.userProfile.fetchWithAF()
}
.onReceive(self.userProfile.$userProfileModel) { model in
self.fullName = model?.payload[0].fullName ?? ""
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62381056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How can I add a row to an HTML form? I'm making a simple app where there are a series of either drop downs or text boxes. Once the user has filled these in the resulting strings are then concatenated and displayed to the user. Now I need a simple function where the user can press a '+' button and adds a row. Ideally I need the row above to be copied (including inputs). So for example I have:
dropdown textbox textbox dropdown
concatenated string
How can I simply copy the row above (minus the concatenated string), including what the user has inputted. If it's easier simply adding the row above for now would be good. I'm using JavaScript...here's the code for a form for example:
<form action="">
<input type="text" id="site" value="Site" title="Site" onfocus="clickclear(this, 'Site')" onblur="clickrecall(this,'Site')" />
<input type="text" id="placementdesc" value="Placement description" title="Placement description" onfocus="clickclear(this, 'Placement description')" onblur="clickrecall(this,'Placement description')" />
<input type="text" id="placementtype" value="Placement Type" title="Placement Type" onfocus="clickclear(this, 'Placement Type')" onblur="clickrecall(this,'Placement Type')" />
<input type="text" id="size" value="Size" title="Size" onfocus="clickclear(this, 'Size')" onblur="clickrecall(this,'Size')" />
<input type="text" id="pricing" value="Pricing" title="Pricing" onfocus="clickclear(this, 'Pricing')" onblur="clickrecall(this,'Pricing')" />
<select id="servetype" title="Serve Type">
<option>STD – Standard trafficking type</option>
<option>SSV – Site-served</option>
<option>PIX – Pixel</option>
<option>CCD – Click command</option>
<option>PCC – Pixel and Click command</option>
<option>RMV – Rich Media Video</option>
<option>RME – Rich Media Expand</option>
<option>RMO – Rich Media Other</option>
</select>
</form>
Is this simple or would I need to use the DOM and use createElement etc? Would it be easier if this was done in a table?
Just to be clear, I'm trying NOT to use JQuery...I'm willing to switch though if it's easier to do it this way.
A: Add the plus button next to each input and give them a class of addRow (for example).
Map a function to .addRow's click event:
$(".addRow").click(function(){
$(this)
.prev("input") // select the previous input element
.clone() // clone said element
.appendTo("#formID"); // append the clone to the form
});
Keep in mind this will clone the existing values of the inputs too, so you may want to clear the clone's value using val() before appending it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8603390",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C# Read and Write objectname and object coordinate position i am doing some sort of animation that record the object position frame by frame. I want to save the frameNo, objectname and the object coordinate position x,y,z into textfile and i can able retrieve the data. What is the best way to implement it?
palmTimer-=Time.time;
if(palmTimer <= 0)
{
palmFrame +=1;
Debug.Log (palmFrame);
Debug.Log (palmObject);
Debug.Log (palmObject.transform.localPosition);
palmTimer =180.0f;
}
A: Use a struct of some sort to store the data, then use an XML or JSON serializer to store and retrieve the data into an array of the structs.
struct FrameData
{
public int FrameNumber;
public string ObjectName;
public int X, Y, Z;
public FrameData(int frameNumber, string objectName, int x, int y, int z)
{
this.FrameNumber = frameNumber; this.ObjectName = objectName; this.X = x;
this.Y = y; this.Z = z;
}
}
At each frame, store the data into a new FrameData object and put it into an array or a list. Then when finished, use a serializer to serialize the data.
XmlSerializer serializer = new XmlSerializer(typeof(FrameData[]));
using (FileStream fs = File.Open(filepath, FileMode.Create))
{
serializer.Serialize(fs, frameDataArray);
}
Then to get the data again:
XmlSerializer serializer = new XmlSerializer(typeof(FrameData[]));
FrameData[] frameDataArray;
using (FileStream fs = File.Open(filepath, FileMode.Open))
{
frameDataArray = (FrameData[])serializer.Deserialize(fs);
}
If XML serialization takes up too much space you could try using JSON instead. There are plenty of resources online to teach you about JSON serialization/deserialization, it's pretty similar to the XML version. I would recommend the Nuget library JSON.NET, it's good and simple.
Can't guarantee the code I wrote will work exactly as is, but it should hopefully point you in the right direction.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23600320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Pass template class instance type alias to non-member template function Is there a way to pass template class instances type alias (ClassTmplt/DerivedFloat::InternalType) to external non-member template function (DoSomething) using Base class object pointer (like in two last test() function commented lines)?
class Base
{
};
template <typename T>
class ClassTmplt:
public Base
{
public:
using InternalType = T;
};
class DerivedFloat:
public ClassTmplt<float>
{
};
template <typename T, typename TIn>
void DoSomething(const TIn value)
{
T val = T(value);
std::cout << val << " | " << typeid(val).name() << " | " << typeid(value).name() << std::endl;
}
template <typename T>
typename T::InternalType PassInternalType(T* obj)
{
return T::InternalType;
//return obj::InternalType
}
void test()
{
Base* obj = new DerivedFloat;
DoSomething<float>(1.23);
DoSomething<DerivedFloat::InternalType>(1UL);
//DoSomething<(*obj)::InternalType>(-123);
//DoSomething<PassInternalType(obj)>(4.56);
}
A: No. Consider:
void f(Base* ptr) {
// What type does ptr point to?
// The runtime derived type might not exist when this function compiles
}
Since the dynamic type of the pointer is only know at runtime, it's impossible for the compiler to gain access to it when compiling the function.
If the definition is available there may be some more options, but all of them require you knowing in advance the entire set of types you intend to support, and possibly need to downcast to first. (A type "id" might help if you go this route.)
You might be able to build some limited working designs with a visitor pattern.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47803594",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Customizing JSON.Net output Back story: I started to use the JSON serializer build into .net but quickly ran into a fair few limitation.
With the way that I need to publish data, its more for producing summaries of object graphs rather than full data dumps. I never know how big these graphs are going to be, where they will cause exceptions, etc.
Based on what I need to do the following are my requirements (note some of these I can do, others I can't find a point of reference within JSON.Net as to where I would build the functionality):
*
*Handel exceptions as trying to seralize graph - CAN DO
*
*The property that caused the exception should still be included in the JSON output and the value be the exception type - ????
*Handel circular references - CAN DO
*Trimming massive strings - CAN DO
*Object graph deepth trimming - ????
*Object graph sibling count trimming - ????
*Object graph total node count trimming - ????
*Serializing different objects in the graph differently to other objects (i.e. have a different JsonSerializerSettings for different properties) - ????
If anyone can give me any pointers as to which direction to go to be able to target the various points that would be great.
A: Did you try checking out the Linq-to-Json in Json.NET for most of these? (even though it would probably get ugly)
http://james.newtonking.com/pages/json-net.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5747121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: IntelliJ java.lang.ClassNotFoundException: com.intellij.ide.plugins.PluginManager during startup I use IntelliJ IDEA Community Edition 2017.1.4 x64 and got following error message during application starting process:
Internal error. Please report to
http://jb.gg/ide/critical-startup-errors
java.lang.ClassNotFoundException:
com.intellij.ide.plugins.PluginManager
at com.intellij.util.lang.UrlClassLoader.findClass(UrlClassLoader.java:225)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at com.intellij.ide.Bootstrap.main(Bootstrap.java:36)
at com.intellij.idea.Main.main(Main.java:79)
I already tried to remove IDE caches folder: https://intellij-support.jetbrains.com/hc/articles/206544519.
A: Your installation is corrupted, please reinstall.
A: Below are the steps which i have tried
*
*Clearing cache as per the intellij Website instructions --didn't worked
*Clearing Temp files -- didn't worked
*Use window system cleaner to remove...temp files..temp internet files..etc --- Worked.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44967048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Android game speed on screen size I have had a recurring problem which has continued to surface the past couple of years and I'd like to finally resolve it.
So I have an Android game which is a bit like Space Invaders (enemies in a line move across the screen). The issue I have is with supporting different screen sizes with Surface View. Clearly the distance the enemy moves will be dependent on the screen size to keep the same difficulty level. So I have a ratio for width and height that I multiply everything by to make sure everything is drawn in the correct locations proportional to the screen size. Such as the following:
posX += (int)(GameScreen.wRatio * speed + 0.5f);
The obvious problem here is that posX is an int and I am casting a float (since drawing a bitmap only takes int parameters). So what ends up happening, is that in some cases the position will be rounded up to the next int making the game faster than it should be. Or, in some cases posX is rounded to 0.
What would be the best approach to avoid this? I can assume that always incrementing by the smallest I can ( by 1 ) and then skipping increments for particular enemies on each update of the game loop. But, this would require a lot of changes to my code and I would like to hear what other suggestions there may be before I do that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18484828",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ASP.Net MVC Model Class key identifier I am new to ASP.Net MVC and I am trying to get a better understanding of ASP.Net MVC. I did a couple tutorials and made a few models in those tutorials. One question that kept popping up in my head was: When would I use public int Id { get; set; } and when would I be using public int MyClassNameId { get; set; } instead as identifier for my model class? Would it matter if I would use a custom property name instead of the default Id name for my identifier for a model class?
For example, why would I use public int ArtistId { get; set; } over public int Id { get; set; }?:
public class Artist
{
public int ArtistId { get; set; }
public string Name { get; set; }
}
Is it so that it matches a property name in another class in which it will be used as Foreign Key?
A: Entity Framework CodeFirst recognize the key, by default, by name. Valid names are Id or <YourClassName>Id.
Your property should be named Id or AccountTypesId
Another way is to use the ModelBuilder to specify the key.
Sample
public class MyDbContext : DbContext
{
public DbSet<Artists> Artists{ get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Artists>.HasKey(x => x.ArtistId);
base.OnModelCreating(modelBuilder);
}
}
More about it you can find here
A: If you use custom property names then compiler will not understand it's meaning that it is an id and must be used as primary key in database table.
when you name it id compiler understands it's meaning .
A: This depends on whether or not using Entity Framework to set up your databases. If you are Entity Framework looks for specific property names to identity as Primary Keys.
For example, let's say you have a model called Book.
public class Book
{
public string Title {get; set;}
//all other properties here
}
When Entity Framework tries to set up your database, it looks for a property that it can identify as a primary key corresponding to the specific model. In this case EF would look for "BookID" as a primary key. So if you wished to have an accessible primary key property you would set it up like this.
public class Book
{
public int BookID {get;set;}
public string Title {get; set;}
//all other properties here
}
If you wished to set up a primary key that was not called "BookID", you could use a data annotation:
public class Book
{
[Key]
public int BookIdentifier{get;set;}
public string Title {get; set;}
//all other properties here
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43833657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to make a RPC call to telegram api? More than 1 week I am trying to communicate with Telegram using RPC call. I readed more than 20 webpage in SO a telegram RPC call documentation to be able to do that, but still I can not. I need your help for this. I imported tl-core and mtproto an telegram api from github source codes into eclipse, but there are some errors that I can not solve. If anyone implemented such a app please help me about that. I need that. Thanks.
A: Telegram API documentation is tricky, but once you get the hang of the authors writing style and work through the AuthKey Creation you will be well on your way.
The starting point in the documentation is:
https://core.telegram.org/mtproto/auth_key
and
https://core.telegram.org/mtproto/samples-auth_key
I had put together a detailed write up for most of this here
The procedures and patterns you build along the way will be usable for further exploration of the Telegram API
cheers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32289907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Logstash Indexing Error - Aggregate plugin: For task_id pattern '%{id}', there are more than one filter Am using Elasticsearch 5.5.0 and logstash 5.5.0 on Linux - AWS ec2-instance.
Have a logstash_etl.conf file which resides in /etc/logstash/conf.d:
input {
jdbc {
jdbc_connection_string => "jdbc:mysql://localhost:3306/mydatabase"
jdbc_user => "root"
jdbc_password => ""
jdbc_driver_library => "/etc/logstash/mysql-connector/mysql-connector-java-5.1.21.jar"
jdbc_driver_class => "com.mysql.jdbc.driver"
schedule => "*/5 * * * *"
statement => "select * from customers"
use_column_value => false
clean_run => true
}
}
filter {
if ([api_key]) {
aggregate {
task_id => "%{id}"
push_map_as_event_on_timeout => false
#timeout_task_id_field => "[@metadata][index_id]"
#timeout => 60
#inactivity_timeout => 30
code => "sample code"
timeout_code => "sample code"
}
}
}
# sudo /usr/share/logstash/bin/logstash-plugin install logstash-output-exec
output {
if ([purge_task] == "yes") {
exec {
command => "curl -XPOST '127.0.0.1:9200/_all/_delete_by_query?conflicts=proceed' -H 'Content-Type: application/json' -d'
{
\"query\": {
\"range\" : {
\"@timestamp\" : {
\"lte\" : \"now-3h\"
}
}
}
}
'"
}
} else {
stdout { codec => json_lines}
elasticsearch {
"hosts" => "127.0.0.1:9200"
"index" => "myindex_%{api_key}"
"document_type" => "%{[@metadata][index_type]}"
"document_id" => "%{[@metadata][index_id]}"
"doc_as_upsert" => true
"action" => "update"
"retry_on_conflict" => 7
}
}
}
When I restart logstash like this:
sudo initctl restart logstash
Inside /var/log/logstash/logstash-plain.log - everything works an actual indexing into Elasticsearch is occuring!
However if I add another SQL input into this config file:
input {
jdbc {
jdbc_connection_string => "jdbc:mysql://localhost:3306/mydatabase"
jdbc_user => "root"
jdbc_password => ""
jdbc_driver_library => "/etc/logstash/mysql-connector/mysql-connector-java-5.1.21.jar"
jdbc_driver_class => "com.mysql.jdbc.driver"
schedule => "*/5 * * * *"
statement => "select * from orders"
use_column_value => false
clean_run => true
}
}
The indexing stops because of an error inside the config file!
Inside /var/log/logstash/logstash-plain.log:
[2018-04-06T21:33:54,123][ERROR][logstash.agent ] Pipeline aborted due to error {:exception=>#<LogStash::ConfigurationError: Aggregate plugin: For task_id pattern '%{id}', there are more than one filter which defines timeout options. All timeout options have to be defined in only one aggregate filter per task_id pattern. Timeout options are : timeout, inactivity_timeout, timeout_code, push_map_as_event_on_timeout, push_previous_map_as_event, timeout_task_id_field, timeout_tags>, :backtrace=>["/usr/share/logstash/vendor/bundle/jruby/1.9/gems/logstash-filter-aggregate-2.6.1/lib/logstash/filters/aggregate.rb:486:in `register'", "org/jruby/ext/thread/Mutex.java:149:in `synchronize'", "/usr/share/logstash/vendor/bundle/jruby/1.9/gems/logstash-filter-aggregate-2.6.1/lib/logstash/filters/aggregate.rb:480:in `register'", "/usr/share/logstash/logstash-core/lib/logstash/pipeline.rb:281:in `register_plugin'", "/usr/share/logstash/logstash-core/lib/logstash/pipeline.rb:292:in `register_plugins'", "org/jruby/RubyArray.java:1613:in `each'", "/usr/share/logstash/logstash-core/lib/logstash/pipeline.rb:292:in `register_plugins'", "/usr/share/logstash/logstash-core/lib/logstash/pipeline.rb:302:in `start_workers'", "/usr/share/logstash/logstash-core/lib/logstash/pipeline.rb:226:in `run'", "/usr/share/logstash/logstash-core/lib/logstash/agent.rb:398:in `start_pipeline'"]}
[2018-04-06T21:33:54,146][INFO ][logstash.agent ] Successfully started Logstash API endpoint {:port=>9600}
[2018-04-06T21:33:57,131][WARN ][logstash.agent ] stopping pipeline {:id=>"main"}
Am really new to logstash and Elasticsearch...
What does this mean?
Would appreciate if someone could tell me why by just by adding one new input causes this tool to crash?!
A:
Would appreciate if someone could tell me why by just by adding one new input causes this tool to crash?!
You can't add two input statement inside the same configuration. Like the documentation says, if you want to add more than one input in a config file, you should use something like that:
input {
file {
path => "/var/log/messages"
type => "syslog"
}
file {
path => "/var/log/apache/access.log"
type => "apache"
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49701823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using legacy projects containing 'System.Web.HttpContext' in ASP.NET Core3.1 We have some legacy projects, written with .Net Framework which should be used by an API project which is written by ASP.NET Core3.1.
The problem is that these legacy projects are using 'System.Web.HttpContext' that you know does not exist in .net core anymore.
Now we are receiving this error:
'Could not load type 'System.Web.HttpContext' from assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.'
Have you faced this problem before? Can anyone help please?
A: .NET Framework libraries are not technically compatible with .NET Core. .NET Standard libraries are, and since both .NET Framework and .NET Core implement .NET Standard, Microsoft made a special exemption in the compiler to allow .NET Framework libraries to be referenced by projects that target .NET Core, with the caveat that they may not actually work. You get a warning to this effect when you reference a .NET Framework library from a .NET Core project.
The .NET Framework library will work as long as it only uses APIs compatible with .NET Standard 2.0. System.Web.HttpContext is not one such API, so it will not work in a .NET Core project. Period. Nothing you can do about that.
You can attempt to multi-target your libraries and sub-in .NET Core compatible APIs using compiler directives. That'll work, but gets messy quick. Otherwise, you'll just have to write new versions of the libraries for ASP.NET Core, since presumably you're trying to maintain support in the current libraries for ASP.NET.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59642906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Return model data inside model function in cakePHP I'm a beginner in cakePHP and I'm kind of stuck about retrieving data.
I have a controller, in which I want to get a users deposit amount.
Therefore I have a user model and a deposit model.
The deposit model looks like this:
<?php
App::uses('AppModel', 'Model');
class Deposit extends AppModel {
public $belongsTo = array('User');
public $useTable = 'deposits';
public $validate = array();
public function __construct($id = false, $table = null, $ds = null) {
parent::__construct($id, $table, $ds);
}
public function getDepositAmount() {
// return a users deposit amount
}
}
?>
How can I tell the model to return the amount (database field is called deposit_amount) and how does it know to which user id it belongs to? Thank you!
A: Uses of belongsTo in CakePhp
class Deposit extends AppModel {
public $useTable = 'deposits';
public $validate = array();
public function __construct($id = false, $table = null, $ds = null) {
parent::__construct($id, $table, $ds);
}
public function getDepositAmount() {
$this->belongsTo('User')
->setForeignKey('user_id');
// your find query here
}
}
Please read doc first for better understanding CakePhp Doc
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44302357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Installation of rdyncall package for R Hi I have a problem with installation rdyncall. rdyncall is in archive and I tried this:
url = "http://cran.r-project.org/src/contrib/Archive/rdyncall/rdyncall_0.7.5.tar.gz"
pkgFile = "rdyncall_0.7.5.tar.gz"
download.file(url = url, destfile = pkgFile)
install.packages(pkgs=pkgFile, type="source",repos=NULL)
unlink(pkgFile)
after install.packages("...") I got this error:
ERROR: failed to lock directory 'C:/Users/user/Documents/R/win-library/3.1' for modifying
Try removing 'C:/Users/user/Documents/R/win-library/3.1/00LOCK-rdyncall'
Warning in install.packages :
running command '"C:/PROGRA~1/R/R-3.1.2/bin/x64/R" CMD INSTALL -l "C:\Users\user\Documents\R\win-library\3.1" "rdyncall_0.7.5.tar.gz"' had status 3
Warning in install.packages :
installation of package ‘rdyncall_0.7.5.tar.gz’ had non-zero exit status
I have removed permission in windows "only to read" but nothing. I tried it at 3.1.2, 3.0, and 2.15 version of R.
A: I try it at Win8 and it is working. At win 8.1 and win7 it is not working. I dont known why, but if I after that copy "R Folder" from program files (from Win8) to Win 8.1. It is working.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27721969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Zend 1 not working with psr-4 namespaces I am working on zend framework 1 But I want to use \ instead of _
Like
class IndexController extends Zend_Controller_Action
This is working fine but when I changed this by
class IndexController extends \Zend\Controller\Action
Then its giving me a error
Fatal error: Cannot redeclare class Zend_Controller_Action in /var/www/flipit_application/vendor/zendframework/zendframework1/library/Zend/Controller/Action.php on line 43
I have created the namespaces in composer
"autoload": {
"psr-4": {
"Zend\\": "vendor/zendframework/zendframework1/library/Zend/"
}
},
So how Can use these namespaces in code
Is this possible in Zend Framework1?.
A: Zend Framework 1 doesn't use psr-4 autoloading, it uses psr-0:
"autoload": {
"psr-0": {
"Zend_": "vendor/zendframework/zendframework1/library"
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31260530",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Kivy VM buildozer I need your help because I have a kivy application and I am trying to use buildozer in the VM.
(I followed these steps if you are interested: https://kivy.org/docs/guide/packaging-android-vm.html)
My code is in Python3 so I downloaded the Crystax NDK as it is written in the readme here: https://pypi.python.org/pypi/buildozer
Still according to the read-me, I changed the following lines in the buildozer.spec:
requirements = python3crystax,kivy
android.ndk_path =/home/kivy/Desktop/crystax-ndk-10.3.2
And I have this error after executing: buildozer android_new debug:
id: 124 or "sys-img-x86-android-15"
Type: SystemImage
Desc: Intel x86 Atom System Image
Revision 4
Requires SDK Platform Android API 15
----------
id: 125 or "sys-img-mips-android-15"
Type: SystemImage
Desc: MIPS System Image
Revision 1
Requires SDK Platform Android API 15
----------
id: 126 or "sys-img-armeabi-v7a-google_apis-15"
Type: SystemImage
Desc: Google APIs ARM EABI v7a System Image
Revision 5
Requires SDK Platform Android API 15
----------
id: 127 or "sys-img-x86-google_apis-15"
Type: SystemImage
Desc: Google APIs Intel x86 Atom System Image
Revision 5
Requires SDK Platform Android API 15
----------
id: 128 or "sys-img-armeabi-v7a-android-14"
Type: SystemImage
Desc: ARM EABI v7a System Image
Revision 2
Requires SDK Platform Android API 14
----------
id: 129 or "sys-img-armeabi-v7a-android-10"
Type: SystemImage
Desc: ARM EABI v7a System Image
Revision 4
Requires SDK Platform Android API 10
----------
id: 130 or "sys-img-x86-android-10"
Type: SystemImage
Desc: Intel x86 Atom System Image
Revision 4
Requires SDK Platform Android API 10
----------
id: 131 or "sys-img-armeabi-v7a-google_apis-10"
Type: SystemImage
Desc: Google APIs ARM EABI v7a System Image
Revision 5
Requires SDK Platform Android API 10
----------
id: 132 or "sys-img-x86-google_apis-10"
Type: SystemImage
Desc: Google APIs Intel x86 Atom System Image
Revision 5
Requires SDK Platform Android API 10
----------
id: 133 or "addon-google_apis-google-24"
Type: Addon
Desc: Google APIs, Android API 24, revision 1
By Google Inc.
Android + Google APIs
Requires SDK Platform Android API 24
----------
id: 134 or "addon-google_apis-google-23"
Type: Addon
Desc: Google APIs, Android API 23, revision 1
By Google Inc.
Android + Google APIs
Requires SDK Platform Android API 23
----------
id: 135 or "addon-google_apis-google-22"
Type: Addon
Desc: Google APIs, Android API 22, revision 1
By Google Inc.
Android + Google APIs
Requires SDK Platform Android API 22
----------
id: 136 or "addon-google_apis-google-21"
Type: Addon
Desc: Google APIs, Android API 21, revision 1
By Google Inc.
Android + Google APIs
Requires SDK Platform Android API 21
----------
id: 137 or "addon-google_apis-google-19"
Type: Addon
Desc: Google APIs, Android API 19, revision 20
By Google Inc.
Android + Google APIs
Requires SDK Platform Android API 19
----------
id: 138 or "addon-google_gdk-google-19"
Type: Addon
Desc: Glass Development Kit Preview, Android API 19, revision 11
By Google Inc.
Preview of the Glass Development Kit
Requires SDK Platform Android API 19
----------
id: 139 or "addon-google_apis-google-18"
Type: Addon
Desc: Google APIs, Android API 18, revision 4
By Google Inc.
Android + Google APIs
Requires SDK Platform Android API 18
----------
id: 140 or "addon-google_apis-google-17"
Type: Addon
Desc: Google APIs, Android API 17, revision 4
By Google Inc.
Android + Google APIs
Requires SDK Platform Android API 17
----------
id: 141 or "addon-google_apis-google-16"
Type: Addon
Desc: Google APIs, Android API 16, revision 4
By Google Inc.
Android + Google APIs
Requires SDK Platform Android API 16
----------
id: 142 or "addon-google_apis-google-15"
Type: Addon
Desc: Google APIs, Android API 15, revision 3
By Google Inc.
Android + Google APIs
Requires SDK Platform Android API 15
----------
id: 143 or "addon-google_apis-google-14"
Type: Addon
Desc: Google APIs, Android API 14, revision 2 (Obsolete)
By Google Inc.
Android + Google APIs
Requires SDK Platform Android API 14
----------
id: 144 or "addon-google_apis-google-13"
Type: Addon
Desc: Google APIs, Android API 13, revision 1 (Obsolete)
By Google Inc.
Android + Google APIs
Requires SDK Platform Android API 13
----------
id: 145 or "addon-google_tv_addon-google-13"
Type: Addon
Desc: Google TV Addon, Android API 13, revision 1 (Obsolete)
By Google Inc.
Requires SDK Platform Android API 13
----------
id: 146 or "addon-google_apis-google-12"
Type: Addon
Desc: Google APIs, Android API 12, revision 1 (Obsolete)
By Google Inc.
Android + Google APIs
Requires SDK Platform Android API 12
----------
id: 147 or "addon-google_tv_addon-google-12"
Type: Addon
Desc: Google TV Addon, Android API 12, revision 2 (Obsolete)
By Google Inc.
Requires SDK Platform Android API 12
----------
id: 148 or "addon-google_apis-google-11"
Type: Addon
Desc: Google APIs, Android API 11, revision 1 (Obsolete)
By Google Inc.
Android + Google APIs
Requires SDK Platform Android API 11
----------
id: 149 or "addon-google_apis-google-10"
Type: Addon
Desc: Google APIs, Android API 10, revision 2 (Obsolete)
By Google Inc.
Android + Google APIs
Requires SDK Platform Android API 10
----------
id: 150 or "addon-google_apis-google-9"
Type: Addon
Desc: Google APIs, Android API 9, revision 2 (Obsolete)
By Google Inc.
Android + Google APIs
Requires SDK Platform Android API 9
----------
id: 151 or "addon-google_apis-google-8"
Type: Addon
Desc: Google APIs, Android API 8, revision 2 (Obsolete)
By Google Inc.
Android + Google APIs
Requires SDK Platform Android API 8
----------
id: 152 or "addon-google_apis-google-7"
Type: Addon
Desc: Google APIs, Android API 7, revision 1 (Obsolete)
By Google Inc.
Android + Google APIs
Requires SDK Platform Android API 7
----------
id: 153 or "addon-google_apis-google-6"
Type: Addon
Desc: Google APIs, Android API 6, revision 1 (Obsolete)
By Google Inc.
Android + Google APIs
Requires SDK Platform Android API 6
----------
id: 154 or "addon-google_apis-google-5"
Type: Addon
Desc: Google APIs, Android API 5, revision 1 (Obsolete)
By Google Inc.
Android + Google APIs
Requires SDK Platform Android API 5
----------
id: 155 or "addon-google_apis-google-4"
Type: Addon
Desc: Google APIs, Android API 4, revision 2 (Obsolete)
By Google Inc.
Android + Google APIs
Requires SDK Platform Android API 4
----------
id: 156 or "addon-google_apis-google-3"
Type: Addon
Desc: Google APIs, Android API 3, revision 3 (Obsolete)
By Google Inc.
Android + Google APIs
Requires SDK Platform Android API 3
----------
id: 157 or "source-25"
Type: Source
Desc: Sources for Android SDK, API 25, revision 1
----------
id: 158 or "source-24"
Type: Source
Desc: Sources for Android SDK, API 24, revision 1
----------
id: 159 or "source-23"
Type: Source
Desc: Sources for Android SDK, API 23, revision 1
----------
id: 160 or "source-22"
Type: Source
Desc: Sources for Android SDK, API 22, revision 1
----------
id: 161 or "source-21"
Type: Source
Desc: Sources for Android SDK, API 21, revision 1
----------
id: 162 or "source-20"
Type: Source
Desc: Sources for Android SDK, API 20, revision 1
----------
id: 163 or "source-19"
Type: Source
Desc: Sources for Android SDK, API 19, revision 2
----------
id: 164 or "source-18"
Type: Source
Desc: Sources for Android SDK, API 18, revision 1
----------
id: 165 or "source-17"
Type: Source
Desc: Sources for Android SDK, API 17, revision 1
----------
id: 166 or "source-16"
Type: Source
Desc: Sources for Android SDK, API 16, revision 2
----------
id: 167 or "source-15"
Type: Source
Desc: Sources for Android SDK, API 15, revision 2
----------
id: 168 or "source-14"
Type: Source
Desc: Sources for Android SDK, API 14, revision 1 (Obsolete)
----------
id: 169 or "extra-android-m2repository"
Type: Extra
Desc: Android Support Repository, revision 47
By Android
Local Maven repository for Support Libraries
Install path: extras/android/m2repository
----------
id: 170 or "extra-google-admob_ads_sdk"
Type: Extra
Desc: Google AdMob Ads SDK, revision 11 (Obsolete)
By Google Inc.
AdMob Ads SDK
Install path: extras/google/admob_ads_sdk
----------
id: 171 or "extra-google-analytics_sdk_v2"
Type: Extra
Desc: Google Analytics App Tracking SDK, revision 3 (Obsolete)
By Google Inc.
Analytics App Tracking SDK
Install path: extras/google/analytics_sdk_v2
----------
id: 172 or "extra-google-auto"
Type: Extra
Desc: Android Auto Desktop Head Unit emulator, revision 1.1
By Google Inc.
Head unit emulator for developers targeting the Android Auto
platform.
Install path: extras/google/auto
----------
id: 173 or "extra-google-gcm"
Type: Extra
Desc: Google Cloud Messaging for Android Library, revision 3 (Obsolete)
By Google Inc.
GCM library has been moved to Google Play Services
(com.google.android.gms.gcm) and this standalone version is no
longer supported
Install path: extras/google/gcm
----------
id: 174 or "extra-google-google_play_services_froyo"
Type: Extra
Desc: Google Play services for Froyo, revision 12 (Obsolete)
By Google Inc.
Google Play services client library and sample code
Install path: extras/google/google_play_services_froyo
----------
id: 175 or "extra-google-google_play_services"
Type: Extra
Desc: Google Play services, revision 42
By Google Inc.
Google Play services Javadocs and sample code
Install path: extras/google/google_play_services
----------
id: 176 or "extra-google-instantapps"
Type: Extra
Desc: Instant Apps Development SDK, revision 1
By Google Inc.
Android Instant Apps Development SDK
Install path: extras/google/instantapps
----------
id: 177 or "extra-google-m2repository"
Type: Extra
Desc: Google Repository, revision 55
By Google Inc.
Local Maven repository for Support Libraries
Install path: extras/google/m2repository
----------
id: 178 or "extra-google-market_apk_expansion"
Type: Extra
Desc: Google Play APK Expansion library, revision 1
By Google Inc.
Android Market APK Expansion library
Install path: extras/google/market_apk_expansion
----------
id: 179 or "extra-google-market_licensing"
Type: Extra
Desc: Google Play Licensing Library, revision 1
By google
Android Market Licensing client library
Install path: extras/google/market_licensing
----------
id: 180 or "extra-google-play_billing"
Type: Extra
Desc: Google Play Billing Library, revision 5
By Google Inc.
Google Play Billing files and sample code
Install path: extras/google/play_billing
----------
id: 181 or "extra-google-simulators"
Type: Extra
Desc: Android Auto API Simulators, revision 1
By Google Inc.
Android Auto API testing simulators
Install path: extras/google/simulators
----------
id: 182 or "extra-google-webdriver"
Type: Extra
Desc: Google Web Driver, revision 2
By Google Inc.
Install path: extras/google/webdriver
# Check that aidl can be executed
# Search for Aidl
# Run '/home/kivy/.buildozer/android/platform/android-sdk-20/build-tools/26.0.0/aidl'
# Cwd None
# Android packages installation done.
# Check application requirements
# Check garden requirements
# Compile platform
# Run 'python -m pythonforandroid.toolchain --color=always --storage-dir=/home/kivy/Desktop/New Folder2/.buildozer/android/platform/build create --dist_name=myapp --bootstrap=sdl2 --requirements=python3crystax,kivy --arch armeabi-v7a --copy-libs'
# Cwd /home/kivy/Desktop/New Folder2/.buildozer/android/platform/python-for-android-master
usage: toolchain.py [-h]
{recipes,bootstraps,clean_all,clean_dists,clean_bootstrap_builds,clean_builds,clean,clean_recipe_build,clean_download_cache,export_dist,apk,create,archs,distributions,delete_dist,sdk_tools,adb,logcat,build_status}
...
toolchain.py: error: argument subparser_name: invalid choice: 'Folder2/.buildozer/android/platform/build' (choose from 'recipes', 'bootstraps', 'clean_all', 'clean_dists', 'clean_bootstrap_builds', 'clean_builds', 'clean', 'clean_recipe_build', 'clean_download_cache', 'export_dist', 'apk', 'create', 'archs', 'distributions', 'delete_dist', 'sdk_tools', 'adb', 'logcat', 'build_status')
# Command failed: python -m pythonforandroid.toolchain --color=always --storage-dir=/home/kivy/Desktop/New Folder2/.buildozer/android/platform/build create --dist_name=myapp --bootstrap=sdl2 --requirements=python3crystax,kivy --arch armeabi-v7a --copy-libs
#
# Buildozer failed to execute the last command
# The error might be hidden in the log above this error
# Please read the full log, and search for it before
# raising an issue with buildozer itself.
# In case of a bug report, please add a full log with log_level = 2
kivy@kivyvm:~/Desktop/New Folder2$
Thanks a lot for your help
python code (kivy example):
from random import random
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.graphics import Color, Ellipse, Line
class MyPaintWidget(Widget):
def on_touch_down(self, touch):
color = (random(), 1, 1)
with self.canvas:
Color(*color, mode='hsv')
d = 30.
Ellipse(pos=(touch.x - d / 2, touch.y - d / 2), size=(d, d))
touch.ud['line'] = Line(points=(touch.x, touch.y))
def on_touch_move(self, touch):
touch.ud['line'].points += [touch.x, touch.y]
class MyPaintApp(App):
def build(self):
parent = Widget()
self.painter = MyPaintWidget()
clearbtn = Button(text='Clear')
clearbtn.bind(on_release=self.clear_canvas)
parent.add_widget(self.painter)
parent.add_widget(clearbtn)
return parent
def clear_canvas(self, obj):
self.painter.canvas.clear()
if __name__ == '__main__':
MyPaintApp().run()
A: Still, the Python3 is experimental in Kivy.
https://kivy.org/doc/stable/guide/packaging-android.html
If you can work in Python2 better try that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44852431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Creating a Spring Boot admin server that also contains Sleuth Dependencies I am developing a Spring Boot Admin Server. When I add Sleuth dependencies (for tracing requests and responses in a distributed architecture), I am getting an exception on startup.
When I comment out the Sleuth dependencies in my POM, the application starts just fine.
The POM
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-sleuth-zipkin</artifactId>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-server</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-server-ui</artifactId>
<version>1.4.1</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Camden.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
The main class
import de.codecentric.boot.admin.config.EnableAdminServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
@SpringBootApplication
@Configuration
@EnableAdminServer
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
}
}
The full stacktrace
java.lang.IllegalStateException: Error processing condition on org.springframework.cloud.sleuth.instrument.zuul.TraceZuulAutoConfiguration.tracePreZuulFilter
at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:64) ~[spring-boot-autoconfigure-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:102) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForBeanMethod(ConfigurationClassBeanDefinitionReader.java:178) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:140) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:116) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:336) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:246) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:273) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:98) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:681) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:523) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1186) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1175) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at ke.co.teketaxi.sleuthissue.Application.main(Application.java:21) [classes/:na]
Caused by: java.lang.IllegalStateException: @ConditionalOnMissingBean did not specify a bean using type, name or annotation and the attempt to deduce the bean's type failed
at org.springframework.boot.autoconfigure.condition.OnBeanCondition$BeanSearchSpec.validate(OnBeanCondition.java:310) ~[spring-boot-autoconfigure-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.boot.autoconfigure.condition.OnBeanCondition$BeanSearchSpec.<init>(OnBeanCondition.java:300) ~[spring-boot-autoconfigure-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getMatchOutcome(OnBeanCondition.java:112) ~[spring-boot-autoconfigure-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:47) ~[spring-boot-autoconfigure-1.4.1.RELEASE.jar:1.4.1.RELEASE]
... 17 common frames omitted
Caused by: org.springframework.boot.autoconfigure.condition.OnBeanCondition$BeanTypeDeductionException: Failed to deduce bean type for org.springframework.cloud.sleuth.instrument.zuul.TraceZuulAutoConfiguration.tracePreZuulFilter
at org.springframework.boot.autoconfigure.condition.OnBeanCondition$BeanSearchSpec.addDeducedBeanTypeForBeanMethod(OnBeanCondition.java:373) ~[spring-boot-autoconfigure-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.boot.autoconfigure.condition.OnBeanCondition$BeanSearchSpec.addDeducedBeanType(OnBeanCondition.java:347) ~[spring-boot-autoconfigure-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.boot.autoconfigure.condition.OnBeanCondition$BeanSearchSpec.<init>(OnBeanCondition.java:294) ~[spring-boot-autoconfigure-1.4.1.RELEASE.jar:1.4.1.RELEASE]
... 19 common frames omitted
Caused by: java.lang.NoClassDefFoundError: org/springframework/cloud/context/named/NamedContextFactory
at java.lang.ClassLoader.defineClass1(Native Method) ~[na:1.8.0_101]
at java.lang.ClassLoader.defineClass(ClassLoader.java:763) ~[na:1.8.0_101]
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) ~[na:1.8.0_101]
at java.net.URLClassLoader.defineClass(URLClassLoader.java:467) ~[na:1.8.0_101]
at java.net.URLClassLoader.access$100(URLClassLoader.java:73) ~[na:1.8.0_101]
at java.net.URLClassLoader$1.run(URLClassLoader.java:368) ~[na:1.8.0_101]
at java.net.URLClassLoader$1.run(URLClassLoader.java:362) ~[na:1.8.0_101]
at java.security.AccessController.doPrivileged(Native Method) ~[na:1.8.0_101]
at java.net.URLClassLoader.findClass(URLClassLoader.java:361) ~[na:1.8.0_101]
at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_101]
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) ~[na:1.8.0_101]
at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_101]
at java.lang.Class.getDeclaredMethods0(Native Method) ~[na:1.8.0_101]
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701) ~[na:1.8.0_101]
at java.lang.Class.getDeclaredMethods(Class.java:1975) ~[na:1.8.0_101]
at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:612) ~[spring-core-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:524) ~[spring-core-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:510) ~[spring-core-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.boot.autoconfigure.condition.OnBeanCondition$BeanSearchSpec.addDeducedBeanTypeForBeanMethod(OnBeanCondition.java:360) ~[spring-boot-autoconfigure-1.4.1.RELEASE.jar:1.4.1.RELEASE]
... 21 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.springframework.cloud.context.named.NamedContextFactory
at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_101]
at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_101]
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) ~[na:1.8.0_101]
at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_101]
... 40 common frames omitted
2016-10-09 11:59:30.432 INFO [-,,,] 2352 --- [ main] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@5c33f1a9: startup date [Sun Oct 09 11:59:28 EAT 2016]; root of context hierarchy
2016-10-09 11:59:30.434 WARN [-,,,] 2352 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception thrown from LifecycleProcessor on context close
java.lang.IllegalStateException: LifecycleProcessor not initialized - call 'refresh' before invoking lifecycle methods via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@5c33f1a9: startup date [Sun Oct 09 11:59:28 EAT 2016]; root of context hierarchy
at org.springframework.context.support.AbstractApplicationContext.getLifecycleProcessor(AbstractApplicationContext.java:416) [spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:997) [spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:956) [spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.boot.SpringApplication.handleRunFailure(SpringApplication.java:818) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:326) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1186) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1175) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at ke.co.teketaxi.sleuthissue.Application.main(Application.java:21) [classes/:na]
A: I added the spring-cloud-starter-zuul dependency and the application started
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39941829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Typing Vuex actions I am using Vue3 and Vuex4 with TS.
Let's say my actions look like this in Vuex:
anAction: async (
{ commit, state }: { commit: Commit; state: MyStoreState },
{ parameter1, parameter2 }: { parameter1: string, parameter2: number }
) => {
/* some code */
commit("...", /* so on so forth */);
},
I am using mapActions inside my components to use those actions:
/* rest of component code */
methods: {
...mapActions(['anAction'])
}
However, if I call this.anAction from any of my component code, this is its signature:
(...args: any[]) => Promise<any>
Is there a way to get the correct typing on the mapped action, i.e. the one I defined in my store?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72894831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: config and settings component for C# I'm starting to design a config and settings component for an application.
I need an easy way to read dictionary style settings and also a way to store simple arrays into a persistence level.
is there a commonly used component already available ? (something like log4net for logging)
what options should I look into ?
A: You don't really need to do that: .NET BCL already has everything you need.
A: Take a look at App.Config and the ConfigurationManager class.
A: If you expand the Properties folder in the SolutionExplorer you should find a Settings.Settings item. Double clicking on this will open the settings editor. This enables you to declare and provide initial values for settings that can either be scoped to the application or the current user. Since the values are persisted in Isolated storage you do not need to worry about what privileges the user is executing under.
For a wee example:
I created a new string setting with the name Drink and a TextBox named drinkTextBox. The code to assign the current value to the text box is:
drinkTextBox.Text = Properties.Settings.Default.Drink;
and to update the value persisted:
Properties.Settings.Default.Drink = drinkTextBox.Text;
Properties.Settings.Default.Save();
A: Depending on how flexible you want it to be, you can use the build in Settings designer (go to Project Properties > Settings) and you can add settings there.
These are strongly typed and accessible through code.
It has built in features like Save, Load and Reload
A: We'll often create a sealed class that has a number of properties that wrap calls to the the System.Configuration.ConfigurationManager class. This allows us to use the standard configuration managagement capabilities offered by the class and the app/web.config file but make the data very easy to access by other classes.
For example we might create a property to expose the connection string to a database as
public static string NorthwindConnectionString
{
get{return ConfigurationManager.ConnectionStrings["Northwind"].ConnectionString
}
While it creates a wrapper around one line of code, which we usually try to avoid, it does make certain confiuration properties accessible via intellisense and provides some insullation around changes to the location of underlying configuration data. If we wanted to move the connection string to the registry, we could do so without major impact to the application.
We find this most helpful when we have larger teams or when we need to hand off code from one team to another. It keeps people from needing to remember what the various settings were named in the config files and even where configuration information is stored (config file, database, registry, ini file, etc.)
A: For noddy apps I use appSettings. For enterprise apps I usually create some custom config sections. CodeProject has some excellent articles on this.
For your scenario of key/value pairs I'd probably use something like this.
A: Building a dictionary in the standard settings
Using the standard Settings, it isn't possible to store dictionary style settings.
To emulate the System.Collections.Specialized.StringDictionary,
what I've done in the past is used two of the System.Collections.Specialized.StringCollection typed settings (this is one of your options for the setting type).
I created one called Keys, and another called values. In a class that needs these settings I've created a static constructor and looped through the two StringCollections and built the StringDictionary into a public static property. The dictionary is then available when needed.
public static StringDictionary NamedValues = new StringDictionary();
public static ClassName() // static construtor
{
StringCollection keys = Properties.Settings.Default.Keys;
StringCollection vals = Properties.Settings.Default.Values;
for(int i = 0; i < keys.Count(); i++)
{
NamedValues.Add(keys[i], vals[i]);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/965116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to install C++ lib Duckx? I want to use this lib DuckX. I followed tutorial,
git clone https://github.com/amiremohamadi/DuckX.git
cd DuckX
mkdir build
cd build
cmake ..
cmake --build .
It went on without any error. However, when I entered sample directory and execute g++ sample1.cpp -lduckx, it got the following error message,
sample1.cpp:1:10: fatal error: duckx.hpp: No such file or directory
#include "duckx.hpp"
^~~~~~~~~~~
compilation terminated.
I wonder how I can successfully use this lib. Could you please tell me what I can do to make the program use this lib. Thanks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65776725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: When resuming music player then music resumes but not the play and pause button states Below is the code which I use.By this code the background music plays on all activities.But when I come back to this activity using home button then music plays normally but the drawables will not resumed. That Mean if music is played and I went back to that activity via home button then play button is shown rather than the pause button but I want that if music played on resume then button is pause and if not then show play button.
Can you tell what to do with play and pause buttons on resuming activties?
public class RadioActivity extends ActionBarActivity implements RadioListener{
private final String[] RADIO_URL = {"url "};
private ActionMenuView amvMenu;
ImageButton mButtonControlStart;
TextView mTextViewControl;
RadioManager mRadioManager = RadioManager.with(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio);
mButtonControlStart = (ImageButton) findViewById(R.id.buttonControlStart);
mRadioManager.registerListener(this);
mRadioManager.setLogging(true);
initializeUI();
mButtonControlStart.setBackgroundResource(R.drawable.play);
Toolbar toolbarBottom = (Toolbar) findViewById(R.id.toolbar);
toolbarBottom.setTitle("Radio");
amvMenu = (ActionMenuView) toolbarBottom.findViewById(R.id.amvMenu);
amvMenu.setOnMenuItemClickListener(new ActionMenuView.OnMenuItemClickListener() {
// toolbarBottom.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switch(item.getItemId()){
case R.id.activity_aboutus:
// TODO
Intent intent=new Intent(RadioActivity.this,Contact_us.class);
startActivity(intent);
break;
// TODO: Other cases
case R.id.menu_refresh:
// TODO
Intent intent1=new Intent(RadioActivity.this,Web.class);
startActivity(intent1);
break;
case R.id.menu_about:
Intent intent2=new Intent(RadioActivity.this,Song_rqst.class);
startActivity(intent2);
break;
case R.id.menu_item_share:
Intent intent3=new Intent(RadioActivity.this,Ratee.class);
startActivity(intent3);
break;
}
return true;
}
});
}
public void initializeUI() {
mButtonControlStart = (ImageButton) findViewById(R.id.buttonControlStart);
mTextViewControl = (TextView) findViewById(R.id.textviewControl);
mButtonControlStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!mRadioManager.isPlaying()) {
mRadioManager.startRadio(RADIO_URL[0]);
mButtonControlStart.setBackgroundResource(R.drawable.end);
}
else {
mRadioManager.stopRadio();
mButtonControlStart.setBackgroundResource(R.drawable.play);
}
}
});
}
@Override
protected void onResume() {
super.onResume();
mRadioManager.connect();
}
@Override
protected void onDestroy() {
super.onDestroy();
mRadioManager.disconnect();
}
@Override
public void onRadioLoading() {
runOnUiThread(new Runnable() {
@Override
public void run() {
//TODO Do UI works here.
mTextViewControl.setText("RADIO STATE : LOADING...");
}
});
}
@Override
public void onRadioConnected() {
}
@Override
public void onRadioStarted() {
runOnUiThread(new Runnable() {
@Override
public void run() {
//TODO Do UI works here.
mTextViewControl.setText("RADIO STATE : PLAYING...");
}
});
}
@Override
public void onRadioStopped() {
runOnUiThread(new Runnable() {
@Override
public void run() {
//TODO Do UI works here
mTextViewControl.setText("RADIO STATE : STOPPED.");
}
});
}
@Override
public void onMetaDataReceived(String s, String s1) {
//TODO Check metadata values. Singer name, song name or whatever you have.
}
@Override
public void onError() {
}
A: Whenever you come back to your Music Play Activity Oncreate() is not called so your drawable resource load on Onpause() or Onstart(), Everytime Oncreate() is not calling.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38671110",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Sort elements to specified data-* order I have a list of items in a <ul>:
<li data-number="1"> Pierce </li>
<li data-number="2"> Annie </li>
<li data-number="3"> Jeff </li>
<li data-number="4"> Abed </li>
<li data-number="5"> Britta </li>
Actually, the list is much longer with real data, but bear with me. As you can see, the <li> elements are listed in numerical order. However, I need to rearrange them to fit a specified order in an array:
Array(2, 3, 1, 5, 4)
How do I do this? If sorted by the array above, the elements should be like the following:
<li data-number="2"> Annie </li>
<li data-number="3"> Jeff </li>
<li data-number="1"> Pierce </li>
<li data-number="5"> Britta </li>
<li data-number="4"> Abed </li>
This seems simple, but I've looked up every jQuery method in the book and I can't figure out how to do this. Thanks a ton for any help in advance.
Further Clarification:
The specified order is dynamic. However, the elements are always initially listed in numerical order.
A: Iterate through the array starting at index 1. Then append that item after its preceding element. That's it.
http://jsfiddle.net/jT8Tt/
var order = [2, 3, 1, 5, 4];
for (var i = 1; i < order.length; i++) {
$('li[data-number="' + order[i] + '"]').insertAfter($('li[data-number="' + order[i - 1] + '"]'));
}
Or in slightly more readable format
for (var i = 1; i < order.length; i++) {
var curElem = $('li[data-number="' + order[i] + '"]');
var prevElem = $('li[data-number="' + order[i - 1] + '"]');
curElem.insertAfter(prevElem);
}
A: This is going to be a bit rough since I'm not sure of your overall process but I'll give you the gist and you can implement it.
If the key is predefined...
var sort_order = ['2', '3', '1', '5', '4']
$.each(sort_order function(key,value){
// build you list here you can use the value from your sort_order
// to match the data-number and print them out in the order of your choosing.
// this will work if you dynamically create the sort_order as well.
});
The $.each function will work through the sort_order array allowing you to define an order.
A: A little late, but I'd already written this so it seems a shame to waste it:
var newOrder = ['2', '3', '1', '5', '4'],
$ul = $("ul"),
$lis = $ul.children().remove();
$.each(newOrder, function(key,val){
$ul.append($lis.filter('[data-number="' + val+ '"]'));
});
Demo: http://jsfiddle.net/zgD3n/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8767472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: add viewbag list of string to checkboxes I have a variable listSiteGroup that contains list of strings, and I put it in ViewBag
ViewBag.listSiteGroup = listSiteGroup;
how do I show each of my string to checkboxes?
I want to show it to the user like this
[ ]sitegroup 1
[ ]sitegroup 2
[ ]sitegroup 3
[ ]sitegroup 4
currently, I looped using for to each viewbag and put it in checkboxfor like the code below
@for (int i = 0; i < ViewBag.listSiteGroup.Count(); i++ )
{
@Html.CheckBoxFor(ViewBag.listSiteGroup[i].IsEnabled, new {nama=ViewBag.listSiteGroup[i].nama })
}
I'm new to asp.net mvc, I just assume this is how I access each of the viewbag
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47050838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Introduction images in android app How to make activity which shows introduction images when android app is launched for the first time?
I have 4 images that describe the app. So I want those images to show up when the app runs for the first time and user can swipe from one image to the next in order to unblock working part of the app.
A: For checking if app is lunched first time use SharedPreferences and for displaying images you have to use Bitmap, because without it you will get memory errors.
Add this code in your activity class.(Not in onCreate method)
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
After in your onCreate method check if app lunched first time and add images to imageView widget.
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (isFirstRun) {
ImageView imageView = (ImageView) findViewById(R.id.imageView);
ImageView imageView2 = (ImageView) findViewById(R.id.imageView2);
imageView.setImageBitmap(decodeSampledBitmapFromResource(getResources(),R.drawable.image1,350,350));
imageView2.setImageBitmap(decodeSampledBitmapFromResource(getResources(),R.drawable.image2,350,350));
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).commit();
}
A: Save a flag in sharedPreferences the first time you access the tutorial, then check it on launch.
If no flag:
LauncherActivity -> TutorialActivity (shows four images) save flag -> MainActivity
If flagged:
Launcher Activity -> MainActivity
Check android dev guide for sharepreferences help.
Also Im not sure what you mean about showing during installation. If you mean during loading, then just go ahead and display the images during loading?
A: This is called Appintro. Which runs first time when app launches
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
public boolean isFirstStart;
Context mcontext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread t = new Thread(new Runnable() {
@Override
public void run() {
// Intro App Initialize SharedPreferences
SharedPreferences getSharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
// Create a new boolean and preference and set it to true
isFirstStart = getSharedPreferences.getBoolean("firstStart", true);
// Check either activity or app is open very first time or not and do action
if (isFirstStart) {
// Launch application introduction screen
Intent i = new Intent(MainActivity.this, MyIntro.class);
startActivity(i);
SharedPreferences.Editor e = getSharedPreferences.edit();
e.putBoolean("firstStart", false);
e.apply();
}
}
});
t.start();
}
}
http://www.viralandroid.com/2016/10/android-appintro-slider-example.html
http://www.androidhive.info/2016/05/android-build-intro-slider-app/
https://github.com/apl-devs/AppIntro
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30601813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Crash :Critical failure: the LastResort font is unavailable in ios7 Iam inserting the contacts from the address book in to the sqlite3 database. for only some contacts my app is getting crashed at
sqlite3_finalize(statement)
this statement. and this is happening in ios7. The crash log is as follows
"Critical failure: the LastResort font is unavailable. in ios"
NSString *insertSQL = [NSString stringWithFormat:@"insert into vcards (some thing data)",(something data)];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(@"Record inserted");
}
else {
NSLog(@"Record inserted failed");
}
sqlite3_finalize(statement);
sqlite3_close(database);
please any one suggest me how to fix this crash.
A: This has nothing to do with your contacts but to do with the fonts when transitioning from ios 6 to ios 7. Delete all the fonts in your project and then carefully add one by one to your .plist testing each time before adding the next until you find the one that is causing the problem.
Have a look at this post from someone who also had the same problem as you and the person's answer.
Person have the same problem as you
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21007399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ReferenceError: Function Not Defined. What am I missing? Can't seem to figure out why I keep getting this ReferenceError: OnLoad is not defined error.
Since the time of my previous commit, I have changed lines 28-30 and that is all.
How can this cause my javascript to not be loaded properly? I have only changed these three lines. I'm certain these lines shouldn't really be related. The Javascript file is identical to the one in the previous commit.
What am I missing?
UserInterface.php - Current Commit
class UserInterface {
var $ParentAppInstance;
function __construct($AppInstance){
$this->ParentAppInstance = $AppInstance;
$this->DrawPageHTML();
$this->DrawDBSetDropdown();
$this->DrawQueryForm();
}
//Override thjis function to change the HTML and PHP of the UI page.
protected function DrawPageHTML(){
$CurrDB_Obj = $this->ParentAppInstance->CurrentDBObj; //Line 28
$EncodedFields = json_encode($CurrDB_Obj->GetFields()); //Line 29
echo "<body onload='OnLoad($EncodedFields);'>"; // Line 30
echo '
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<link rel="stylesheet" type="text/css" href="./CSS/UserInterface.css">
<div id="DebugOutput"></div>
</body>
';
}
protected function DrawDBSetDropdown(){
echo '<div align="right">';
echo '<select onchange="SwitchDatabaseSet();" name="DBSetList" form="DBSetSelector" id="DBSetSelector">';
$i = 0;
foreach ($this->ParentAppInstance->DBSetsArr as $DBSet){
if ($DBSet->DBSetName == $this->ParentAppInstance->CurrDBSetStr){
echo '<option value="' . $DBSet->DBSetName . '">' . $DBSet->DBSetName . '</option>';
}
}
foreach ($this->ParentAppInstance->DBSetsArr as $DBSet){
if ($DBSet->DBSetName == $this->ParentAppInstance->CurrDBSetStr){/* DO NOTHING. IE. IGNORE IT*/}
else if ($DBSet->DBSetName == 'DBSet0'){/* DO NOTHING. IE. IGNORE IT*/}
else{
//Add the DBSet to the dropdown list.
$i++;
echo '<option value="' . $DBSet->DBSetName . '">' . $DBSet->DBSetName . '</option>';
}
}
echo '</select>';
echo '</div>';
}
protected function DrawQueryForm(){
echo '<form action="DatabaseSearch.php" method="post" accept-charset="UTF-8">';
echo '<div id="QFormBody">';
$NumActiveQBoxes = $this->ParentAppInstance->Config['ApplicationSettings']['NumberDefaultQueryOptions'];
for ($i = 1; $i <= $NumActiveQBoxes; $i++){
echo '<div class="QueryBox" name="QBox_' . $i . '">';
echo '<select name=Field_' . $i . '">';
$DBSet_Num = filter_var($this->ParentAppInstance->CurrDBSetStr, FILTER_SANITIZE_NUMBER_INT);
$CurrDBSet_Obj = $this->ParentAppInstance->DBSetsArr[$DBSet_Num];
foreach($CurrDBSet_Obj->GetDBSetFields() as $Field){
//echo $Field;
echo '<option>' . $Field . '</option>';
}
echo '</select>';
echo '<input type="text" name="Query_' . $i . '"></input>';
echo '<button class= "RMButton" type="button">-</button>';
echo '</div>';
}
echo '<button type="button" id="add" onclick="AddQueryBox();">+</button>';
echo '<button type="submit" id="submit">SEARCH</button>';
echo '</Form>';
echo '<script src=/GLS_DBSearchProject/JavaScript/UserInterface.js></script>';
}
UserInterface.php - Previous Commit
class UserInterface {
var $ParentAppInstance;
function __construct($AppInstance){
$this->ParentAppInstance = $AppInstance;
$this->DrawPageHTML();
$this->DrawDBSetDropdown();
$this->DrawQueryForm();
}
//Override thjis function to change the HTML and PHP of the UI page.
protected function DrawPageHTML(){
$DBSet_Num = filter_var($this->ParentAppInstance->CurrDBSetStr, FILTER_SANITIZE_NUMBER_INT); //Line 28
$CurrDBSet_Obj = $this->ParentAppInstance->DBSetsArr[$DBSet_Num]; //Line 29
$EncodedFields = json_encode($CurrDBSet_Obj->GetDBSetFields()); //Line 30
echo "<body onload='OnLoad($EncodedFields);'>";
echo '
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<link rel="stylesheet" type="text/css" href="./CSS/UserInterface.css">
<div id="DebugOutput"></div>
</body>
';
}
protected function DrawDBSetDropdown(){
echo '<div align="right">';
echo '<select onchange="SwitchDatabaseSet();" name="DBSetList" form="DBSetSelector" id="DBSetSelector">';
$i = 0;
foreach ($this->ParentAppInstance->DBSetsArr as $DBSet){
if ($DBSet->DBSetName == $this->ParentAppInstance->CurrDBSetStr){
echo '<option value="' . $DBSet->DBSetName . '">' . $DBSet->DBSetName . '</option>';
}
}
foreach ($this->ParentAppInstance->DBSetsArr as $DBSet){
if ($DBSet->DBSetName == $this->ParentAppInstance->CurrDBSetStr){/* DO NOTHING. IE. IGNORE IT*/}
else if ($DBSet->DBSetName == 'DBSet0'){/* DO NOTHING. IE. IGNORE IT*/}
else{
//Add the DBSet to the dropdown list.
$i++;
echo '<option value="' . $DBSet->DBSetName . '">' . $DBSet->DBSetName . '</option>';
}
}
echo '</select>';
echo '</div>';
}
protected function DrawQueryForm(){
echo '<form action="DatabaseSearch.php" method="post" accept-charset="UTF-8">';
echo '<div id="QFormBody">';
$NumActiveQBoxes = $this->ParentAppInstance->Config['ApplicationSettings']['NumberDefaultQueryOptions'];
for ($i = 1; $i <= $NumActiveQBoxes; $i++){
echo '<div class="QueryBox" name="QBox_' . $i . '">';
echo '<select name=Field_' . $i . '">';
$DBSet_Num = filter_var($this->ParentAppInstance->CurrDBSetStr, FILTER_SANITIZE_NUMBER_INT);
$CurrDBSet_Obj = $this->ParentAppInstance->DBSetsArr[$DBSet_Num];
foreach($CurrDBSet_Obj->GetDBSetFields() as $Field){
//echo $Field;
echo '<option>' . $Field . '</option>';
}
echo '</select>';
echo '<input type="text" name="Query_' . $i . '"></input>';
echo '<button class= "RMButton" type="button">-</button>';
echo '</div>';
}
echo '<button type="button" id="add" onclick="AddQueryBox();">+</button>';
echo '<button type="submit" id="submit">SEARCH</button>';
echo '</Form>';
echo '<script src=/GLS_DBSearchProject/JavaScript/UserInterface.js></script>';
}
UserInterface.js
var DBSetFields = [];
var NumQBoxes = 3;
//window.onload = OnLoad();
function OnLoad(Fields){
console.log("OnLoad called");
CloneDBSetFields(Fields);
var RMNodeList = document.getElementsByClassName('RMButton');
for (var i = 0; i < RMNodeList.length; ++i) {
console.log(RMNodeList[i]);
RMNodeList[i].onclick = RemoveQBox; // Calling myNodeList.item(i) isn't necessary in JavaScript
}
}
function JSTEST(){
window.alert("JS Called Successfully!!");
}
function CloneDBSetFields(Fields){
console.log("CloneDBSetFields");
DBSetFields = Fields;
}
function SwitchDatabaseSet(MainPageDoc){
document.getElementById("DebugOutput").innerHTML = "Test";
window.location.replace('/GLS_DBSearchProject/index.php?DBSet=' + document.getElementById("DBSetSelector").value);
console.log(document.getElementById("DBSetSelector").value);
//console.log(document.)
}
function Fields_FOREACH(ELEMENT, INDEX, ARRAY){
console.log("TEST");
var FieldOption = document.createElement('option');
FieldOption.setAttribute('value', ARRAY[INDEX]);
FieldOption.innerHTML = ARRAY[INDEX];
this.appendChild(FieldOption);
}
function AddQueryBox(){
NumQBoxes += 1;
var NewQBox = document.createElement('div');
NewQBox.setAttribute('class', 'QueryBox');
//Create and fill Field Selector dropdown "select" element
var FieldSelector = document.createElement('select');
FieldSelector.setAttribute('name', 'Field_' + NumQBoxes);
//foreach element in Fields
console.log(DBSetFields);
DBSetFields.forEach(Fields_FOREACH, FieldSelector);
//Create and fill
var QueryText = document.createElement('input');
QueryText.setAttribute('type', 'text');
QueryText.setAttribute('name', 'Query_' + NumQBoxes);
//Create "-" Remove button for removing query lines.
var RemoveButton = document.createElement('button');
RemoveButton.innerHTML = "-";
RemoveButton.setAttribute('type', 'button');
RemoveButton.setAttribute('class', 'RMButton');
RemoveButton.addEventListener("click", RemoveQBox);
//Combine the individual elements into a new query box and insert the new query box into the HTML Document
NewQBox.appendChild(FieldSelector);
NewQBox.appendChild(QueryText);
NewQBox.appendChild(RemoveButton);
document.getElementById("QFormBody").insertBefore(NewQBox, document.getElementById("add"));
}
function RemoveQBox(e){
console.log("Remove");
var RemoveButton = this; //this == e.currentTarget
console.log(RemoveButton);
var QBox = RemoveButton.parentNode;
QBox.remove();
NumQBoxes -= 1;
}
EDIT: My Javascript file is not being loaded on the client side (ie. it doesn't show up under "Sources", so I'm not really not sure: Why wouldn't my javascript be loading on the client side?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36849244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: sql server query with a too "ORs" clauses I have a dictionary container with next info:
{ID=412, CATEG=1},
{ID=413, CATEG=2},
{ID=414, CATEG=3},
{ID=415, CATEG=4}
I need to construct a string query for execute it in SQL SERVER, something like that:
select * from PASSAGES psg
where (psg.ID = 413 AND psg.CATEGORY_ID = 2)
OR (psg.ID = 414 AND psg.CATEGORY_ID = 3)
OR (psg.ID = 415 AND psg.CATEGORY_ID = 4)
OR (psg.ID = 416 AND psg.CATEGORY_ID = 5)
The problem is that my container now have 4 elements, if it would have 200 i would have 200 ORs ??
Any idea about avoid too many ORs ? (I need a string query, i can not use a stored procedure)
thanks in advance
A: You could use a join instead, putting the values in a derived table:
select p.*
from passages p join
(values (413, 2), (414, 3), (415, 4), (416, 5)
) v(id, category_id)
on p.id = v.id and p.category_id = v.category_id;
A: If you can store that dictionary container in a table it will be easier to use it in an (IN) clause like this:
SELECT * FROM PASSAGES AS psg
JOIN Dictionary AS D ON psg.ID = D.ID
WHERE psg.ID IN (D.ID) AND psg.CATEGORY_ID IN (D.CATEG)
and as the Dictionary table records increase the query will be fixed all time without multiple (ORs).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38374861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Excel file name changed dynamically I used an excel template. In my ssis package at first the template is copied in the working directory and package execute. In the next run the excel file which is already existed in the working directory it moved into BACKUP folder and again the template file copied. It works good.
But i want to do something when i move it i want to rename it like is the previous file name is Input_01 in the next move it will input_02. How can i do this?
i am using Execute process task toolbox in SSIS pacakge.
and a .bat file is called. in the .bat file i write
move "E:\InputFolder\Input.xls" "D:\Backup"
copy "E:\Template\Input.xls" "E:\InputFolder\Input.xls"
I want a ouput in the backup folder the excel files are like
Input_01,Input_02.... what will be my command?
A: Here's how to do it with a batch file:
@echo off
set cnt=1
for /f %%f in ('dir /b "D:\Backup\Input_*.xls"') do set /a cnt+=1
if %cnt% lss 10 (move "E:\InputFolder\Input.xls" "D:\Backup\Input_0%cnt%.xls") else (move "E:\InputFolder\Input.xls" "D:\Backup\Input_%cnt%.xls")
copy "E:\Template\Input.xls" "E:\InputFolder\Input.xls"
You can have more control over your files' naming convention (not to mention deletion of old files) if you use a Script Task, though.
A: can we use a 'File system task' instead. It helps us Renaming a file. You will have to use a 'For-Each loop Container' as well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23782339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Not being able to Load Image from a function To HTML Canvas I am trying to place the screenshot image into html canvas but not being able to. I have taken screenshot of current tab by using following chrome API. Trying to make a chrome extension.
/* background.js */
let id = 100;
//calling chrome api
chrome.browserAction.onClicked.addListener(() => {
chrome.tabs.captureVisibleTab((screenshotUrl) => {
const viewTabUrl = chrome.extension.getURL('screenshot.html?id=' + id++)
let targetId = null;
//checking if the opened tab id is the same as the target id
chrome.tabs.onUpdated.addListener(function listener(tabId, changedProps) {
if (tabId != targetId || changedProps.status != "complete")
return;
chrome.tabs.onUpdated.removeListener(listener);
const views = chrome.extension.getViews();
for (let i = 0; i < views.length; i++) {
let view = views[i];
if (view.location.href == viewTabUrl) {
view.setScreenshotUrl(screenshotUrl);
return;
}
}
});
//chrome tabs create method
//no listener on create event because the tab’s URL may not be set at the time this event is fired
chrome.tabs.create({ url: viewTabUrl }, (tab) => {
targetId = tab.id;
});
});
});
But not able to call the image from the function
function setScreenshotUrl(url) {
document.getElementById('target').src = url;
};
var cnv = document.getElementById("conv");
cnv.onclick = function() {
var x = document.getElementById("target").src;
document.getElementById("demo").innerHTML = x;
};
window.addEventListener('load', function() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("target");
ctx.drawImage(img, 10, 10, 300, 175, 0, 0, 100, 175);
});
A: The problem was image was not ready at windows on load event, verified by checking the innerHTML of the image, while if I try to do the same thing in onClick event, the image is successfully loaded into canvas.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69054987",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to parse CSV that is passed as a parameter to a method I have a string that contains content of CSV file.
I need to extract those values to my objects.
I don't get CSV from CSV file I receive it as a parameter (data).
And in exmple they use file.csv to parse data.
I have tried to load it in MemoryStream but without luck.
public string methos(string data)
{
CsvFileDescription inputFileDescription = new CsvFileDescription
{
SeparatorChar = ',',
FirstLineHasColumnNames = true
};
CsvContext cc = new CsvContext();
MemoryStream mStream = new MemoryStream(System.Text.ASCIIEncoding.Default.GetBytes(data));
IEnumerable<Data datas=
cc.Read<Data>(mStream, inputFileDescription);
Also I don't know if I pick good framework to parse CSV to custom objects but to me it's important that values can have commas and that framework can handle that.
A: LINQtoCSV only takes a StreamReader, not a stream. Try this:
using (MemoryStream mStream = new MemoryStream(System.Text.ASCIIEncoding.Default.GetBytes(data)))
using (StreamReader reader = new StreamReader(mStream))
{
IEnumerable<Data> datas = cc.Read<Data>(reader, inputFileDescription);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18959797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Sort dates in Perl I need help sorting in perl. I have an array of dates in this format. DD-MMM-YY. Example 19-FEB-12.
I have spent quite a lot of time already, but couldn't get it work. I'm very new to perl as well. Any amount of help is appreciated. Thanks!!
A: An easy way is to convert the dates to YYYYMMDD format that can be sorted lexicographically.
Note that MM should be the month represented as a two digit number.
A: You could use the core module Time::Piece to convert the DD-MMM-YY (or any input format) to an ISO 8601 form. This allows simple sorting. This example builds up an array of raw data which includes the ISO value as a sort key; sorts it; and returns the data in sorted order:
#!/usr/bin/env perl
use strict;
use warnings;
use Time::Piece;
my $t;
my @data;
while (<DATA>) {
chomp;
$t = Time::Piece->strptime( $_, "%d %b %y" );
push @data, [ $t->datetime, $_ ]; #...ISO 8601 format...
}
my @sorteddata = sort { $a->[0] cmp $b->[0] } @data;
for my $value (@sorteddata) {
print $value->[1], "\n";
}
__DATA__
19 Feb 12
17 Aug 11
31 Mar 10
01 Aug 11
08 Apr 11
29 Feb 11
A: This can be done using the Time::Piece core module's strptime method to decode the dates and sorting them according to the resulting epoch seconds.
This program demonstrates the idea.
use strict;
use warnings;
use Time::Piece;
my @dates = <DATA>;
chomp @dates;
my @sorted = sort {
Time::Piece->strptime($a, '%d-%b-%y') <=> Time::Piece->strptime($b, '%d-%b-%y')
} @dates;
print "$_\n" for @sorted;
__DATA__
05-FEB-12
10-MAR-11
22-AUG-11
26-FEB-12
10-NOV-12
07-JUN-11
20-APR-12
19-DEC-12
17-JAN-11
25-NOV-11
28-FEB-11
04-SEP-11
03-DEC-12
16-SEP-12
31-DEC-11
08-JUN-11
22-JUN-12
02-AUG-12
23-SEP-11
14-MAY-11
output
17-JAN-11
28-FEB-11
10-MAR-11
14-MAY-11
07-JUN-11
08-JUN-11
22-AUG-11
04-SEP-11
23-SEP-11
25-NOV-11
31-DEC-11
05-FEB-12
26-FEB-12
20-APR-12
22-JUN-12
02-AUG-12
16-SEP-12
10-NOV-12
03-DEC-12
19-DEC-12
A: Here's a possible way to do this using only basic Perl (no modules):
#! perl -w
use strict;
my @dates = ( '19-FEB-12', '15-APR-12', '13-JAN-11' );
# map month names to numbers
my %monthnum = (
'JAN' => 1, 'FEB' => 2, 'MAR' => 3, 'APR' => 4,
'MAY' => 5, 'JUN' => 6, 'JUL' => 7, 'AUG' => 8,
'SEP' => 9, 'OCT' => 10, 'NOV' => 11, 'DEC' => 12
);
# sort the array using a helper function
my @sorted_dates = sort { convert_date($a) cmp convert_date($b) } @dates;
print join(", ", @sorted_dates), "\n";
# outputs: 13-JAN-11, 19-FEB-12, 15-APR-12
exit(0);
# THE END
# converts from 19-FEB-12 to 120219, for sorting
sub convert_date
{
my $d1 = shift;
my $d2;
if ($d1 =~ /(\d{2})-([A-Z]{3})-(\d{2})/)
{
$d2 = sprintf( "%02d%02d%2d", $3, $monthnum{$2}, $1 );
}
else
{
die "Unrecognized format: $d1";
}
return $d2;
}
This relies on your dates being formatted correctly, but it should be trivial to add more validation.
A: Using DateTime module;
or use sort command with month option (*nix);
or transform dd-mmm-yyyy to yyyymmdd and then sort;
A: Totally from scratch:
Printed Output:
Unsorted:
14-OCT-06
15-OCT-06
13-OCT-06
19-FEB-12
29-DEC-02
15-JAN-02
Sorted (Least recent to most recent):
15-JAN-02
29-DEC-02
13-OCT-06
14-OCT-06
15-OCT-06
19-FEB-12
Code:
#!C:\Perl64
#Input Strings
@inputs = ('14-OCT-06','15-OCT-06','13-OCT-06', '19-FEB-12', '29-DEC-02', '15-JAN-02');
print "Unsorted:\n";
foreach(@inputs){
print $_."\n";
}
# Hash for Month : Number
%months = ('JAN' => '01',
'FEB' => '02',
'MAR' => '03',
'APR' => '04',
'MAY' => '05',
'JUN' => '06',
'JUL' => '07',
'AUG' => '08',
'SEP' => '09',
'OCT' => '10',
'NOV' => '11',
'DEC' => '12');
# Hash for Number : Month
%revmonths = ('01'=>'JAN',
'02' => 'FEB',
'03' => 'MAR',
'04' => 'APR',
'05' => 'MAY',
'06' => 'JUN',
'07' => 'JUL',
'08' => 'AUG',
'09' => 'SEP',
'10' => 'OCT',
'11' => 'NOV',
'12' => 'DEC');
# Rearrange the order to 'Year-Month-Day'
@dates = ();
foreach(@inputs){
my @split = split('-',$_);
my @rearranged = reverse(@split);
@rearranged[1] = $months{$rearranged[1]};
push(@dates, \@rearranged);
}
# Sort based on these three fields
@sorted = sort { $a->[2] <=> $b->[2] } @dates;
@sorted = sort { $a->[1] <=> $b->[1] } @sorted;
@sorted = sort { $a->[0] <=> $b->[0] } @sorted;
# Replace Month Number with Month name
$size = @sorted;
for $counter (0..$size-1){
my $ref = $sorted[$counter];
my @array = @$ref;
my $num = $array[1];
$array[1] = $revmonths{$array[1]};
my @array = reverse(@array);
$sorted[$counter] = \@array;
}
print "\nSorted (Least recent to most recent):\n";
foreach(@sorted){
my @temp = @$_;
my $day = $temp[0];
my $month = $temp[1];
my $year = $temp[2];
print $day."-".$month."-".$year;
print "\n";
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10987507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: sort object by key by using lodash but key has lost after sorted I want to sort some Object look likes this
data = {
"imH3i4igFNxM3GL": {
"name": "Nacky",
"age": 12
},
"vuzPuZUmyT8Z5nE": {
"name": "Emmy",
"age": 20
},
"OkIPDY1nGjxlq3W": {
"name": "Nat",
"age": 20
}
}
I want to sort it by "name".
I tried to use Lodash for this problem.
_.sortBy(data, [function(o) { return o.name; }]);
but, it return me an array of objects without the keys
[
{
"name": "Emmy",
"age": 20
},
{
"name": "Nacky",
"age": 12
},
{
"name": "Nat",
"age": 20
}
]
I want it return me sorted object with key like the same
{
"vuzPuZUmyT8Z5nE": {
"name": "Emmy",
"age": 20
},
"imH3i4igFNxM3GL": {
"name": "Nacky",
"age": 12
},
"OkIPDY1nGjxlq3W": {
"name": "Nat",
"age": 20
}
}
what should I do? thanks
A: Objects in JS can't be sorted, and the order of the properties is not reliable, ie it depends on browsers' implementations. That's why _.sortBy() is converting your object into a sorted array.
I can think of 2 options to work with that.
Add the key to the objects in the array
If you just need an ordered array with the keys in the objects, so you can render a list.
var data = {
"imH3i4igFNxM3GL": {
"name": "Nacky",
"age": 12
},
"vuzPuZUmyT8Z5nE": {
"name": "Emmy",
"age": 20
},
"OkIPDY1nGjxlq3W": {
"name": "Nat",
"age": 20
}
};
var result = _(data)
.map(function(v, k) { // insert the key into the object
return _.merge({}, v, { key: k });
})
.sortBy('name') // sort by name
.value();
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Create an order array
Create an array of ordered keys, and use them when you wish to render the objects in order.
var data = {
"imH3i4igFNxM3GL": {
"name": "Nacky",
"age": 12
},
"vuzPuZUmyT8Z5nE": {
"name": "Emmy",
"age": 20
},
"OkIPDY1nGjxlq3W": {
"name": "Nat",
"age": 20
}
};
var orderArray = _(data)
.keys() // create an array of keys
.sortBy(function(key) { // sort the array using the original names
return data[key].name;
}) // sort by name
.value();
console.log('The order array', orderArray);
console.log(orderArray.map(function(k) {
return data[k];
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
A: I use something like this.
let data = {
'g34ghgj3kj': {
YOUR_KEY: 'g34ghgj3kj',
'key1': false,
'key2': false,
},
'hh334h664': {
YOUR_KEY: 'hh334h664',
'key1': true,
'key2': false,
},
//{...}
};
_.orderBy(data, ['key1', 'key2'], ['desc', 'desc']).reduce((result, value) => {
result[value.YOUR_KEY] = value;
return result;
}, {});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43852690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Error when adding parameter for reportsviewer VB.Net I am new to VB.NET and I'm trying to add a parameter for filtering a reportsviewer. When I added the Client_Name_, the following error pops up -
How can it be solved? I scoured everywhere for solutions but to no avail.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35117513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can AWS RDS be used as a MySQL host only? Is it possible to use AWS' RDS MySQL solution in tandem with my current file server host? By that, I mean, can I connect to the RDS MySQL server as I am with my hosts current database?
I've tried the AWS documentation but it seems a bit flaky in this area.
Thank you,
A: Amazon RDS is a database server, just like any other. If you start up an RDS MySQL server, you can connect to it from anything else that can connect to a MySQL server.
The difference is that you do not have direct host access to the RDS server. Meaning, you cannot SSH into it and get a command prompt.
But you can connect to it from any MySQL client, including MySQL Workbench.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38998203",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Is select N + 1 ever better than eager join? i am using nhibernate profiler and seeing a few places where it is giving me a "Select n + 1" warning.
The obvious fix is to make some upfront eager joins but it got me thinking if in certain cases its actually simpler or faster to live with Select N + 1 compared to doing joins that may be load lots of data that you never actually use.
A: Your thinking is correct. In some cases, for example, all the root entities reference one or two instances of another entity. It might be faster to do 2 or 3 small selects instead of a denormalized one (i.e. with joins)
There is a way to make this convenient in almost all cases: batch-size. If you set this attribute in both the entities and the collections to your usual page size, you'll get a constant number of small selects (one per entity type).
A: Select N+1 will become bigger and bigger problem once your application will have enough data in it.
Generally loading data is much cheaper then another trip to the data base. So if you can - you obviosly should avoid it.
As for loading additional data. If you are thinkg that you will load property values that are not going to be used you can use NHibernate 3.0 lazy loaded property feature.
So overall Select N+1 should be avoided.
A: I am not sure if you know about another option
In your mappings add
<list name="MyItems" batch-size="10">
or
<bag name="MyItems" batch-size="10">
If you have 10 Items, you only need two queries instead of 11. For 20 items, you need
three instead of 21 and so on. This will cut out about 90 percent of your queries.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4582214",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: String not storing in a structure properly typedef struct class {
char* CLASS_ID;
char* CLASS_NAME;
}
What would cause those two strings to lose their values over the course of 30-40 unrelated lines of code? (Assigned to a pointer returned from a function called getString()).
A: Perhaps getString() returns a pointer to a statically allocated buffer, whose value is overwritten each time it is called?
Maybe you're overflowing an array and corrupting your stack or heap?
Maybe you're storing a pointer to a string that was allocated on the stack and has gone out of scope?
With some more information about or code for getString(), someone could probably give you a definitive answer.
A: Well, not knowing how getString() is implemented, or any of your other code, it could be anything. That is part of the problem with C's (over)use of pointers.
My first guess would be that getString() actually returns a pointer to an internal (static) string, and thus each call obliterates the value retrieved from the last.
If you are actually using C++, then I would strongly advise you to ditch this code and use std::string instead. I bet your problem magically goes away.
A: Aside from what the other's posted here there's also that you should avoid names like class, CLASS_ID and CLASS_NAME because they are #defined in many librarys you might include in the future and debug for hours to find out what's suddenly wrong.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5278266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Create AWS cache clusters in VPC with CloudFormation I am creating an AWS stack inside a VPC using CloudFormation and need to create ElastiCache clusters on it. I have investigated and there is no support in CloudFormation to create cache clusters in VPCs.
Our "workaround" was to to create the cache cluster when some "fixed" instance (like a bastion for example) bootstrap using CloudInit and AWS AmazonElastiCacheCli tools (elasticache-create-cache-subnet-group, elasticache-create-cache-cluster). Then, when front end machines bootstrap (we are using autoscaling), they use elasticache-describe-cache-clusters to get cache cluster nodes and update configuration.
I would like to know if you have different solutions to this problem.
A: VPC support has now been added for Elasticache in Cloudformation Templates.
To launch a AWS::ElastiCache::CacheCluster in your VPC, create a AWS::ElastiCache::SubnetGroup that defines which subnet in your VPC you want Elasticache and assign it to the CacheSubnetGroupName property of AWS::ElastiCache::CacheCluster.
A: You workaround is a reasonable one (and shows that you seem to be in control of your AWS operations already).
You could improve on your custom solution eventually by means of the dedicated CustomResource type, which are special AWS CloudFormation resources that provide a way for a template developer to include resources in an AWS CloudFormation stack that are provided by a source other than Amazon Web Services. - the AWS CloudFormation Custom Resource Walkthrough provides a good overview of what this is all about, how it works and what's required to implement your own.
The benefit of using this facade for a custom resource (i.e. the Amazon ElastiCache cluster in your case) is that its entire lifecycle (create/update/delete) can be handled in a similar and controlled fashion just like any officially supported CloudFormation resource types, e.g. resource creation failures would be handled transparently from the perspective of the entire stack.
However, for the use case at hand you might actually just want to wait for official support becoming available:
*
*AWS has announced VPC support for ElastiCache in the context of the recent major Amazon EC2 Update - Virtual Private Clouds for Everyone!, which boils down to Default VPCs for (Almost) Everyone.
We want every EC2 user to be able to benefit from the advanced networking and other features of Amazon VPC that I outlined above. To enable this, starting soon, instances for new AWS customers (and existing customers launching in new Regions) will be launched into the "EC2-VPC" platform. [...]
You don’t need to create a VPC beforehand - simply launch EC2
instances or provision Elastic Load Balancers, RDS databases, or
ElastiCache clusters like you would in EC2-Classic and we’ll create a
VPC for you at no extra charge. We’ll launch your resources into that
VPC [...] [emphasis mine]
*This update sort of implies that any new services will likely be also available in VPC right away going forward (else the new EC2-VPC platform wouldn't work automatically for new customers as envisioned).
Accordingly I'd expect the CloudFormation team to follow suit and complete/amend their support for deployment to VPC going forward as well.
A: My solution for this has been to have a controller process that polls a message queue, which is subscribed to the SNS topic which I notify CloudFormation events to (click advanced in the console when you create a CloudFormation stack to send notifications to an SNS Topic).
I pass the required parameters as tags to AWS::EC2::Subnet and have the controller pick them up, when the subnet is created. I execute the set up when a AWS::CloudFormation::WaitConditionHandle is created, and use the PhysicalResourceId to cURL with PUT to satisfy a AWS::CloudFormation::WaitCondition.
It works somewhat, but doesn't handle resource deletion in ElastiCache, because there is no AWS::CloudFormation::WaitCondition analogue for stack deletion. That's a manual operation procedure wth my approach.
The CustomResource approach looks more polished, but requires an endpoint, which I don't have. If you can put together an endpoint, that looks like the way to go.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15730704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Different datatype from endpoint created a basic Api Rest service in Laravel 4.2 (the project was created in this version), and local responses me corresponding datatype (Int), but when execute endpoint from online server, receive different datatype(String) to local(Int), appreciate someone who knows the reason of this.
Local example
HERE
Online CentOs Server example
HERE
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73146518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CCButton not working completely when pressed in Cocos2D v3 iOS I have a gameplay scene, over which I add a CCNode as a child. My Game Over node has a replay CCButton in it.
The button is supposed to restart the game play scene. The problem is, when I press the "Restart" button, it goes through the lines but it doesn't perfrom replaceScene. Also it doesn't highlight when pressed. Here's my relevant code:
The code where I add the Game Over Node in my GamePlay Class (.m):
CCNode GameOver = [[GameOverNode alloc] init];
[self unscheduleAllSelectors];
[self stopAllActions];
[[OALSimpleAudio sharedInstance] stopBg];
[[CCDirector sharedDirector] stopAnimation];
[[CCDirector sharedDirector] pause];
[self addChild:GameOver z:5];
and here's the code for GameOver Class (.h):
@interface GameOverNode:CCNode {
CCButton *_aButton;
}
@property (nonatomic, retain) CCButton *aButton;
- (id)init;
- (void)ButtonPressed:(id)sender;
and Game Over (.m):
-(id)init {
if ( self = [super init] ){
CCSpriteFrame *replayFrame = [CCSpriteFrame frameWithImageNamed:@"Replay.png"];
_aButton = [CCButton buttonWithTitle:@"" spriteFrame:replayFrame];
_aButton.position = ccp(200,200);
[_aButton setTarget:self selector:@selector(ButtonPressed:)];
[self addChild:_aButton z:2];
}
return self;
}
- (void)ButtonPressed:(id)sender
{
NSLog(@"Button pressed");
CCTransition* t = [CCTransition transitionFadeWithDuration:0.4f];
t.outgoingSceneAnimated = YES;
t.incomingSceneAnimated = YES;
[[CCDirector sharedDirector] replaceScene:[GamePlayScene scene] withTransition:t];
}
The thing is, it prints out "Button pressed", also goes through the rest of the code of the method, but nothing happens.
I'll appreciate if you can let me know what I am doing wrong.
Thanks!
A: It does not work because you have paused the CCDirector. Remove the following line:
[[CCDirector sharedDirector] pause];
Alternatively if you really need that, resume the director before you attempt to replace the scene.
[[CCDirector sharedDirector] resume];
[[CCDirector sharedDirector] replaceScene:[GamePlayScene scene] withTransition:t];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23323511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Actionscript 2.0 How to get keyPress working for number 1 I'm trying to get on (keyPress "<1>") working for my calculator so when I press one, the number one appears in the text box.
But there is no keyPress "<1>" for the number one, I heard there is something called KeyCode is needed, and I found the keycode for 1 is "49".
Can someone write the keyPress for the number 1?
A: Use the Key event listener.
var key:Object = {
onKeyDown:function() {
switch(Key.getCode()) {
case 49:
trace('key 1 is down');
break;
case 50:
trace('key 2 is down');
break;
}
}
};
Key.addListener(key);
Then you can handle actions in the switch statement.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18908744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: p5 - Syntax error: expected ; but got hour I have the following code:
function setup() {
createCanvas(500, 500);
angleMode(DEGREES);
}
function draw() {
background(0);
translate(width/2, height/2);
let hour = hour();
}
I get an error on let hour = hour(); saying that there was supposed to be a semicolon there instead of hour. The only way I have found to fix the problem is by writing it as let; hour = hour(); This gets rid of the error but then the code doesn't run properly. Any ideas?
A: In JavaScript, variables and functions can't have the same name. (More confusingly: functions are variables!)
So that means that this line:
let hour = hour();
Is not allowed, because you're trying to reassign the hour variable from being a function to being a value. (This is a side effect of using let. If you had used var then this would have silently did the wrong thing.)
To fix the problem, just rename your variable to something that's not already a function.
let myHour = hour();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48393329",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Syntax highlighting using RSyntaxTextArea library in java netbeans swing Text is highlighted for java syntax when i am doing it in a seperate class i.e.
TextEditorDemo , but not getting the same result when i am executing the code in
action listener of a JCombo Box in swing and initialising the JtextArea msg1 (here) with the rsyntaxtextarea object -> syntax is not being highlighted.
TextEditorDemo.java
import javax.swing.*;
import org.fife.ui.rtextarea.*;
import org.fife.ui.rsyntaxtextarea.*;
/**
* A simple example showing how to use RSyntaxTextArea to add Java syntax
* highlighting to a Swing application.<p>
*/
public class TextEditorDemo extends JFrame {
public TextEditorDemo() {
JPanel cp = new JPanel();
RSyntaxTextArea syntaxTextArea = new RSyntaxTextArea(20, 60);
syntaxTextArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA);
// No other property of RSyntaxTextArea is allowed to use
// You can now modify textArea object similar to any other JTextArea object to add other functionality
JTextArea textArea = syntaxTextArea;
JScrollPane sp = new JScrollPane(textArea);
cp.add(sp);
setContentPane(cp);
setTitle("Text Editor Demo");
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args) {
// Start all Swing applications on the EDT.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TextEditorDemo().setVisible(true);
}
});
}
}
action listener for JComboBox -
private void language1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
RSyntaxTextArea syntaxTextArea = new RSyntaxTextArea(6, 20);
String lang = (String) language1.getSelectedItem();
syntaxTextArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA);
msg1 = syntaxTextArea;
msg1.setVisible(true);
System.out.println("language "+lang);
if (lang.equals("JAVA")) {
syntaxTextArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA);
}
else if(lang.equals("C")){
syntaxTextArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_C);
}
else if(lang.equals("CSHARP")){
syntaxTextArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_CSHARP);
}
else if(lang.equals("CSS")){
syntaxTextArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_CSS);
}
//syntaxTextArea.setCodeFoldingEnabled(true);*/
}
A: private void language1ActionPerformed(java.awt.event.ActionEvent evt) {
RSyntaxTextArea syntaxTextArea = new RSyntaxTextArea(6, 20);
String lang = (String) language1.getSelectedItem();
syntaxTextArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA);
msg1 = syntaxTextArea;
msg1.setVisible(true);
The above code does nothing. You haven't actually added the syntax area component to the frame.
Don't create a new RSyntaxArea object!
Instead you need to make the syntaxTextArea an instance variable in your class then you can reference the variable from the listener and just change the editing style property.
Or if for some reason the class doesn't allow you to dynamically change the property, then you will need to use:
sp.setViewportView(syntaxTextArea);
in you listener code. In which case the scrollpane variable will now need to be an instance variable in your class.
Either way you will need to create an instance variable that can be referenced from your ActionListener so you will need to restructure your code. Read the Swing tutorial on How to Use Text Areas. The demo code there will show you how to better structure your classes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46608019",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: For loop variable is empty in gmake I have a list of header files created thus:
expand=$(1)/$(1).h
HDRS=$(foreach x, $(DIRS), $(call expand,$(x)))
Which yields a list like a/a.h b/b.h ...
but when I use this in a for loop:
for i in $(HDRS) ; do \
echo $$i \
cp $$i $(some_dir) \
done
$$i is empty. And the cp fails, having only one argument.
The usual variants of $$i ( $i, $$i, $(i), ${i} ), don't change anything, nor do the usual variants of $(HDRS) ("$(HDRS)", etc.).
gmake echos the for-loop as
for i in a.h b.h ; \
do \
echo $i \
cp $i somedir \
done
Which looks correct.
But the implicit bash shell emits an error "/bin/sh -c: line 5: syntax error: unexpected end of file"
gmake then exits due to the failed command.
A: Due to the \, make emits the recipe as a single line. This confuses the shell. Try this instead, using ; in place of the line terminator:
for i in a.h b.h ; \
do \
echo $i ; \
cp $i somedir ; \
done
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51105808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Meteor.js: Understanding sort parameters within a find{} method I am doing exercises in the book "Getting Started With Meteor.js Javascript Framework" and
there is a section where a template called categories is created, then a {#each} loop thumbs through a collection.This is done with the intent of printing the results to the screen. This works and the code is below.
<template name ="categories">
<div class ="title">my stuff</div>
<div id='categories'>
{{#each lists}}
<div id="category">
{{Category}}
</div>
{{/each}}
</div>
</template>
My question is this:
In the code below the sort parameter doesn't seem to do anything. I am curious what it is supposed to be doing. I understand that theoretically it's suppose to "sort", but when I play with the parameters nothing changes. I looked it up in the meteor documentation and I couldn't figure it out. I am trying to modify the code so that it so that it sorts in a different order. This way I can see results and get a real understanding of how {sort: works. I tried modifying the {sort: {Category: 1}}) to {sort: {Category: -1}}) as well as {sort: {Category: 2}}) and it's always the same result.
Template.categories.lists = function() {
return lists.find({}, {sort: {Category: 1}}); // Works
/* return lists.find({}); */ // Works just the same
}
The Collections are as follows:
lists.insert({Category:"DVDs", items: [{Name:"Mission Impossible" ,Owner:"me",LentTo:"Alice"}]});
lists.insert({Category:"Tools", items: [{Name:"Linear Compression Wrench",Owner:"me",LentTo: "STEVE"}]});
A: In your code, you can attempt to change the argument of the sort to be an array instead of an object, like this:
sort: [["Category","asc"],["another argument","desc"],[...]]
so the code :
Template.categories.lists = function() {
return lists.find({}, {
sort: [
["Category", "asc"],
["another argument", "desc"],
[...]
]
});
// return lists.find({}); // Works just the same
}
A: As per my understanding that is because default is to sort by natural order. More info can be found at this link
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15180519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Magento 2 : How to setup an option for customers to buy one year free shipping? I`m a beginner in Magento 2. I did setup a shopping cart app with flat rate shipping. But now client wants to add a link in cart for buying premium membership, so that this particular users can shop without shipping charges for one year. Normal users will have to pay shipping charges as usual. Any idea on how to implement this?
A: You can make a Customer Group.
Stores > Other Setting and select Customer Group.
Add new customer group.
Go To Cart Rule please follow.
Marketing > Select Cart Price Rule > Add New Rule. now without using coupon and select free shipping in magento for that customer group .
Thanks
A: Easiest thing comes to my mind is Coupon code that he'll use everytime, with 1-year validity.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45211294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL Generate a table of multiple top X records, where top # comes from another table I'm using SQL Server 2012.
I need to generate an output that includes the results for multiple "top" queries, where the # of "top" rows returned in each query varies based on the value in another table.
My first table, call it Table1, is the reference table where NUMBER tells me how many top rows I need to return from another table for each unique MARKET/MEASURE.
MARKET MEASURE NUMBER
------ ------- ------
MarketA MeasureA 411
MarketA MeasureB 396
MarketB MeasureA 548
MarketB MeasureC 424
MarketC MeasureC 411
The second table, Table2, lists detail for each individual person in a given MARKET/MEASURE, where the combination of MARKET and MEASURE is my primary key. There are many entries for any given MARKET/MEASURE.
MARKET MEASURE LASTNAME COMPLIANT
------ ------- -------- ---------
MarketA MeasureA Coppola Y
MarketA MeasureA Winterbottom N
MarketA MeasureB Scorsese Y
MarketC MeasureC Tarr Y
For each value in Table1, I need to return that many top rows from Table2 based on a sort of LASTNAME in ascending order. So for example, because Table1 has a NUMBER of 411 for MarketA/MeasureA, my output needs to contain the TOP 411 * rows from Table2 (based on all persons in that market sorted by LASTNAME ascending), and the TOP 396 rows for MarketA/MeasureB, and then the TOP 548 rows for MarketB/MeasureA, and so on, all in one table, as if I've "UNIONed" (?) each query individually.
How do I do this dynamically without having to UNION individual queries for each MARKET/MEASURE in Table1 (of which there are over 1000)?
I feel like the answer is to use a select expression to generate # in the TOP expression, like.....
select TOP (select NUMBER from TABLE2) *
from TABLE1 t1
inner join TABLE2 t2 on t2.MARKET = T1.MARKET
and t2.MEASURE = T2.MEASURE
...but obviously I'm missing a few steps because the TOP expression will bring back multiple values from TABLE2, and I can't quite figure out how to get it to "run" for each MARKET/MEASURE combination.
Help much appreciated.
A: This is what APPLY can be used for
SELECT
*
FROM
Table1
CROSS APPLY
(
SELECT TOP (Table1.Number)
*
FROM
Table2
WHERE
Table1.Market = Table2.Market
AND Table1.Measure = Table2.Measure
ORDER BY
LastName
) AS TopResults
http://sqlfiddle.com/#!6/46b57/4
A: For anyone in the same predicament, I figured out another way of accomplishing the same thing, using the ROW_NUMBER() windowed function instead of trying to use TOP dynamically. The idea was to add a row number to Table2, partitioned by market & measure and ordered by last name, then to join the Table1.Number to Table2, and select only rows where the row number was less than Table1.Number, thus returning the "top" number of rows according to the Table1.Number.
with temp as (select 'rownum' = row_number() over(partition by t2.market, t2.measure)
order by t2.lastname)
, t2.*
, t1.number
from table2 t2
inner join table1 t1 on t1.market = t2.market
and t1.measure = t2.measure)
select *
from temp
where rownum <= number
order by market, measure, rownum
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36508175",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: use where clause to search from a substring SQL Server Hi I have column which contains below values:
names
-----------------
johnDoeKing
Joseph
MaxSecond
Plank
-----------------
Now I have an input string:
johnDoeMaxAlexPaul
is there a way I can use where clause which will return JohnDoeKing and MaxSecond from my column when I search with this input string in where clause ?
A: Yes, you can use LIKE:
DECLARE @InputString VARCHAR(100) = 'johnDoeMaxAlexPaul';
SELECT *
FROM dbo.YourTable
WHERE @InputString LIKE '%' + names + '%';
Here is a live demo of this, and the results are:
╔═════════╗
║ names ║
╠═════════╣
║ johnDoe ║
║ Max ║
╚═════════╝
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47983391",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Swipe To Push View Controller Like Whatsapp messages details i want to ask what is the best way we need to work when we want to pan a view to push view controller, we want to make something similar like whatsapp messages status view like the following photo
we try swipe gesture and also pan gesture but we want to make same animation like what happen on whatsapp
so please can you help me?
waiting your responses
thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68609089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.