text
stringlengths 0
13M
|
---|
Title: Keep application state on android
Tags: android
Question: I am having trouble saving the state/singleton of my application.
When the application starts a loading screen (activity) is shown and a singleton is initialized with values from a webservice call (note that network access cannot run on the main thread).
After the singleton is created I open my main activity. Note that values from the singleton are required to build the layout.
Now assume the app goes in the background and is killed there (e.g. because of low memory). My singleton instance is deleted as the app is killed. When I switch back to my app it tries to recreate the main activity. As I mentioned earlier the values from the singleton are required to build the layout, so this leads to a NullPointerException (when I try to access members of the singleton, as it is not there anymore).
Can I somehow tell android to start the first loading activity after the app was killed? It would be great if I could refresh the singleton before the layout is recreated, but this seems to be a problem as network calls can not be on the main thread and therefore not block until the refresh is finished.
I assume that I could save the singleton in all activities onStop and recreate it in the onCreate methods, but this seems a bit too unpredictable and would probably lead to a inconsistent state...
Another way could be to just always finish my activity onStop, but this would lead to losing on which tab the user last and so on, even if the app is not killed, so this is not a good option.
Any ideas on how to solve this?
Comment: Show code or at least code snippets. Also show the logcat for the 'crash' - we can't really if all you say is "...leads to a crash...".
Comment: The problem is not the crash, the problem is that the singleton object is null as the app was killed in the background and when I switch back to it it tries to load the last activity, which has to access the singleton to create its layout.
Here is the accepted answer: Why not just use a SharedPreferences instead of a singleton?
Anytime you want to save some global state, commit it to preferences. Anytime you want to read the global state, read it back from preferences.
Then you don't have to concern yourself with application lifecycle at all, as your data will always be preserved regardless of what the phone is doing.
Comment for this answer: SharedPreferences is not universal utility. In my case I have 100k strctured data and images. To save/load via SharedPreferences is not goos idea - I tried, but loading takes 10 seconds.
Comment for this answer: This will definitely do, I will evaluate this tomorrow and give feedback if it works for me :) I really like the idea of not having to deal with the application lifecycle
Here is another answer: For something like that I used a pseudo singelton object as a Application class. This object will be created on the beginning and will be in the memory. But note that the system will terminate the application if the memory is needed by other applications. However this object is persitent even if all activities are temporally terminated.
To use that you need to declare that in your android manifest like here:
```<application android:label="@string/app_name"
android:icon="@drawable/icon"
android:description="@string/desc"
android:name=".MySingeltonClass"
...
```
Here is a code example:
```public abstract class MySingeltonClass extends Application {
// ...
public void informClientOnline() {
clientOnline=true;
Log.v(LOG_TAG, "Client is online!");
}
public void informClientShutdown() {
clientOnline=false;
Log.v(LOG_TAG, "Client is going offline. Waiting for restart...");
Timer t=new Timer("shutdowntimer", false);
t.schedule(new TimerTask() {
@Override
public void run() {
if(!clientOnline) {
Log.v(LOG_TAG, "Client has not restartet! Shutting down framework.");
shutdown();
System.exit(0);
}
}
}, 5000);
}
}
```
this two functions are called like this:
```((MySingeltonClass)getApplicationContext()).informClientOnline();
```
Comment for this answer: My solution was to call on oncreate a *here am i* method and a *good by* method in ondestroy... I'll add an example.
Comment for this answer: The application object will exists even if temporally all activities are closed. That is why I check that manually and save than all custom states in my `shutdown()` method.
Comment for this answer: I call the methods `informClientOnline()` and `informClientOnline()` in every activity in `oncreate`/`ondestroy`. So it's simple to know that. If the last activity is destroyed you know that you have to save your state before your app will be terminated. How every I think it is a much better design to use contentproviders and sync services. But that is really a heavy topic.
Comment for this answer: The "system will terminate" part is exactly my problem, as I need a way to recreate the object after that.
Comment for this answer: Thank you, however I do not see how this helps restore my singleton (ok, I guess you mean my singleton should just be this application object. Now mind the part that the data has to be filled with a webservice call. The application will be closed, reopened, the Application object will be created, I can schedule my webservice call, but then my activity is opened and the call is not finished, I get a bad layout).
Comment for this answer: How do you check manually and save anything if you are not informed that the app is killed? Maybe I do not get something or something is still missing...
Comment for this answer: This will not work, as onDestroy will not even be called. Look at the Activity Lifecycle: The app goes to the background, onStop() is called. Now the app is killed, so the onDestroy will not even be called then, so you cannot know for sure when the app or an activity is terminated.
Here is another answer: You could save your Singleton when ```onSaveInstanceState()``` in the Activity gets called. All you need to do is to make it implement ```Parcelable``` (it's Androids own form of serialization), then you can put it in the ```outState``` ```Bundle``` in ```onSaveInstanceState()``` which will allow you to retrieve it laver in ```onCreate()``` or ```onRestoreInstanceState()``` in the Activity, whichever you like.
I've included an example for you:
```public class TestActivity extends Activity {
private MySingleton singleton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState.containsKey("singleton")) {
singleton = savedInstanceState.getParcelable("singleton");
} else {
singleton = MySingleton.getInstance(5);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("singleton", singleton);
}
public static class MySingleton implements Parcelable {
private static MySingleton instance;
private int myData;
private MySingleton(int data) {
myData = data;
}
public static MySingleton getInstance(int initdata) {
if(instance == null) {
instance = new MySingleton(initdata);
}
return instance;
}
public static final Parcelable.Creator<MySingleton> CREATOR = new Creator<TestActivity.MySingleton>() {
@Override
public MySingleton[] newArray(int size) {
return new MySingleton[size];
}
@Override
public MySingleton createFromParcel(Parcel source) {
return new MySingleton(source.readInt());
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeInt(myData);
}
}
}
```
Comment for this answer: Then what will happen with more than one activity? I guess the singleton would be saved/serialized independently (with possibly different values) and with every onCreate I change my singleton to something different again (which leads to a inconsistent state)
Comment for this answer: Yes, but if I serialize my singleton I kind of "freeze" it, right? Now assume one activity opens an activity that is only open for a short time (like a dialog). After this dialog-kind activity is closed it saves its state, right? Now ten minutes later the main activity saves its state (so the state 10 minute later). After the app is killed and comes back to life the main activity will restore the singleton. But when the dialog comes back it will resore the 10min earlier state, isn't that right?
Comment for this answer: Your singleton cannot be in a different state in each activity if it's a true singleton. It's the same object everywhere, that's why it's a singleton :)
Comment for this answer: Okay sure I see your problem. You could do some sort of serialization (Parcelable doesn't support writing the object to disk) that always saves the object to the same file. Then when your activity is re-created you check if an instance of your singleton exists (something like a `isInstanceAvailable` boolean method in your singleton), if it is, then you grab it, if it isn't then you re-create it from the object stored on disk. But this may be a somewhat inelegant solution to your problem (serialization is reportedly slow on Android), and I must admit I'm not an expert on this subject :)
|
Title: How to check, if a canvas element has been tainted?
Tags: javascript;html5-canvas;cors
Question: Basic scenario
I'm loading several images on the client side. Some of them are from another domain, some are not. Some I may be able to access using the ```crossOrigin``` attribute, some not.
The basic requirement is to retrieve a dataURL for the images where possible.
Question
After drawing the image to the canvas element (which I need to to to get a dataURL, right?), how can I check, without a ```try ... catch``` block, whether the canvas has been tainted? If the canvas is tainted, I can't use ```toDataURL()``` anymore (see MDN).
```var image = new Image(),
canvas = document.createElement( 'canvas' ),
context = canvas.getContext( '2d' );
image.onload = function(){
// adjust dimensions of canvas
canvas.width = image.width;
canvas.height = image.height;
// insert image
context.drawImage( image, 0, 0 );
// how to check here?
// get dataurl
dataurl = tmpCanvas.toDataURL();
// do stuff with the dataurl
};
image.src = src; // some cross origin image
```
Comment: @monsur that is internal for the browser (the specs are for browser implementers).
Comment: This is a great question. I don't know of any way other than try/catch. But if you have a reference to the `image` variable, you could call `image.crossOrigin`. Expanding on this idea, you could create a global object that maps images to their corresponding crossOrigin variable. Checking if the image is tainted would then be a matter of iterating over the object and see what the crossOrigin values are.
Comment: Also, it looks like canvas contexts have an internal `origin-clean` variable:
http://www.w3.org/TR/html5/scripting-1.html#concept-canvas-origin-clean
but as far as i can tell, this isn't exposed to the user.
Comment: @Cryptoburner Yup, that is true. But the discussion below indicates a good need for this property. It is something that should be brought up in the HTML5 spec.
Here is another answer: Here is a solution that doesn't add properties to native objects:
```function isTainted(ctx) {
try {
var pixel = ctx.getImageData(0, 0, 1, 1);
return false;
} catch(err) {
return (err.code === 18);
}
}
```
Now simply check by doing this:
```if (isTainted(ctx)) alert('Sorry, canvas is tainted!');
```
Edit: NOW i see you wanted a solution without try-catch. Though, this is the proper way to check as there is no origin clean flag exposed to user (it's for internal use only). Adding properties to native object is not recommended.
Comment for this answer: @markE yes, it's dynamically (one reason why we love it!) but with our own objects ;) It does most likely no harm whatsoever in this case but in general it's considered bad practice if it can be solved other ways (which it can in this case).
Comment for this answer: @markE I don't mind changing objects if needed. My point is if "*you know what you're doing*" there's no problem. However, there will be beginners reading the posts and I think it's wise not to give the impression that it's a fully OK practice as experience has shown that it isn't (if you *don't* know what you're doing). It's better to be on the safe-side in places like SO IMO & when users are experienced enough they'll figure out what is and isn't good to do. But I didn't intend to start any discussion - it was meant as an advice which I think is a good advice. jQuery is btw a special case.
Comment for this answer: Yep, since CORS errors are fatal this quick if-else test fails also :-(. I agree there should be an exposed flag to indicate a tainted canvas. Even thought the question explicitly asks not, I would probably use try-catch here also. After all the questioner is not trying to smooth over errors created by poor coding. He’s just trying to determine the state of the canvas.
Comment for this answer: **Jumping on my soapbox** ;-) I would better say "modifying the functionality of existing properties of a native object is not recommended." IMHO, the nature of javascript is an open prototypical language that encourages you create and extend objects. That’s my 2-cents ;)
Comment for this answer: **Again on soapbox :-)** Adding (not replacing) properties / methods on native objects is common. Even John Resig (creator of jQuery!) extends native objects (example: http://ejohn.org/blog/fast-javascript-maxmin/) Certainly, if adding properties is not to your liking, you can encapsulate the native object into your own object and extend your own object. Or just create an array that holds which images are tainted. Lots of workarounds to suite every programmers style! Anyway, SO's auto-moderator will get mad at us for this discussion--but it's been fun discussing with you! :-)
Comment for this answer: We just have different philosophies about adding properties to make native objects useful. I respect your philosophy :)
Comment for this answer: Adding properties to native objects is widely considered bad practice because it blacklists property names that future versions of JavaScript can use without breaking (widespread) libraries. Just search `smooshMap` for an example.
Here is another answer: Here's an indirect test for CORS tainting that doesn't use try-catch:
A Demo: http://jsfiddle.net/m1erickson/uDt2K/
It works by setting a ```image.tainted=true``` flag before loading the image
Then in image.onload, ```context.getImageData``` triggers/doesn't trigger a CORS violation.
If no violation occurs, then the tainted flag is set to false (```image.tainted=false```).
```var img=new Image();
// set a "tainted flag to the image to true (initialize as tainted)
img.tainted=true;
img.onload=function(){
// try an action that triggers CORS security
var i=ctx.getImageData(1,1,1,1);
// if we don't get here, we violated CORS and "tainted" remains true
// if we get here, CORS is happy so set the "tainted" flag to false
img.tainted=false;
};
// test with tainted image
img.src="http://pp-group.co.uk/wp/wp-content/uploads/2013/10/house-illustration-web.gif";
```
Since image.onload is asynchronous, your code outside image.onload will still execute even after a CORS violation.
Here's example code that:
creates an image object
tests if the image is CORS compliant
executes one callback if the image is compliant
executes another callback if the image is not compliant
Example Code:
```<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
// known CORS violator
var src1="http://pp-group.co.uk/wp/wp-content/uploads/2013/10/house-illustration-web.gif";
// known CORS compliant
var src2="https://dl.dropboxusercontent.com/u/139992952/houseIcon.png";
// callbacks depending on if the image causes tainted canvas
function tainted(img){console.log("tainted:",img.src);}
function notTainted(img){console.log("not tainted:",img.src);}
// testing
var image1=newImage(src1,tainted,notTainted);
var image2=newImage(src2,tainted,notTainted);
function newImage(src,callWhenTainted,callWhenNotTainted){
// tmpCanvas to test CORS
var tmpCanvas=document.createElement("canvas");
var tmpCtx=tmpCanvas.getContext("2d");
// tmpCanvas just tests CORS, so make it 1x1px
tmpCanvas.width=tmpCanvas.height=1;
var img=new Image();
// set the cross origin flag (and cross our fingers!)
img.crossOrigin="anonymous";
img.onload=function(){
// add a tainted property to the image
// (initialize it to true--is tainted)
img.tainted=true;
// draw the img on the temp canvas
tmpCtx.drawImage(img,0,0);
// just in case this onload stops on a CORS error...
// set a timer to call afterOnLoad shortly
setTimeout(function(){
afterOnLoad(img,callWhenTainted,callWhenNotTainted);
},1000); // you can probably use less than 1000ms
// try to violate CORS
var i=tmpCtx.getImageData(1,1,1,1);
// if we get here, CORS is OK so set tainted=false
img.tainted=false;
};
img.src=src;
return(img);
}
// called from image.onload
// at this point the img.tainted flag is correct
function afterOnLoad(img,callWhenTainted,callWhenOK){
if(img.tainted){
// it's tainted
callWhenTainted(img);
}else{
// it's OK, do dataURL stuff
callWhenOK(img);
}
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=360 height=281></canvas>
</body>
</html>
```
Comment for this answer: Just in case it was not clear to readers, this is still throwing an uncaught error, it is just ignored by synchronous code because it throws in the asynchronous flow. In some environments uncaught asynchronous exceptions will halt the program (and you should catch them regardless).
|
Title: How to save emails from Thunderbird as .eml
Tags: email;thunderbird
Question: Thunderbird officially supports the format .eml-file but I am not able to save mails into this format. Please advise how to do this.
Here is another answer: You have to:
first save the email you are writing, as a draft
then go to the drafts folder, right click on your email > Save as... > choose .eml file type and save
I don't know why Thunderbird obliges us to this workaround.
Here is another answer: Yes
```
Displays a 'Save Message As' dialog where you can select a location on
your local disks or network to save a copy of the message you are
currently reading. You can save as .eml, .html, or .txt file types. In
the Windows version, select these under 'Save as type:', in the Linux
version change the default extension of '.eml' to either '.html' or
'.txt' if you wish to save it in one of these other formats. (Note,
the only way to open a '.eml' format file in the Linux version is to
use the File > Open Saved Message menu selection.)
```
Source
Comment for this answer: many thanks - i will do all you advice. greetings
|
Title: Please help in converting time zone using powershell when source time is property of an element
Tags: powershell;time;timezone
Question: Somebody please help me in converting the time zone as said in the description.
A little explanation on code will be great help in understanding the concept.
Thanks in advance!
```PS> Get-HotFix -id KB4537572 | select InstalledOn
InstalledOn
-----------
3/4/2020 12:00:00 AM
PS> $from = (Get-HotFix -id KB4537572 | select InstalledOn)
PS> $from
InstalledOn
-----------
3/4/2020 12:00:00 AM
PS> $to = 'Central Europe Standard Time'
PS> [System.TimeZoneInfo]181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16onvertTimeBySystemTimeZoneId( $from , $to )
Cannot find an overload for "ConvertTimeBySystemTimeZoneId" and the argument count: "2".
At line:1 char:1
+ [System.TimeZoneInfo]181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16onvertTimeBySystemTimeZoneId( $from , $to )
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
```
Comment: In short: [`Select-Object`](https://docs.microsoft.com/powershell/module/microsoft.powershell.utility/select-object) (`select`) returns _a `[pscustomobject]` instance_ that has the _requested properties_ - even when you're only asking for a _single_ property. To get only that property's _value_, use `-ExpandProperty ` instead - see the [linked answer](https://stackoverflow.com/a/48809321/45375) for details and alternatives.
|
Title: What is "crossflow compression"?
Tags: compression;wan
Question: I came across the term "crossflow compression" several times while reading about WAN optimization techniques. The only elaboration I've seen is that it refers to "compression across various flows", which wasn't very helpful.
Can anyone give an example of what "crossflow compression" is?
Comment: Yes, that was the website I found that refers to "compression across various flows". Thanks for your reply, though!
Comment: Perhaps the explanation given in http://www.bcs.org/content/ConWebDoc/6849 (Section Compression) will give you a hint.
Here is the accepted answer: Basically a flow is a set of packets out of a stream that have something in common.
It's easy to determine flows with protocols like TCP that have sequence numbers, specifically tag packets with them, and are connection oriented.
UDP based protocols require the WAN accelerator to work harder since nothing "built-in" is keeping track of the flow.
Let's say you are caling someone using a UDP-based VoIP protocol, to a remote office bridged by two WAN accelerators, and the line is silent for 20 seconds. So, during this time, your VoIP protocol is basically transmitting a flow of empty VoIP packets - with a header and other overhead. Crossflow compression sounds like it would be able to recognize this flow, and compress accordingly (perhaps instead of a whole UDP packet containing data representing no sound, it just sends a single byte representing that packet - the "flow" comes into play where the WAN accelerator knows this byte "stands for" data in your VoIP call.)
The VoIP example is likely not the best but hopefully you get the general idea.
Comment for this answer: In this case, would the compression still be applied packet by packet, or across the entire flow, i.e. multiple packets at once? If the former, why call it "crossflow compression"? What's the difference between "crossflow compression" and "regular" compression, which I assume is applied on a packet-by-packet basis?
Comment for this answer: Hmm... It's starting to make more sense now. Thank you for the explanation!
Comment for this answer: Across the entire flow. That's why it's called "crossflow." So the WAN accelerator may receive multiple packets comprising the flow, but not actually transmit that many packets to the other WAN accelerator on the other side. Standard compression would be per-packet. Probably a better example would be a file transfer - if WAN accelerators A and B had enough cache and the algorithms were intelligent enough, it may "crossflow compress" an entire potential sequence of SMB packets into a simple packet telling the other WAN accelerator that a particular system on that end wants a cached file.
|
Title: Write multiple laravel query at once
Tags: laravel
Question: im new to laravel, I just want to know if there's any way to efficiently rewrite this code?
```$answer1 = SurveyAnswer181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16where('answer_1','=','1')->get()->count();
$answer2 = SurveyAnswer181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16where('answer_1','=','2')->get()->count();
$answer3 = SurveyAnswer181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16where('answer_1','=','3')->get()->count();
$answer4 = SurveyAnswer181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16where('answer_1','=','4')->get()->count();
$answer5 = SurveyAnswer181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16where('answer_1','=','5')->get()->count();
```
Comment: Hi, thanks for the answers, both worked. Im sorry if my question was incomplete. But what im trying to do is to count specific data in my table and display it in a page. I have 20 queries from different questions. Each questions have 5 answers. I want to count how many of each answers were recorded. I just want to know if there's better way to do it so that I won't have to write the same lines of codes 20 times. Thank you so much for your time.
Here is another answer: Get the data first:
```$answers = SurveyAnswer181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16whereIn('answer_1', [1, 2, 3, 4, 5])->get();
```
Then count answers using loaded collection:
```$answer1 = $answers->where('answer_1', 1)->count();
$answer2 = $answers->where('answer_1', 2)->count();
...
```
This code will generate just one DB query instead of five.
Here is another answer: You can easily do it with an agregate function with a case expression, since mysql doesnot support native pivoting functions
Following is a sample, and try to rewrite according to your requirement and runt it against database directly, if it works, then you can use it with laravel raw sql.
``` select id,
sum(case when value = 1 then 1 else 0 end) ANSWER1_COUNT,
sum(case when value = 2 then 1 else 0 end) ANSWER2_COUNT
from survey
group by answer
```
Here is another answer: Try this:
```$matches = [1,2,3,4,5];
$answer = SurveyAnswer181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16whereId('answer_1', $matches)->groupBy('answer_1')->get();
```
|
Title: How to prevent screen from terminating once process ends
Tags: bash;gnu-screen
Question: I'm launching a process in a named screen like:
```screen -dmS myscreen bash -c "export VAR=123; cd /usr/local/myproject; ./myscript.py"
```
However, after a few minutes, my script crashes and when it exits the screen terminates so I can't see the debugging output. My script runs long enough so I can manually attach to the screen, but the screen still auto-terminates kicking me out of it.
How do I stop the screen from exiting when the process it's running stops?
Here is another answer: You can pipe the output to ```less``` or a file with ```tee``` and then to ```less```, or just add a "pause" command like ```sleep 99999``` after the command.
```screen -dmS myscreen bash -c "export VAR=123; cd /usr/local/myproject; ./myscript.py; sleep 9999"
```
In any case i recommend switching from ```screen``` to ```tmux```, and you can use this question to learn how to run a command and leave it after it exit.
basically you can add ```bash -i``` to the end of your command.
```tmux start-server
tmux new-session -d
tmux new-window 'ls;bash -i'
```
or you can use the this option ```remain-on-exit```
```
set-remain-on-exit [on | off]
When this option is true, windows in which the running program has
exited do not close, instead remaining open but inactivate.
```
Comment for this answer: This seems like an unreliable hack. If I create the screen manually and detach, it doesn't terminate. What's the difference between that and the screen I create without attaching?
Here is another answer: By default, ```screen``` exits when the command it is running closes, as you've observed. When you start ```screen``` by itself, the command it runs is an interactive shell, which of course doesn't exit when its children do.
If you want to be able to achieve something like this from another script, you could do
```screen -dm -S myscreen
screen -S myscreen -X stuff "export VAR=123; cd /usr/local/myproject^M"
screen -S myscreen -X stuff "./myscript.py && exit^M"
```
This first starts a new screen which will have a login shell running in it and will not close until the login shell exits. You then use ```screen```'s ```stuff``` command to input text into that shell. On the first line, we define the variables and change directory. On the second line, we start the script, and then exit the shell (assuming here that you want to close the screen session if the script succeeds). However, due to the short-circuit and (```&&```), if ```myscript.py``` fails, the ```exit``` will never happen, and you'll be free to reconnect to the screen session and see what happened.
Note that to input the ```^M``` properly, you need to type ```^V``` (control-v) followed by ```^M``` (which is the same as your enter key).
Comment for this answer: how can I type ^M in nano ?
Comment for this answer: the answer was to use vim :D which in insert mode, allows ctrl+V ctrl+M
Comment for this answer: I think `^M` can be replaced with `\n` or `\r`.
|
Title: Desktop Environment Screen Goes Black when Screen is Static
Tags: debian;drivers;desktop-environment
Question: I have a Dell Inspiron 14 5000 2-in-1 with a i5-1035g1, 8gb ddr4 ram, and integrated graphics. I have only tested Debian distros, but I have tested a number of different desktop environments, but all of them have the same issue. If nothing is happening (no pixels are changing) on my screen it immediately goes black until I move the mouse or do something to make a pixel change (typing, moving mouse, pressing play to a video, etc). This does not happen if a video is playing. Also I would like to add that I installed kali wsl-2 with win-kex and the desktop environment for that does not have this issue.
I have looked at many other posts on similar issues, but haven't found anything to work. I think it might be a driver issue, but I cant seem to figure out what driver I would want, or if there even is an incorrect driver.
If you want more details on my laptop, here is a link to the amazon page for this device. https://www.amazon.com/Dell-Inspiron-5000-Touchscreen-i5-1035G1/dp/B08PTW4QD2/ref=dp_fod_2?pd_rd_i=B08PTW4QD2&psc=1
On my current distro (kali) here is what ```sudo lspci``` displays
```00:02.0 VGA compatible controller: Intel Corporation Iris Plus Graphics G1 (Ice Lake) (rev 07)
00:04.0 Signal processing controller: Intel Corporation Device 8a03 (rev 03)
00:0d.0 USB controller: Intel Corporation Ice Lake Thunderbolt 3 USB Controller (rev 03)
00:12.0 Serial controller: Intel Corporation Ice Lake-LP Integrated Sensor Solution (rev 30)
00:14.0 USB controller: Intel Corporation Ice Lake-LP USB 3.1 xHCI Host Controller (rev 30)
00:14.2 RAM memory: Intel Corporation Ice Lake-LP DRAM Controller (rev 30)
00:14.3 Network controller: Intel Corporation Ice Lake-LP PCH CNVi WiFi (rev 30)
00:15.0 Serial bus controller [0c80]: Intel Corporation Ice Lake-LP Serial IO I2C Controller #0 (rev 30)
00:15.1 Serial bus controller [0c80]: Intel Corporation Ice Lake-LP Serial IO I2C Controller #1 (rev 30)
00:16.0 Communication controller: Intel Corporation Ice Lake-LP Management Engine (rev 30)
00:1d.0 PCI bridge: Intel Corporation Ice Lake-LP PCI Express Root Port #9 (rev 30)
00:1f.0 ISA bridge: Intel Corporation Ice Lake-LP LPC Controller (rev 30)
00:1f.3 Multimedia audio controller: Intel Corporation Ice Lake-LP Smart Sound Technology Audio Controller (rev 30)
00:1f.4 SMBus: Intel Corporation Ice Lake-LP SMBus Controller (rev 30)
00:1f.5 Serial bus controller [0c80]: Intel Corporation Ice Lake-LP SPI Controller (rev 30)
01:00.0 Non-Volatile memory controller: KIOXIA Corporation Device 0001
```
Comment: It turns completely black less than a second after everything stops moving. My settings are all normal and it shouldn't go black until 4 minutes. Does that clarify it?
Comment: Could you please clarify "*If nothing is happening (no pixels are changing) on my screen it immediately goes black*"? **How many seconds/minutes do you have between leaving your computer untouched and the black screen?** (This duration could be related to **power management**, check [the documentation on gnome.org](https://help.gnome.org/users/gnome-help/stable/power.html.en#saving))
Comment: Yes, thank you for these details. I can't help you more though
|
Title: Julia: Simple Manual Matrix Input
Tags: matrix;julia
Question: Could someone please demonstrate how to input a matrix manual in Julia?
Code might act like like:
```pseudo>(9 3 2, 3 2 1)
9 3 2
3 2 1
```
Here is the accepted answer: The typical MATLAB syntax.
```julia> [9 3 2; 3 2 1]
2x3 Array{Int64,2}:
9 3 2
3 2 1
```
|
Title: how to use a helm chart inside an organization
Tags: kubernetes-helm;helm3;appdynamics
Question: I am trying to automate my helm installation. while trying to run the below command in GCP, the external URL is not accessible based on our organization standard.
```helm repo add appdynamics-charts https://ciscodevnet.github.io/appdynamics-charts
```
I am getting below error:
```Error: Looks like "https://ciscodevnet.github.io/appdynamics-charts" is not a valid chart repository or cannot be reached: Get https://ciscodevnet.github.io/appdynamics-charts/index.yaml: Forbidden
```
May I know what alternative options do I have? we have Jfrog and gitlab as repository.
|
Title: Auto reloading on save of template file in Quarkus?
Tags: quarkus
Question: I know Quarkus has auto reload for resources and java files however, while editing a html template using the Qute templating engine you have to manually hit refresh in the browser. This can be a little tedious when making tons of small css changes.
Is there a way to have it when you save the resource it auto calls a refresh to your browser? Tried the LiveReload extension for chrome but I believe that is for local files instead of served files.
Comment: I imagine you could just use a browser extension that triggers page refreshes periodically, every few seconds? Like Easy Auto Refresh for Chrome, it can reload every second if you want to.
LiveReload is only for specific LiveReload-compatible web frameworks, I think Quarkus is not supported by it.
Comment: Yeah seems like the only solution at the moment until LiveReload is implemented, I created a request for it here which seemed to be a duplicate. https://github.com/quarkusio/quarkus/issues/11761
|
Title: Implies sign between two lines
Tags: math-mode
Question: I would like to achieve the below effect:
I was able to achieve something little bit similar with the following code, however it is a wrong solution.
```\begin{ceqn}
\begin{equation*}
\begin{gathered}
x_{1}=h \\
x_{2}=\dot{h} \\
\downarrow \\
\dot{x_{1}} = x_{2}\\
\dot{x_{2}} = u
\end{gathered}
\end{equation*}
\end{ceqn}
```
My wrong solution:
Could you please let me know how to achieve the desired effect?
Thank you in advance!
Comment: Notice that `\dot{x_{1}}` is different than `\dot{x}_{1}`. You probably want to use the latter.
Here is the accepted answer: ```\documentclass{article}
\usepackage{amsmath}
\begin{document}
\begin{equation*}
\begin{aligned}
x_1&=p\\
x_2&=\dot{p}
\end{aligned}
\quad\Rightarrow\quad
\begin{aligned}
\dot{x}_1&=x_2\\
\dot{x}_2&=u
\end{aligned}
\end{equation*}
\end{document}
```
Here is another answer: A simple version (you might need to adjust spacing):
```\documentclass{article}
\usepackage{amsmath}
\begin{document}
\[
\begin{gathered}
x = y\\
y = x
\end{gathered} \Rightarrow \begin{gathered}
x = y\\
y = x
\end{gathered}
\]
\end{document}
```
|
Title: Git - take a code, branch it and push partially
Tags: git;git-extensions
Question: I got a huge code base, with many changes, I want to branch it, and push it to a remote new branch, but to push only change sets from the last month, make the first change of the month look like it's the creation of the repository, meaning I don't care about previous changes.
I'm sure it's possible, just don't know what's it called and how to do it.
Comment: Sorry I don't understand
Comment: Fair enough. Fixed my answer.
Comment: Its for pushing to a new repo...
Here is another answer: One potential solution would be using a filter-branch query in order to isolate the relevant commits (one month old or less) in its own repo.
But that means pushing to a new repo, not pushing a new branch in an existing repo.
Unless you create a disjoint branch (a new root commit), with no common history. See "Adding older versions of code to git repo".
In that case, you would indeed push a new branch based on the result of ```filter-branch``` (which serves to split the repo history and isolate the changes that you want).
Comment for this answer: @Chen: the general idea is to isolate the history in a separate reop, and push it to your new repo.
Here is another answer: If I get your request correctly, you want to create a new repository starting at a specific point from your current repository. Why? Because you want to keep it clean and eliminate every history behind that certain specific point. Now, that's more likely a good idea, and here is a link to better answer.
The key term here is either squash or filter-branch. You just need to have a backup first.
Above of all, you're requesting a very specific thing to do in GitExtensions. It does not do that. It does not do many things, in all truth... That's why it even gives you a button to command line.
You'll need it. You'll need command line tweaking. If you're not confortable on doing that, then you're out of luck. I know no git gui tools that will do this job for you.
Below, is just part of my previous (now legacy) answer, before op's new comment on his true intents.
If that was not the case, let's assume there's a good reason for "taking a code, branching it, and pushing partially". Then, all you have to do is follow Mark's directions, right there in the other answer.
Or, let's assume it is for backup. Then, that's a bad way to do it. Instead, get a backup tool, and use it. Simple as that. GIT isn't meant for backup and shouldn't be used for such, despite many attempts. I highly advice using CrashPlan or even Dropbox (my referral link).
Here is another answer: First, let's suppose that you've found the commit from about a month ago that you want to be the new first commit, perhaps with ```git show HEAD@{1.month.ago}``` or by just looking through ```git log```. Let's say that that commit is ```f414f31```. Let's also suppose that the name of the branch you're working on is called ```dev```.
You say that you want it to appear that a later commit was the first one in the repository, so there's no real point in keeping this branch in the same repository - there will be no history in [email protected]. So, let's create a new empty repository in order to start from a clean slate:
``` mkdir squashed-repository
cd squashed-repository
git init
```
Now let's add a remote that refers to your old repository, and fetch all the branches from there as remote-tracking branches in your new repository.
```git remote add previous /home/whoever/original-repository/
git fetch previous
```
Now update your working tree and index from the commit at the start of the month:
```git checkout f414f31 .
```
(Note the ```.``` at the end of that line.)
Now create a commit from the state of the index:
```git commit -m 'A new start.'
```
Now you use ```git rebase``` to replay all of the commits from after ```f414f31``` up to and including ```previous/dev``` on top of your new ```master```, which currently only has one commit.
```git rebase --onto master b1cbc10e84bb2e2 previous/master
```
You may have to fix some conflicts during that rebase. By default, ```git rebase``` will linearize the history when it reapplies the changes introduced by those commits - you can tell it to try to preserve them with ```-p```, but that may not work.
Now the ```master``` branch in this new repository should be as you want it, so you can remove the remote we created:
```git remote rm previous
```
I should say that I'd generally try to avoid this type of rewriting of history, especially if you've shared the original repository with anyone. In any case, the earlier history can be really useful - is it really so bad to keep that in your repository?
Comment for this answer: Is there a particular part (starting from the beginning, perhaps) that you don't understand? If so, you might consider starting with a more specific question on Stack Overflow, since what you're trying to do needs a clear understanding of git concepts.
Here is another answer: There is the ```git checkout --orphan``` method that can create an independent branch that can be used in a similar manner, that may save some key strokes.
Obviously (?), as implied by other, things will be simpler if you have selected a simple linear portion of history as your baseline.
Edit: the clone step is detailed at how-to-clone-a-single-branch-in-git
Comment for this answer: how do I select a simple linear history?
Comment for this answer: One method is to have a look with gitk to see if you have a portion of the appropriate branch looking for a recent section as far back as the last merge. The recent set of commit-commit-commit without a merge is (a) a pretty unique sha1 sequence, and (b) independent of anything else other than the initial commit's single parent sha1. This should provide that unique key for branch updates to latch on to.
Comment for this answer: For the branch you want, go back about 6-8 commits before the place you want to start. This will give you a 'clean' sequence to compare against if you have any problems later.
|
Title: How do I read a text file into to my main function and store it in an array?
Tags: c++
Question: I made a text file in my function I created and What I'm trying to do is read that text file in the main function then store the text file into an array. After I figure out how to do both I will compare the text file answers with the correct answers.
```#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void Get_Answers();
int main()
{
const int NUM_ANSWERS = 20;
char answers[NUM_ANSWERS] = { 'A', 'D', 'B', 'B', 'C', 'B', 'A', 'B', 'C', 'D', 'A', 'C', 'D', 'B', 'D', 'C', 'C', 'A', 'D', 'B' };
string textName;
//Fuction for the users answers
Get_Answers();
ifstream textIn;
textIn.open(textName);
if (textIn.fail())
{
cout << "\nFile not found; program will end";
return (0);
}
cout << endl << endl;
system("pause");
return(0);
}
void Get_Answers()
{
const int NUM_ANSWERS = 20;
char userAnswers[NUM_ANSWERS];
string textName;
cout << "\nEnter a text file name ";
cin >> textName;
ofstream textFileOut;
textFileOut.open(textName);
for (int i = 0; i < NUM_ANSWERS; i++)
{
cout << "\nEnter the test answers ";
cin >> userAnswers[i];
textFileOut << userAnswers[i] << '\n';
}
textFileOut.close();
}
```
Comment: How do I read that text file I made in the "Get_Answers" function to the main function.... or should I say how do I input the text file into my main function?
Comment: Ok... so what's the question?
Here is another answer: Ok, judging by what you wrote as your question and by my debug results, the problem you have is that you correctly read the file inside the function, but you don't pass this data outside the Get_Answers() function.
I think the C++ way of doing this would be:
1) Initialize a pointer to empty char array in main() function:
```char* userAnswersPointer = new char[NUM_ANSWERS];
```
2) Parametrize your Get_Answer() function to pass a pointer to this array:
```void Get_Answers(char* userAnswers_Ptr, int N_ANS) {
//...
for (int i = 0; i < N_ANS; i++)
{
cout << "\nEnter the test answers ";
cin >> userAnswers_Ptr[i];
textFileOut << userAnswers[i] << '\n';
}
//...
}
```
3) Use it properly in main():
```int main() {
//...
Get_Answers(userAnswersPointer, NUM_ANSWERS);
//...
return 0;
}
```
I didn't compile it, just wrote out of my head, so feel free to check this out. It should give you an idea how this should be done.
Comment for this answer: @simplegamer: If any of the answer helped you, vote it up or mark it as an answer so the other users, who may stumble upon this question could easier get to the correct answer of your question.
Here is another answer: You can do it following this code:
``` st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16ifstream is ("test.txt", st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16ifstream181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16inary);
if (is) {
// get length of file:
is.seekg (0, is.end);
int length = is.tellg();
is.seekg (0, is.beg);
char * buffer = new char [length];
st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16cout << "Reading " << length << " characters... ";
// read data as a block:
is.read (buffer,length);
if (is)
st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16cout << "all characters read successfully.";
else
st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16cout << "error: only " << is.gcount() << " could be read";
is.close();
// ...buffer contains the entire file...
delete[] buffer;
}
```
Found this snippet of code here: http://www.cplusplus.com/reference/istream/istream/read/
Replace "test.txt" with the name of your file. However your main code has no way of knowing what the file name is created in Get_Answers().
Here is another answer: If you mean store each line to an array, a for loop and getline should work well.
Edit: judging by your previous answer, I would say yes this is how to do it.
To elaborate a little more, a simple way of doing this would be to make a for loop to count how many lines there are, then go to the beginning of the file and make another for loop: for(int i = 0; i != lines; i++)
Then in the for loop make it array[i] = getline(file,string);
You can use while(!file.EOF()) instead of the for loop and the while loop. I just prefer getting a line count for some reason.
Comment for this answer: Basically the user enters 20 answers in the Get_answers function. The answers are then written on to a text file. My problem is idk how to get the text file answers into my main function. Sorry if I'm confusing anyone I'm a beginner.
Comment for this answer: Well one thing you can do then if you want to compare is save both to files then open both and save both to arrays using the information I posted. After that, you can make another for loop that uses the counter data and compares the elements of the array. For example, If arr[i] != arr1[i], the answer is wrong.
Maybe have a variable for wrong answers and right answers and each time it is wrong, it increases wrong, otherwise it increases right.
|
Title: Onclick linear layout , return view id always -1
Tags: android;view
Question: In my app , I try to generate dynamic arrays of view and try to add onclick listener but onclick that view it is returning java.lang.ArrayIndexOutOfBoundsException: length=5; index=-1 and view id return always -1, please help me how to solve it.
Below is my code:-
```private void setLayout() {
layoutHeader = new LinearLayout[5];
layoutTable = new LinearLayout[5];
for (int i = 0; i <5; i++) {
layoutHeader[i] = new LinearLayout(this);
layoutHeader[i].setLayoutParams( new LayoutParams(LayoutParams.FILL_PARENT, 50));
layoutHeader[i].setBackgroundColor(R.color.background);
LayoutParams vName = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView tv=new TextView(this);
tv.setLayoutParams(vName);
tv.setText("Reliance");
layoutHeader[i].addView(tv);
LayoutParams pts = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView tvPts=new TextView(this);
tvPts.setLayoutParams(pts);
tvPts.setText("12345");
tvPts.setGravity(0);
layoutHeader[i].addView(tvPts);
myWalletLayout.setId(i);
myWalletLayout.addView(layoutHeader[i]);
layoutHeader[i].setOnClickListener(onClickHeader);
//////////////////////////////////////////////////////////////////////////////////////
//////////SET CHILD VIEW/////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
layoutTable[i] = new LinearLayout(this);
layoutTable[i].setLayoutParams( new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
layoutTable[i].setId(12345);
layoutTable[i].setVisibility(View.GONE);
TableLayout MainLayout = new TableLayout(this);
MainLayout.setVerticalFadingEdgeEnabled(true);
MainLayout.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
MainLayout.setStretchAllColumns(true);
MainLayout.setFadingEdgeLength(4);
//Create the first row and add two text views
TableRow row = new TableRow(this);
row.setPadding(1, 1, 1, 1);
row.setBackgroundColor(Color.parseColor("#ABA8A8"));
TextView txt1 = new TextView(this);
txt1.setText("Card Number");
txt1.setTextColor(Color.parseColor("#000000"));
txt1.setGravity(android.view.Gravity.CENTER);
TextView txt2 = new TextView(this);
txt2.setText("1234545");
txt2.setTextColor(Color.parseColor("#000000"));
txt2.setGravity(android.view.Gravity.CENTER);
row.addView(txt1);
row.addView(txt2);
MainLayout.addView(row);
TableRow row1 = new TableRow(this);
row1.setPadding(1, 1, 1, 1);
row1.setBackgroundColor(Color.parseColor("#ABA8B8"));
TextView txt3 = new TextView(this);
txt3.setText(" Barcode");
txt3.setTextColor(Color.parseColor("#000000"));
txt3.setGravity(android.view.Gravity.CENTER);
TextView txt4 = new TextView(this);
txt4.setText("1234545");
txt4.setTextColor(Color.parseColor("#000000"));
txt4.setGravity(android.view.Gravity.CENTER);
row1.addView(txt3);
row1.addView(txt4);
MainLayout.addView(row1);
layoutTable[i].addView(MainLayout);
layoutTable[i].setId(i);
myWalletLayout.addView(layoutTable[i]);
}
}
OnClickListener onClickHeader = new OnClickListener() {
public void onClick(View v) {
int currSelId = v.getId();
System.out.println("=============================="+currSelId);
if(layoutTable[currSelId].getVisibility()==8){
layoutTable[currSelId].setVisibility(View.VISIBLE);
}
else{
layoutTable[currSelId].setVisibility(View.GONE);
}
}
};
```
|
Title: How do shields work in the game I-War?
Tags: independence-war
Question: In this comment, @GrimmTheOpiner claims
```
...shields are a universal Sci-Fi trope and Star Trek is no more guilty than any/many others! The only "shields" I can bring to mind that were explained differently were in the computer game "iWar" [sic].
```
Can someone explain what is unique about the shield mechanics in I-War?
(I'm assuming this is a reference to I-War (1997 video game) and not I-War (1995 video game).
Comment: according to these guides - looks like there is nothing specifically different about these shields than Star Wars / Star Trek shielding https://www.giantbomb.com/independence-war-the-starship-simulator/3030-8415/ | https://www.i-war2.com/documents/help/tactics/combat-guide - hardly definitive, thus just a comment -
Comment: both links work for me: https://www.giantbomb.com/independence-war-the-starship-simulator/3030-8415/
Comment: https://www.i-war2.com/documents/help/tactics/combat-guide
Here is another answer: The manual for Independence War describes the function and operation of shields in this fictional universe.
```
SHIELDS
The NSO 929 is also fitted as standard with two Displacement array shields fitted on wide swivel mountings. Although provided as a defensive mechanism, they may be used offensively, albeit at close range.
The principle of linear displacement has been used as a method of propulsion for over 200 years. Its potential as a defensive device is a more recent innovation. The shield array projects a steerable region of disrupted space. Radiation or material passing through that space is displaced in random directions by amounts of up to 100meters.
The shields region of disruption can be between 100m to 200m from the array itself. The region can vary in radius between 2 and 10 meters. The newest shield arrays can easily block the blast from a particle beam cannon.
An important point to remember is that the shielding zone must be kept between the ship and any hostile adversary. For this reason, the LDA is mounted on a fast linkage mechanism which can automatically track hostile vessels and keep the ship protected. The NSO-929 is fitted with two such LDAs mounted at complementary positions - each capable of covering one hemisphere.
The LDA has also been used with some success as a hostile weapon at low range, by being able to displace elements of the enemy ship's hull.
```
The manual for Independence War 2: Edge of Chaos gives some additional info about their tactical uses and weaknesses.
```
LDA shields
Combat ships are usually protected by one or more Linear
Displacement Array (LDA) shield systems. LDAs are an offshoot of LDS
technology that uses local spatial distortions to disrupt a small area of
space in front of the shield projector. This disperses the energy of an
incoming weapon, preventing it from damaging the hull. Or that’s what
the technical manual says. All you need to know is that if you see a
purple flash when you shoot a ship, you didn’t do it any damage.
“Shield coverage varies from ship to ship. However, the drives
are always vulnerable, so cover your ass while shooting
theirs.”
Another important point to remember about shields is that each LDA
decides which is the most likely enemy to fire at you and tracks that
vessel with the shield projector. You can use this to your advantage by
getting your wingmen to attack your target. The target’s LDA will not be
able to deflect the weapons from both attackers if they attack from a
different angle.
```
Comment for this answer: ...so pretty much the same as Star Trek imo
Comment for this answer: @NKCampbell - Very much not so. In Star Trek the shields are a projected force-field. In I-War, the shields are a projected region of disrupted space-time.
Comment for this answer: @Valorum - Because that's so much more scientific. :)
Comment for this answer: @NKCampbell : The *TNG Technical Manual* describes shields in very similar terms: *"the deflector system creates a localized zone of highly focused spatial distortion"* (Section 11.8, pg. 138).
|
Title: splitting the root from path in a platform-agnostic way in python
Tags: python;split;path;root
Question: i have a path that describe a folder:
```s = foo/bar/baz
```
and i need to split the root from everything else. I know that i could use:
```s.split('/',1)
```
but this is not platform agnostic. Also it seems that the os.path module doesn't implement this feature, so i'm a bit lost. Writing the function from scratch looks like ridiculous amount of work for the task.
Here is the accepted answer: You can use the ```os.path.sep``` variable whose value is defined according to the platform in which the module is installed.
```import os
s.split(os.path.sep, 1)
```
Comment for this answer: that's exactly what i was looking for! Thanks ;)
Comment for this answer: I would also add os.path.normpath(s).split(os.path.sep, 1) to get the right path every time, in case you cross-platform some path from Linux to Windows.
|
Title: Locust.io: Controlling the request per second parameter
Tags: amazon-web-services;load-testing;stress-testing;locust
Question: I have been trying to load test my API server using Locust.io on EC2 compute optimized instances. It provides an easy-to-configure option for setting the consecutive request wait time and number of concurrent users. In theory, rps = wait time X #_users. However while testing, this rule breaks down for very low thresholds of #_users (in my experiment, around 1200 users). The variables hatch_rate, #_of_slaves, including in a distributed test setting had little to no effect on the rps.
```
Experiment info
The test has been done on a C3.4x AWS EC2 compute node (AMI image) with 16 vCPUs, with General SSD and 30GB RAM. During the test, CPU utilization peaked at 60% max (depends on the hatch rate - which controls the concurrent processes spawned), on an average staying under 30%.
Locust.io
setup: uses pyzmq, and setup with each vCPU core as a slave. Single POST request setup with request body ~ 20 bytes, and response body ~ 25 bytes. Request failure rate: < 1%, with mean response time being 6ms.
variables: Time between consecutive requests set to 450ms (min:100ms and max: 1000ms), hatch rate at a comfy 30 per sec, and RPS measured by varying #_users.
```
The RPS follows the equation as predicted for upto 1000 users. Increasing #_users after that has diminishing returns with a cap reached at roughly 1200 users. #_users here isn't the independent variable, changing the wait time affects the RPS as well. However, changing the experiment setup to 32 cores instance (c3.8x instance) or 56 cores (in a distributed setup) doesn't affect the [email protected].
So really, what is the way to control the RPS? Is there something obvious I am missing here?
Here is another answer: (one of the Locust authors here)
First, why do you want to control the RPS? One of the core ideas behind Locust is to describe user behavior and let that generate load (requests in your case). The question Locust is designed to answer is: How many concurrent users can my application support?
I know it is tempting to go after a certain RPS number and sometimes I "cheat" as well by striving for an arbitrary RPS number.
But to answer your question, are you sure your Locusts doesn't end up in a dead lock? As in, they complete a certain number of requests and then become idle because they have no other task to perform? Hard to tell what's happening without seeing the test code.
Distributed mode is recommended for larger production setups and most real-world load tests I've run have been on multiple but smaller instances. But it shouldn't matter if you are not maxing out the CPU. Are you sure you are not saturating a single CPU core? Not sure what OS you are running but if Linux, what is your load value?
Comment for this answer: One of the reason i strive for RPS is due of the fact that I know the users (for eg. 2) but for locust, 2 users are generating a request of 110+ RPS, but in real world, those 2 users can only make 1-2 requests per seconds? How is that helpful in determining user based loads?
Here is another answer: While there is no direct way of controlling rps, you can try ```constant_pacing``` and ```constant_throughput``` option in ```wait_time```
From docs
https://docs.locust.io/en/stable/api.html#locust.wait_time.constant_throughput
```
In the following example the task will always be executed once every 1 seconds, no matter the task execution time:
```
```class MyUser(User):
wait_time = constant_throughput(1)
```
```constant_pacing``` is inverse of this.
So if you run with 100 concurrent users, test will run at 100rps (assuming each request takes less than 1 second in first place
|
Title: CSS animation and transformation in react-native
Tags: css;react-native
Question: Just wondering if we can use CSS animation and transformation in react-native?
i.e.
``` <Image style={animateImage} / >
StyleSheet.create({
animateImage {
width: 100px;
height: 100px;
background: red;
transition: width 3s;
transition-delay: 1s;
}
});
```
Here is another answer: No, you can't use CSS animations and transformations in React Native.
There is a Keyframes library for React-Native called react-native-facebook-keyframes. It might be what you need instead.
Here is another answer: No, you cannot. React Native's ```Stylesheet``` properties are pretty limited when compared with vanilla CSS.
For animations look into the Animated API.
|
Title: ImportError when trying to install "worldengine"
Tags: python;installation;pip;importerror
Question: Tried to install this tool here https://github.com/Mindwerks/worldengine.
pip install git+https://github.com/Mindwerks/worldengine.git gives me
this error message
I get the same error when installing it manually with the source setup.py.
I'm a total beginner to Python and coding in general so I really don't know how to solve this myself. The tool is quite old and discontinued, so I'm using Python 2.7 to install since Python 3 just brings up a whole load of other error messages.
Comment: The console then tells me: C:\Python27\python.exe: can't open file 'pip': [Errno 2] No such file or directory. There is a pip file in Scripts. How do I get pip for 2.7?
Comment: No, you're using Python 3.10. The error says so. Try `py -2 pip install git+etc` to force it to use Python 2.
|
Title: Undefined symbols for architecture x86_64 when inheriting
Tags: c++;c++11
Question: I have a C++ code, where I'm trying to use inheritance to reuse my code. But when I make the code I get the following error:
```
Undefined symbols for architecture x86_64:
"QuickUnion181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16QuickUnion(int)", referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [a.out] Error 1
```
My Makefile:
```CC = g++
CFLAGS = -std=c++11 -Wall -c
LFLAGS = -std=c++11 -Wall
DEBUG = -g
OBJS = main.o unionfind/UnionFind.o unionfind/QuickUnion.o
a.out: $(OBJS)
$(CC) $(LFLAGS) $(OBJS) $(DEBUG)
main.o: main.cpp
$(CC) $(CFLAGS) main.cpp $(DEBUG)
unionfind/QuickUnion.o: unionfind/UnionFind.h unionfind/QuickUnion.h unionfind/QuickUnion.cpp
$(CC) $(CFLAGS) unionfind/QuickUnion.cpp $(DEBUG)
unionfind/UnionFind.o: unionfind/UnionFind.h unionfind/UnionFind.cpp
$(CC) $(CFLAGS) unionfind/UnionFind.cpp $(DEBUG)
```
The UnionFind .h and .cpp:
```#ifndef UNIONFIND_H
#define UNIONFIND_H
#include <vector>
class UnionFind {
protected:
int connectedComponents;
st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16vector<int> parents;
public:
UnionFind(int);
virtual void connect(int, int) = 0;
virtual int find(int) = 0;
bool connected(int, int);
int count();
};
#endif
...
#include "UnionFind.h"
UnionFin181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16UnionFind(int size): parents(size) {
connectedComponents = size;
for (int i = 0; i < size; i++) {
parents[i] = i;
}
}
bool UnionFin181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16connected(int p, int q) {
return find(p) == find(q);
}
int UnionFin181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16count() {
return connectedComponents;
}
```
The QuickUnion .h and .cpp:
```#ifndef QUICKUNION_H
#define QUICKUNION_H
#include <vector>
#include "UnionFind.h"
class QuickUnion: public UnionFind {
public:
QuickUnion(int);
void connect(int, int);
int find(int);
};
#endif
...
#include "QuickUnion.h"
QuickUnion181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16QuickUnion(int size): UnionFind(size) {
}
void QuickUnion181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16onnect(int p, int q) {
int pRoot = find(p);
int qRoot = find(q);
if (pRoot == qRoot) {
return;
}
parents[pRoot] = qRoot;
connectedComponents--;
}
int QuickUnion181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16ind(int p) {
while (p != parents[p]) {
p = parents[p];
}
return p;
}
```
main.cpp
```#include <iostream>
#include "unionfind/QuickUnion.h"
using namespace std;
int main() {
QuickUnion qu(10);
cout << "Count:" << endl;
cout << qu.count();
}
```
Maybe there is something to do with the constructor, but I don't know neither why this error is happening nor how to correct it.
PS.: I am using OS X El Capitan.
Comment: Show us `main` method.
Here is the accepted answer: Default output file for command
```g++ -c path/to/file.cpp
```
is not ```path/to/file.o``` but ```./file.o```. That means, that later invoked ```g++``` for linkage of object files fails to find those files. Edit your ```Makefile``` and add ```-o $@``` to ```unionfind/QuickUnion.o``` and ```unionfind/UnionFind.o``` rules.
|
Title: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.isEmpty()' on a null object reference
Tags: java;runtime-error
Question: This code works fine on android version below 9 but crashes on 9 and ABOVE:
```public class Utils_String {
public static String prepareContacts(Context ctx,String number) {
if (number.isEmpty())
return "";
String preparednumbers=number.trim();
preparednumbers=preparednumbers.replace(" ","");
preparednumbers=preparednumbers.replace("(","");
preparednumbers=preparednumbers.replace(")","");
if(preparednumbers.contains("+")) {
preparednumbers=preparednumbers.replace(preparednumbers.substring(0,3),""); //to remove country code
}
preparednumbers=preparednumbers.replace("-","");
return preparednumbers;
}
}
```
The code where I call ```utils_Strings```:
```recyclerAdapter.setListener(new Adapter_incoming.itemClickListener() {
@Override
public void onClick(View v, int position) {
if(mensu){
Contacts_data contacts1= (Contacts_data) searchPeople.get(position);
String records= GetContact.getRecordsList(v.getContext(),recordings,"IN",contacts1);
if(Build.VERSION.SDK_INT>18){
GetContact.openMaterialSheetDialog(getLayoutInflater(),position,records, Utils_String.prepareContacts(ctx,contacts1.getNumber()));
}else{
GetContact.showDialog(v.getContext(),records,contacts1);
}
}else {
Contacts_data contacts= (Contacts_data) realrecordingcontacts.get(position);
String records= GetContact.getRecordsList(v.getContext(),recordings,"IN",contacts);
if(Build.VERSION.SDK_INT>18){
GetContact.openMaterialSheetDialog(getLayoutInflater(),position,records, Utils_String.prepareContacts(ctx,contacts.getNumber()));
}else{
GetContact.showDialog(v.getContext(),records,contacts);
}
}
GetContact.setItemrefresh(new GetContact.refresh() {
@Override
public void refreshList(boolean var) {
if(var)
recyclerAdapter.notifyDataSetChanged();
}
});
}
});
```
Comment: Where exactly you are calling Utils_String ? and did you check for
1. NULL value 2. !TextUtils.isEmpty(number)) 3. check for "" or 'null' (if it's from cursor
Comment: How are you calling that method? What are you using for the parameters?
Here is the accepted answer: You have to check the number is null or not, after that you can check if the value is empty or not.
As @Jon Skeet commmented, the best way approached this is, add new condition using OR for null
```public static String prepareContacts(Context ctx, String number){
if(number == null || number.isEmpty()){
return "";
}else{
String preparednumbers=number.trim();
preparednumbers=preparednumbers.replace(" ","");
preparednumbers=preparednumbers.replace("(","");
preparednumbers=preparednumbers.replace(")","");
if(preparednumbers.contains("+")){
preparednumbers=preparednumbers.replace(preparednumbers.substring(0,3),""); //to remove country code
}
preparednumbers=preparednumbers.replace("-","");
return preparednumbers;
}
}
```
Comment for this answer: This won't currently compile - it doesn't return anything if `number` *is* null. Rather than indent most of the body further, I'd rewrite it as `if (number == null || number.isEmpty()) { return ""; } and then the rest of it can be all at the "top level" of the method, which will make it easier to read.
Comment for this answer: Feel free to update your answer with my suggestion if you agree with it - no credit necessary.
Comment for this answer: @JonSkeet should I update my answer, and credit to you ?
|
Title: After upgrade from Flutter 2 to Flutter 3 on running automation, my app immediately crash after launch
Tags: flutter;mobile;automation
Question: We try to run Automation with Webdriver.io, Appium and appium flutter driver.
After upgrade from Flutter 2 to Flutter 3 app is crash immediately after launch. It's happen on both Android and iOS (physical and simulator devices).
App release with Flutter 2 is work correctly.
Build command:
```flutter build apk --debug --target=./test_driver/build.dart
```
Run command:
``` npx wdio config/wdio.android.flutter.conf.js --spec tests/flutter_specs/app.test.spec.js
```
In Output get an error:
```DEBUG webdriver: request failed due to response error: unknown error
ERROR webdriver: Request failed with status 500 due to unknown error: An unknown server-side error occurred while processing the command. Original error: Cannot read property 'match' of undefined
ERROR webdriver: unknown error: An unknown server-side error occurred while processing the command. Original error: Cannot read property 'match' of undefined
```
I cleaned npm node modules and package.lock and it didn't help.
My dependencies from package.json:
"dependencies":
``` "@wdio/appium-service": "^6.1.16",
"@wdio/cli": "^6.1.24",
"@wdio/jasmine-framework": "^6.1.23",
"@wdio/junit-reporter": "^7.5.3",
"@wdio/local-runner": "^6.1.24",
"@wdio/sauce-service": "^6.1.16",
"@wdio/spec-reporter": "^6.1.23",
"@wdio/sync": "^6.1.14",
"appium": "^1.21.0",
"appium-flutter-driver": "0.0.4",
"appium-flutter-finder": "^0.1.0",
"babel-eslint": "^10.1.0",
"node-fetch": "^2.6.0",
"webdriverio": "^6.1.24"
},
"devDependencies": {
"npm-bundle": "^3.0.3"
},
"bundledDependencies": [
"@wdio/appium-service",
"@wdio/cli",
"@wdio/jasmine-framework",
"@wdio/junit-reporter",
"@wdio/local-runner",
"@wdio/sauce-service",
"@wdio/spec-reporter",
"@wdio/sync",
"babel-eslint",
"node-fetch",
"webdriverio"
]
### Update!!
```
We clone small flutter project with minimum dependencies: https://github.com/bitrise-dev/flutter-sample-app-hello-world
Before update to flutter 3 all works fine, but after it we get the same error mention before
Any help to solve the issue...
Comment: did you ever solve this issue?
Comment: Yes, i resolve this issue
|
Title: Server is showing error message of Max_execution_time:
Tags: mysql;phpmyadmin;phpexcel;execution-time;phpexcelreader
Question: I want to import an Excel (CSV, XLX, XLSX) file to my phpmyadmin databases. The file is 50 MB having around 5 million records. The issue is that whenever I try to upload that file, around 900 000 records are successfully inserted, but after that server shows an error of Exceeding Time Limit.
I also tried it by increasing max-execution-time of PHP.ini file but still, it shows the same error message. My Server is Hostgator.
Comment: How did you try to increase the timeout limit? Did you try to create a php file with phpinfo(); function inside and verify that the timeout limit has been altered?
If you cannot.. a crappy way is to take a watch and count the seconds it takes to give you the timeout error.. just to verify that the limit you set, it was actually placed.
I mostly believe that hostgator would not allow the user to override any php.ini settings.
I know this is not your question but.. Would it work for you to break the file into smaller parts?
Comment: Just an extra suggestion since I am not aware of your code or server configurations: there are a few settings that might be related to what you are doing.. max_input_time, max_execution_time, set_time_limit, upload_max_filesize, post_max_size
Good luck and let me know the results!
Comment: Thank you so much for your kind reply. But Hostgator is allowing to change the php.ini file. And yes max_execution_time can be altered. Because before changing I was just able to insert 1 lac to 3 lac data but now I am able to insert 9 lac 52K records. And yes I think I must have to upload it in Chunks. Anyhow thanks again mate.
|
Title: glfwSwapBuffers(window) causing a segfault
Tags: c++;opengl;cmake;glfw
Question: I was having a problem with code from a GLFW tutorial (open.gl) and I narrowed it down to it being caused by
```glfwSwapBuffers(window);
```
The full code: http://pastebin.com/Evtf5PRf
The CMakeLists.txt I am using: http://pastebin.com/vKUQiMtf
This is on Ubuntu 12.04
Changing to the proprietary drivers has fixed the issue! (See answer from me below)
Comment: Have you checked that `window` isn't NULL?
Comment: Works fine for me. What does gdb say?
Comment: Maybe my graphics card doesn't support OpenGL3.2 on Ubuntu (HD7970 should handle OpenGL3.2 right?)
Comment: Problem seems to have been resolved by changing my graphics driver from the Ubuntu default to the AMD proprietary drivers. Interestingly enough it is giving me a Unsupported Hardware watermark in the bottom right of my screen.
Am going to install the updates graphics drivers form AMD in the hopes of getting rid of the watermark.
Here is the accepted answer: This issue is caused by GLFW not interacting properly with the drivers Ubuntu provides. To solve this, change to the proprietary drivers.
How to change your graphics drivers to the proprietary drivers:
Open System Settings (Icon is a gear with a wrench)
Open Software and Updates
Go to the Additional Drivers tab
Select the proprietary graphics drivers for you graphics card.
Restart your computer for the changes to apply
|
Title: Completed elections don't show all candidates in the primary phase
Tags: bug;election;moderator-primaries
Question: On the primary tab of completed elections, only the top 10-finishing candidates are shown. This should be changed to show the primary as it was run, with all candidates (up to 30).
Only the election phase should cut off candidates who didn't pass the primary.
Comment: @ShadowTheKidWizard It now shows "18 Candidates" for me (in fact, a few minutes ago I'm pretty sure it was showing me "17 Candidates", too). It seems that there is a regression of the bug marked (status-completed) here: [Election primaries appear to perpetually check the candidate reputation](https://meta.stackexchange.com/q/102260). Probably this bug has been around for a while, since there's a much older bug report that looks like a duplicate of this one: [Candidates not surviving primaries not displayed in "primary" tab anymore for past elections](https://meta.stackexchange.com/q/170912).
Comment: @ShadowTheKidWizard Ah, you're probably right.
Comment: Worth to mention that it [does show](https://i.stack.imgur.com/x51Aj.png) "19 Candidates" in the title, so even more confusing. (feel free to use the screenshot in the bug report :))
Comment: @TheAmplitwist more likely it's a case of deleted account.
Here is another answer: If you're after the primary scores, you can use the Data Explorer as a workaround.
```select Id as [Post Link], OwnerUserId as [User Link], Score, CreationDate, Body
from Posts where PostTypeId = 6
order by CreationDate
```
Results here for Stack Overflow. Entries with a Score of zero didn't make it to the primary (or actually got a net score of zero there, but that's probably not common). The Post Link column takes you to the nomination, if it wasn't removed. To see only people who passed the nomination phase, tack on a ```and Score <> 0``` to the "where" part.
|
Title: Development of a FIX engine
Tags: trading;fix-protocol
Question: I am new in the FIX and have requirement to develop a small FIX engine to communicate trading system. As I know there are plenty of FIX engine available but here requirement is to develop it.
Could anyone provide me the reference on any open source or any good article to start it?
Here is the accepted answer: For C++ use quickfix
Java use QuickfixJ
For .NET use VersaFix
To refer to Fix message constructions.
Both the libraries(Quickfix) have the same nomenclature as mentioned in the FIX protocol standards. But they are little buggy here and there, but you can rectify them in your source code. I have used both of the libraries in a commercial project and say so after seeing the libraries work. But the code is quite simple and they have an online reference manual to work with.
But developing your own library will be a big task for only one developer, if you have a team it can be much easier. Remember other than parsing you have to incorporate network communications, configuration on how to run it and threading structures also.
Comment for this answer: Not a very big task though, depending on the requirements level can take anywhere from two weeks to half a year.
Comment for this answer: @Saurabh01 - Quickfix uses one thread per session, you can try that.
Comment for this answer: thanks DumbCoder. One more question, what architect would be use in the server to handle many client?
Here is another answer: You certainly want to [email protected].
Here is another answer: Developing your own FIX engine is not easy, specially if you will be dealing with FIX session level details yourself. Synchronizing sequences through ResendRequest, GapFill and SequenceReset is not easy and it would be nice if you can just use a FIX engine that is already doing that for you.
Another problem with the FIX protocol is REPEATING GROUPS. It is not easy to parse them quickly as it requires recursion or alternatively a complex iterative implementation.
Moreover, most Java FIX engines produce a lot of garbage when they are parsing the message, which increases variance and latency due to GC overhead.
Lastly, an intuitive API design is crucial to accelerate FIX development. If you want a good example of a clean API, you can check CoralFIX.
Disclaimer: I am one of the developers of CoralFIX.
|
Title: Creating Constructors with JavascriptCore
Tags: javascript;ios;objective-c;c;xcode
Question: When using the ```JavascriptCore API```, I'm not sure how to create new instances of Objective-C objects from Javascript via the ```new``` syntax ```(ex. var x = new MyAwesomeClass())```. It seems like the constructor objects that are created in Javascript when passing in an Objective-C class that conforms to a ```JSExport-derived protocol``` should be callable as constructors, but they are not.
For example, say I delcare a class that conforms to a ```JSExport-derived protocol``` and I insert it into the javascript context as such:
``` @protocol MyAwesomeClassExports <JSExport>
...
@end
@interface MyAwesomeClass : NSObject <MyAwesomeClassExports>
...
@end
JSContext *context = ...;
context[@"MyAwesomeClass"] = [MyAwesomeClass class]
```
Then, if I try to make a new instance in javascript via a syntax such as this:
```[object MyAwesomeClassConstructor] is not a constructor
```
Is it possible to make new instances of Objective-C objects from javascript using the ```new``` syntax? What I would ideally like is for it to ```alloc``` and then call the ```init``` method on my Objective-C instance. If any arguments were passed in javascript those would hopefully be accesible in the Objective-C ```init``` method via the [JSContext currentArguments] class method.
Here is the accepted answer: This question was asked the other day in the Apple Developer Forums, here.
From what I can tell, it looks as if this is a known deficiency that was only fixed recently in WebKit (which includes JavaScriptCore); and the change isn't in iOS7:
https://bugs.webkit.org/show_bug.cgi?id=123380
It might be possible to accomplish this externally to WebKit though by using JSObjectMake and a properly configured JSClassDefinition? I haven't had time to investigate this route.
Here is another answer: Create a protocol for the class you want to instantiate from Javascript. It should extend JSExport.
```@import JavaScriptCore
@protocol EntityExports <JSExport>
@property NSString *somePropertyToExpose
- (instancetype)initWithSomeValue:(NSString *)value;
@end
@interface Enity : NSObject <EntityExports>
@end
```
and in the .m file, implement the initializer and synthesize the property:
```@implementation Entity
@synthesize somePropertyToExpose = _somePropertyToExpose;
- (instancetype)initWithSomeValue:(NSString *)value
{
// implementation goes here
}
@end
```
Then, in your code that instantiates the JSContext:
```context[@"Entity"] = [Entity class];
```
and to instantiate an ```Entity``` in Javascript:
```var entity = new Entity("hello!");
```
(note that the property is not necessary for constructing the object; it is just there to make the example non-trivial).
Comment for this answer: Its worth noting that you can only have one initialiser in the JSExported class, multiple initialisers are discarded (see the above patch).
Here is another answer: I know this is really old, but this is what works for me:
```context[@"MyClass"] = ^MyClass*{
return [[MyClass alloc] init];
};
```
Then from JavaScript:
```var myClass = new MyClass();
```
Here is another answer: An easy solution is to define a constructor function in Obj-C.
```// Inside protocol
+ (MyAwesomeClass *)create;
...
// Inside implementation
+ (MyAwesomeClass *)create
{
return [[MyAwesomeClass alloc] init];
}
```
Then in JavaScript, simply call this constructor to create a new object:
```obj = MyAwesomeClass.create()
```
Comment for this answer: This helped me out. Good answer.
Here is another answer: I'm not sure this but I think you should create your Objective-C object first and after that you should create JSValue like this:
```MyAwesomeClass *myClass = [[MyAwesomeClass alloc] init];
JSValue *dataValue = [JSValue valueWithObject: myClass inContext:context];
```
Let me know is this help.
Here is another answer: This is what i've been using. Hope this helps!
```extern void RHJSContextMakeClassAvailable(JSContext *context, Class class){
NSString *className = NSStringFromClass(class);
context[[NSString stringWithFormat:@"__%@", className]] = (id) ^(void){ return [[class alloc] init]; };
[context evaluateScript:[NSString stringWithFormat:@"var %@ = function (){ return __%@();};", className, className]];
//allow a class to perform other setup upon being loaded into a context.
SEL selector = NSSelectorFromString(@"classWasMadeAvailableInContext:");
if ([class respondsToSelector:selector]){
((void (*)(id, SEL, JSContext*))[class methodForSelector:selector])(class, selector, context);
}
}
```
Comment for this answer: When using this, class methods can be accessed because the Constructor does not contain the correct prototype. This causes class methods to be unaccessable. The code does work for the constructor creation though.
|
Title: Which CUDA version should I install? Do they have back compatibility?
Tags: nvidia;cuda;gpu
Question: This is the first GPU I am using and unfortunately, I am using Ubuntu 20.04 not easy easy Windows.
I want to use my GPU (Nvidia Quadro 2000 1GB GDDR5) for very basic machine learning models. I've got a supercomputer from my university to train bigger models.
When I type ```nvidia-smi``` in my terminal I can see the following.
```+-----------------------------------------------------------------------------+
| NVIDIA-SMI 390.144 Driver Version: 390.144 |
|-------------------------------+----------------------+----------------------+
| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |
| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |
|===============================+======================+======================|
| 0 Quadro 2000 Off | 00000000:01:00.0 On | N/A |
| 34% 62C P0 N/A / N/A | 383MiB / 963MiB | 20% Default |
+-------------------------------+----------------------+----------------------+
+-----------------------------------------------------------------------------+
| Processes: GPU Memory |
| GPU PID Type Process name Usage |
|=============================================================================|
| 0 955 G /usr/lib/xorg/Xorg 93MiB |
| 0 1261 G /usr/bin/gnome-shell 143MiB |
| 0 3398 G ...AAgAAAAAAAAACAAAAAAAAAA= --shared-files 142MiB |
+-----------------------------------------------------------------------------+
```
In other answers for example in this one Nvidia-smi shows CUDA version, but CUDA is not installed there is ```CUDA version``` next to the ```Driver version```.
I want to download Pytorch but I am not sure which CUDA version should I download. Or should I download CUDA separately in case I wish to run some Tensorflow code. BTW I use Anaconda with VScode.
I found an old article which says my GPU supports CUDA 2.1. Are the newer versions back-compatible?
As per Nmath's suggestion, I went on to install CUDA from the Ubuntu repository as follows.
```$ sudo apt install nvidia-cuda-toolkit
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been Recommends: nvidia-visual-profiler (= 10.1.243-3) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.oing to be installed
Recommends: nvidia-visual-profiler (= 10.1.243-3) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
```
Here, I do understand that it need some dependencies. How do I fix it?
Comment: Check the CUDA compute capability requirements on any software you want to install. My 2GB Quadro 1000 (cc=2.1 same as yours) was limited to CUDA 8.x for my DNN and Tensorflow.
Comment: `nvidia-visual-profiler` is at the multiverse repository. Make sure you have it enabled. Open Software & Updates to confirm and act accordingly.
Comment: @ChanganAuto Yes, Software restricted by copyright or legal issues (multiverse) is already checked in Software and Updates.
Comment: @ubfan1 Yes. the CUDA toolkit 9.0 supports my driver version (from nvidia-smi). Still when I install an older version of Pytorch that supports CUDA 9.0, Still torch.cuda.is_available() is False. Please see this question: https://askubuntu.com/q/1383692/1230667
Here is another answer: Quadro 2000 has Fermi architecture with compute capability 2.1. If you want to do deep learning, you may find difficulties since most CUDA features for deep learning are available for GPU with compute capability 3.0 or higher. Also, you may not be able to update to the latest version of CUDA toolkit since each CUDA version has minimum compute capability that it supports.
If you use desktop GPU, probably this list can help in finding alternatives (old) desktop GPUs. For CUDA compatibility table, you may also find this explanation helpful especially when installing/upgrading the driver and the CUDA toolkit on your GPU-powered machine.
Here is another answer: Don't overthink this. Just use the version of CUDA that is in repos for your version of Ubuntu. Unless you have a very specific technical reason for doing so, you shouldn't need to install a specific version, especially not one that isn't in Ubuntu's repositories. This is as true with CUDA as it is any other software. Think about this: why would developers release new versions of software that stop supporting features and hardware that most people are still using?
In fact, if you try to explicitly install software versions (especially older ones) that are different than what's in Ubuntu's repositories, this is often a recipe for disaster as lots of software in Ubuntu/Linux rely on dependencies and expect the version that is in official repositories.
Comment for this answer: Did you run `sudo apt update` and `sudo apt upgrade` first? You need to be up-to-date on maintenance and your package management system can't be broken before installing anything new. This is a very different problem than the question you asked here. See: https://askubuntu.com/q/223237
Comment for this answer: `you have held broken packages` indicates that those commands would have had problems that need to be fixed first. Add the full output of each to your question
Comment for this answer: Thanks for the reply. I am getting some errors. I've updated the answer.
Comment for this answer: yes I did run the update and upgrade command first.
|
Title: What's the short key to comment/uncomment several lines in zend studio?
Tags: zend-studio
Question: Anyone knows this?
Here is the accepted answer: I don't actually use Zend Studio, however it is based on the Eclipse platform. For a default Eclipse install typically Ctrl+/ is typically mapped to toggle comments. I've also seen Ctrl+/ mapped to comment and Ctrl+\ used to uncomment.
You can always check your key binding by going to Window->Preferences and selecting "Keys" under the "General" branch of settings.
|
Title: I want to set "Password Must Change at Next Login" flag
Tags: c#;active-directory
Question: In my application, I am doing things that a user can control his/her local Windows User account from my app i.e. creating user, set/remove password, change password and also invoking password expiration policy is possible from my app. Now, at this point, I need to figure out If user wants to change his password at next login, then what happens. As many forums and blogs say about this, I did coding accordingly:
Invoke Password Expire at Next Login
``` public bool InvokePasswordExpiredPolicy()
{
try
{
string path = GetDirectoryPath();
string attribute = "PasswordExpired";
DirectoryEntry de = new DirectoryEntry(path);
de.RefreshCache(new string[] { attribute });
if(de.Properties.Contains("PasswordExpired"))
de.Properties[attribute].Value = 1;
de.CommitChanges();
return true;
}
catch (Exception)
{
return false;
}
}
```
Provoke Password Expire at Next Login. Reset the flag
```public bool ProvokePasswordExpiredPolicy()
{
try
{
string path = GetDirectoryPath();
string attribute = "PasswordExpired";
DirectoryEntry de = new DirectoryEntry(path);
de.RefreshCache(new string[] { attribute });
de.Properties[attribute].Value = -1;
de.CommitChanges();
return true;
}
catch (Exception)
{
return false;
}
}
```
Checking for whether concerned flag is set or not
```public bool isPasswordPolicyInvoked()
{
try
{
string path = GetDirectoryPath();
string attribute = "PasswordExpired";
DirectoryEntry de = new DirectoryEntry(path);
de.RefreshCache(new string[] { attribute });
int value = Convert.ToInt32(de.Properties[attribute].Value);
if (value == 1)
return true;
else
return false;
}
catch (Exception)
{
return false;
}
}
```
I am using WinNT to get the directory path rather than LDAP. I used the following method to get the directory path.
```private String GetDirectoryPath()
{
String uName = this.userName;
String mName = this.userMachine;
String directoryPath = "WinNT://" + mName + "/" + uName;
return directoryPath;
}
```
is there anything I am missing? Help me out here.
Note: Firstly, I used pwdLastSet attribute to be set to 0(for on) and -1(for off) that throws an exception "Directory Property Not found in Property Cache", later I discovered that WinNT doesn't support this attribute rather it supports PasswordExpired which needs to be 1 to set the flag. That's what I did.
Here is another answer: How about using System.DirectoryServices.AccountManagement instead, in which case you can call the following code:
```UserPrincipal.Current.ExpirePasswordNow();
```
Comment for this answer: What does it do? When you set a temporary password, does it ask the user to change it when they login with the tempory password?
Here is another answer: The code below should work:
```de.Properties["pwdLastSet"][0] = 0;
```
From User Must Change Password at Next Logon (LDAP Provider):
```
To force a user to change their password at next logon, set the pwdLastSet attribute to zero (0). To remove this requirement, set the pwdLastSet attribute to -1. The pwdLastSet attribute cannot be set to any other value except by the system.
```
Here is another answer: I tracked this down. This corresponds to the ```UserPrincipal.LastPasswordSet``` property.
The property is read only so you have to set using these methods:
``` public bool UserMustChangePasswordNextLogon
{
get
{
return (_userPrincipal.LastPasswordSet == null);
}
set
{
if (value)
_userPrincipal.ExpirePasswordNow();
else
_userPrincipal.RefreshExpiredPassword();
}
}
```
In my case I set variables to expire or refresh the password on next save instead of in the property setter.
|
Title: Inline function(C++) is efficient, why don't we define every function as inline function?
Tags: c++
Question: In line function is quite efficient, so I was confused why don't we define every function as inline funciton?
Comment: In modern compilers, inline has nothing to do with efficiency.
Comment: Take a look at http://stackoverflow.com/questions/1932311/ or maybe http://stackoverflow.com/questions/3999806
Comment: Inlining functions doesn't always inject their code into the call site, and it's not all sunshine and roses, anyway. See [this question](http://stackoverflow.com/questions/145838/benefits-of-inline-functions-in-c), specifically the [second answer](http://stackoverflow.com/a/145952/4892076). Declaring a function `inline` is more about linkage than code generation these days, as well.
Here is the accepted answer: Apart from the call overhead I would mention that pasting the code allows the compiler to make further optimization at call site.
There are few cases in which is impossible to inline:
Procedures linked from shared objects
callback function that are invoked using function pointers
recursive function (non tail recursive) i.e. (function call don't need to hang waiting for the recursive call to return)(can be easily and automatically converted to an iterative form)
Inlining also affects dimension of the executable that end up in more disk usage and longer load time.
Here is another answer: Marking every function inline will not make your functions inline its totally dependent on compiler! sometimes it may inline sometimes it may not. Also inling will not get you any befinites if it involves a loop.
|
Title: var_export with multiple variables of the same name
Tags: php
Question: If I have this, simplified:
```<?php
$image='henry.jpg';
$name='henry';
echo '<img src="'.$image.'"/><p>'.$name.'</p>;
?>
Some other code
<?php
$image='walter.jpg';
$name='walter';
echo '<img src="'.$image.'"/><p>'.$name.'</p>;
?>
```
I want to convert ```$image``` and ```$name``` into an associative array. Using ```$arr = compact('image', 'name');``` and ```var_export``` only creates an array for walter thusly
```array ( 'image' => 'walter.jpg', 'name' => 'walter', )```.
Desired output should be
```array (
'image' => 'henry.jpg', 'name' => 'henry',
'image' => 'walter.jpg', 'name' => 'walter',
)```
How do I achieved this? I have tried ```foreach``` but it only duplicates ```walter```.
Here is the accepted answer: You can't achieve the exact result you want as that would require having an array with multiple identical keys. However you can generate an array of arrays instead by changing your code slightly:
```$image='henry.jpg';
$name='henry';
$arr[] = compact('image', 'name');
$image='walter.jpg';
$name='walter';
$arr[] = compact('image', 'name');
print_r($arr);
```
Output:
```Array (
[0] => Array (
[image] => henry.jpg
[name] => henry
)
[1] => Array (
[image] => walter.jpg
[name] => walter
)
)
```
Demo on 3v4l.org
Comment for this answer: All right, I can work with that. Thank you for the knowledge. It's certainly a time-saver.
|
Title: How to convert extended ascii characters from char to wstring in c++
Tags: c++;unicode;wstring
Question: I read a file using ifstream's read method into a char* memory block. I call my GetChar method on each char in the memory block to write to a wstring. I am trying to write the unicode characters to the screen (at least I think they are unicode, please correct me if I am wrong - oh no it looks like I was wrong its extended ascii). Unfortunately the only way I've got it to work is to hard code the unicode characters in a switch statement, but I'd rather it work for any character, not just the ones I've encountered and added by hard coding them.
Here is what I'm currently using:
```st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16wstring GetChar(char o)
{
switch (o)
{
case 0x0D:
return L"♪";
case 0x0A:
return L"◙";
case -38:
return L"┌";
case -60:
return L"─";
case -77:
return L"│";
case -65:
return L"┐";
case -61:
return L"├";
case -76:
return L"┤";
case -2:
return L"■";
}
st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16wstring tmp_string(1, o);
return tmp_string;
}
```
Any idea how to convert -38 to L"┌" in a generic way?
[Edit] I discovered that my mappings are actually extended ascii!, see the webpage https://www.sciencebuddies.org/science-fair-projects/references/ascii-table
I think what I will try is to create a txt file with extended ascii mapping based on this webpage: https://theasciicode.com.ar/ Is there is a simpler programmatic way (eg with setlocale)?
Comment: There is no such thing as "Extended ASCII", really. Chars outside of standard ASCII (0-127) are *locale-dependant*. What you need is a Unicode library that understands **codepages** or **charsets**. The site you linked to says the "Extended" characters are in [**codepage 437**](https://en.wikipedia.org/wiki/Code_page_437) (aka "DOS Latin US", "DOS OEM US", "IBM437"), which encodes `┌` (U+250C) as byte 0xDA (-38), `─` (U+2500) as byte 0xC4 (-60), etc (FYI, other similar DOS codepages encode those characters in the same way). Most popular Unicode libraries (iconv, ICU, etc) handle that charset.
Comment: The C++ go-to library for all matters Unicode is [ICU](https://icu.unicode.org/) (at least until we finally get full Unicode support in the standard, which I was told *might* happen in C++23).
Here is another answer: You could use a st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16map<char,wstring>.
```wstring ConvertChar (const char target)
{
static const st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16map<char, wstring> convert = {{38,L"┌"}, {76, L"┤"} ....
auto target = convert.find(target);
if (target != convert.end())
return *target;
return L" ";// NOT found
}
```
Or there are functions that do the conversion between char and wide. see How to convert char* to wchar_t*?
Comment for this answer: I thought you wanted a non-standard mapping. The function above should work then, you can use that to map A => Z if you really wanted to :)
You could populate the map from a file as well.
Comment for this answer: I tried the char* to wchar_t* link, but it doesn't work for my case (I could try again though). I suppose I could also store the mappings in an external unicode text file that users could add missing items too. I might even be able to use a mapping table on the web to programatically generate the text file. I found this page Ú is 0xDA https://unicodelookup.com/#latin/1, not ┌, so maybe what I am looking for isn't standard unicode (I can convert to Ú). Anyway thanks for your help, I'm closer to a solution now.
Here is another answer: I got a solution I am happy with. I wrote a key file containing bytes 00 to FF, then I viewed the file with eXtreme (no longer exists) which could show the extended ascii values which I then copied into Notepad++ and saved as unicode values file. I then had mapping for 0x00 to 0xFF to their nice looking extended ascii characters (saved as unicode) all displaying well as wstrings (no hard coded values). I may want to support regular unicode too some day as another mode, but extended ascii is good enough for the files I'm currently working with.
Here is an archived version of eXtreme if anyone needs it: http://members.iinet.net.au/~bertdb/ryan/eXtreme/
|
Title: Importing a test helper into global namespace
Tags: typescript;mocha.js;typescript2.0
Question: I want to define a test helper -- ```test-helper.ts``` -- which sets up with global set of test file dependencies and later will also add some utility functions. Something like this:
```import 'mocha';
import * as chai from 'chai';
import * as Promise from "bluebird";
import './testing/test-console'; // TS declaration
import '../src/shared/base-defs';
import { stdout, stderr } from 'test-console';
const expect = chai.expect;
function prepareEnv(env) { ... }
```
In the test file ```test-spec.ts``` I'd like to import the helper file with something like:
```import 'test-helper';
declare('my tests', () => { ... }
```
and have the mocha, chai, and other globally loaded dependencies loaded into the global namespace for the test file. Is this possible? I'd also like to be able to have my helper functions like ```prepareEnv()``` available ... either in the global namespace or maybe more ideally in a helper namespace. Maybe I can use something like the following to achieve this last part?
```declare namespace Helpers { ... }
```
and put the function into it?
added
It would be appear functions can not be implemented in ambient contexts so my idea about declaring a namespace should be ignored. Instead I am importing a ```test-functions.ts``` in the ```test-helper.ts``` file:
```import * as helpers from './testing/test-functions.ts';
```
That's probably a step in the right direction but the main problem remains which is keeping the ambient/global declarations in the ```test-helper.ts``` file available to test files like ```test-spec.ts```;
Here is the accepted answer: You need to do global augmentation in this case:
https://www.typescriptlang.org/docs/handbook/declaration-merging.html
But in general, get away from namespacing! :)
|
Title: fetchWsapiRecords error: communication failure"
Tags: rally
Question: I have custom list with Deep Export app from Community App in Rally. When I am trying to export the data from Rally.
Most of the time, I am get the error:
```
fetchWsapiRecords error: communication failure
```
And not able to export the project data. I tried after cleaning up the cache. But couldn't. Does anyone know why this wouldn't be successful?
Comment: I agree that there isn't much information to go on but based on a similar error I can tell you this much. Removing "Project" like many people say has no value whatsoever for us. What we found by running the code in a debugger was that the setting "childCountTarget" can be increased to something like "childCountTarget=500" for example and that fixed our issue. To find this click the gear and select "Settings" then do a control F and type in the chilcCountTarget. You will find the setting quickly. The limitation this set was the number of child records that could be returned. Not knowing the iss
Comment: What have you tried so far? It is much easier to help you if we can make suggestions to your code rather than guess what might be going on. Read [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) and try to improve your question to get help.
Here is another answer: Unfortunately this isn't enough information to really debug the problem. Can you include some error information from the console? Or any errors in network requests?
|
Title: Downloading file stops just before finish - caused by Content Length in response header
Tags: java;jakarta-ee;download
Question: The following code is used to prepare a file to be downloaded:
```File downloadFile = new File(ftpPath + File.separator + company.toLowerCase() + File.separator + "download" + File.separator + paramFileName);
FileInputStream fis = new FileInputStream(downloadFile);
BufferedInputStream bis = new BufferedInputStream(fis);
response.setContentType("binary");
response.setHeader("Content-Disposition", "attachment; filename="+paramFileName);
response.setHeader("Content-Length",String.valueOf(downloadFile.length()));
response.setHeader("Content-Encoding", "utf-8");
ServletOutputStream sos = response.getOutputStream();
IOUtils.copy(bis, sos);
sos.flush();
fis.close();
bis.close();
sos.close();
```
When a file is clicked and downloaded, while the total file size is correctly visible in the download progress bar, the file never actually finishes downloading. For large files, it gets about 95%+ of the way there and then stops completely. For smaller files, the results are less consistent, but the file never finishes downloading in it's entirety.
If I remove the following lines, the file does completely download:
```/*
response.setHeader("Content-Length",String.valueOf(downloadFile.length()));
response.setHeader("Content-Encoding", "utf-8");
*/
```
However, the total file size is not given when the file begins downloading. This is very inconvenient for our users, who may be downloading a large file and would like to know an approximate "time to completion" number.
Is there a fix which will allow the file to completely download and also give an accurate indication of the file size?
Thanks for the help
Note: Got rid of DataInputStream as it was never used.
|
Title: Django listview capture value from url then pass to template
Tags: django
Question: I captures value from url using
```def get_queryset(self):
name= self.request.GET.get('name')
```
Now want to pass this varible to template. Just like:
your have searched: {{ name }}
Comment: This is *not* what should be implemented in the `get_queryset` function.
Comment: I don't see why you do that in `get_queryset`. That's for, well, getting a queryset. You should do this in `get_context_data` and add it to the context dict there.
Here is the accepted answer: In a class-based view, the ```get_queryset``` is used to - like the name suggests - construct a queryset of objects, for example in a ```ListView``` this queryset is than passed to the template such that one can render the items in the queryset.
Here you want to add something to the context dictionary, in that case you need to patch the ```get_context_data``` [Django-doc] function, so:
```def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['name'] = self.request.GET.get('name')
return context```
Note that you should return a dictionary, so here we alter the dictionary that we obtain from a super call. Calling the ```super().get_context_data(..)``` method is not required, you could for example return a dictionary with only the attributes you want. But it is typically not good design, since a view typically already adds a lot of data to the context dictionary, and now you can no longer use that in the template.
Here is another answer: Use this
```def get_context_data(self, **kwargs):
name = self.request.GET.get('name')
context = super().get_context_data(**kwargs)
context["name"] = name
return context
```
now the name variable is available in template
in template you can use {{name}}
|
Title: how to increase return size of yahoo related Suggestions php
Tags: php;api;yahoo
Question: I have this code that will return keyword suggestion from yahoo using the api.
```function suggestion($keyword,$keyid){
$search_key= str_replace(' ','+',$keyword);
$app ="D4FRJzjeHUCoJsYIeYV4E6XFUlJpX.o1TWALuI-";
$search = "http://search.yahooapis.com/WebSearchService/V1/relatedSuggestion?appid=".$app."&query=".$search_key."&output=json";
$content= file_get_contents($search);
$json = json_decode($content);
foreach($json->ResultSet->Result as $string){
//insert to database
echo $string."<br />";
}
}
```
but it only return 4 keyword suggestion.
I tried adding &results=30 in the search, but no luck it still return 4 keyword suggestion only.
Thanks a lot.
Comment: This sounds like something to look for in the yahoo API documentation
Here is the accepted answer: read the docs, http://developer.yahoo.com/search/web/V1/relatedSuggestion.html
its being shut down in a month, why bother using it now.
|
Title: How to find what is causing a 502 Bad Gateway nginx Ubuntu
Tags: node.js;angular;ubuntu;nginx
Question: I'm trying to deploy my app which using nodejs and angular. Everything looks fine on
```sudo pm2 logs.
```
I have also done
```sudo nginx -t
```
Nginx is ok and successful.
However when I look at the error.logs from nginx directory, I have this.
I then when to this link here Nginx error "1024 worker_connections are not enough"
I changed it to 1500 worker connections and I'm still in the same spot. Is there another way around this? Please help, I have been trying to deploy this website for over a week. Thank you for your time.
Comment: can you post the client code too?
Comment: Only the worker connections. I don't see that in the nginx.conf where I updated the worker connections.
Comment: have you updated ulimit value aswell?
|
Title: Creating Controllers in ROR for MYSQL tables
Tags: mysql;ruby-on-rails
Question: I have created a new MySQL DB app through ruby console giving below command
```rails new -demo -d mysql
```
Then I created 1 table through MySQL editor. In Ruby Console I started rails server and its working fine (checked localhost:3000). Now I am unable to create controller class for this table. I tried many commands given on net but nothing seems to be working.
From Ruby command console I switched to rails console giving below command
```rails console
```
Then I entered below command to create controller class which in turn returned nil
```irb(main):003:0> class CategoryController < ApplicationController
irb(main):004:1> def index
irb(main):005:2> end
irb(main):006:1> def show
irb(main):007:2> end
irb(main):008:1> end
=> nil
```
But no such class got created in app/controller folder of my application.
I read couple of tutorials and it was referred that controller classes gets automatically created in rails. I tried those too but they didn't run.
I am not sure if I am missing something. Could someone please help to guide further steps. I am using ROR only on server side. My Android app will be using this DB.
It will be really helpful if somebody can provide relevant Beginner tutorial or sample examples using ROR for server side coding with MySQL.
Thanks.
Comment: What book or site are you learning from? I would suggest working through the [Rails Tutorial](http://ruby.railstutorial.org) which is a great help to a newcomer to Rails.
Comment: Thanks Bert for link.
Here is the accepted answer: The Rails console is used to test code at runtime, not to generate code which is actually stored in files to be used again. The correct way to generate a controller is via the ```rails generate controller``` command from your system's command line (not from the Rails console or ```irb```):
This will create your ```CategoryController``` file with two actions, ```index, show```. You may omit those actions or add additional actions.
```rails generate controller CategoryController index show
```
This will result in output similar to what's below, assuming all your gem dependencies are correctly met.
``` create app/controllers/category_controller_controller.rb
route get "category_controller/show"
route get "category_controller/index"
invoke erb
create app/views/category_controller
create app/views/category_controller/index.html.erb
create app/views/category_controller/show.html.erb
invoke test_unit
create test/controllers/category_controller_controller_test.rb
invoke helper
create app/helpers/category_controller_helper.rb
invoke test_unit
create test/helpers/category_controller_helper_test.rb
invoke assets
invoke js
create app/assets/javascripts/category_controller.js
invoke scss
create app/assets/stylesheets/category_controller.css.scss
```
Comment for this answer: Thanks a ton. I struggled for almost 5-6 hours before posting here. I guess it worked now. Ran the command and got o/p. Thanks again.
|
Title: Bash script exiting when repeated in double click execution
Tags: command-line;bash;scripts
Question: This is my code
```#!/bin/bash
function boo {
function goo {
echo "Please enter name"
read name;
echo "Hello $name"
}
function xoo {
echo "Please enter number"
read numl;
echo "$numl"
}
read -p "`echo $'\n> \n>'` Name N or Number S`echo $'\n> \n>'`" var
if [[ $var =~ [nN](es)* ]]
then
goo
elif [[ $var =~ [sS](es)* ]]
then
xoo
fi
}
boo
read -p "`echo $'\n> \n>'` To Repeat press Y`echo $'\n> \n>'`" prompt
if [[ $prompt =~ [yY](es)* ]]
then
boo
else
echo""
fi
```
Initially I am able to successfully run this script by double clicking but when I tried to repeat it its exiting
```>
> Name N or Number S
>
>n
Please enter name
john
Hello john
>
> To Repeat press Y
>
>y
>
> Name N or Number S
>
>n
Please enter name
ajay
```
I am able to print hello john but when i enter ajay its exiting. Any idea whats happening
Here is the accepted answer: Your problem is the ```if…then```. After the first call off ```boo``` you check the value of ```prompt``` and ```boo``` will be started, if ```prompt``` is ```y```. After that, there is no more code to execute and the script exits.
Using this script
```#!/bin/bash
function boo {
function goo {
echo "Please enter name"
read -r name;
echo "Hello $name"
}
function xoo {
echo "Please enter number"
read -r numl;
echo "$numl"
}
read -rep $'\n> \n> Name N or Number S \n> \n> ' var
if [[ $var =~ [nN](es)* ]]; then
goo
elif [[ $var =~ [sS](es)* ]]; then
xoo
fi
}
while true; do
boo
read -rep $'\n> \n> To Repeat press Y \n> \n> ' prompt
if [[ ! $prompt =~ [yY](es)* ]]; then
break
fi
done
exit 0
```
Example
```% ./foo
>
> Name N or Number S
>
> N
Please enter name
abc
Hello abc
>
> To Repeat press Y
>
> y
>
> Name N or Number S
>
> N
Please enter name
def
Hello def
>
> To Repeat press Y
>
> y
>
> Name N or Number S
>
> N
Please enter name
jjj
Hello jjj
>
> To Repeat press Y
>
> n
%
```
Comment for this answer: Thanks it worked but can you tell me where i made the mistake. why **read -r** , **read -rep** and while loop
|
Title: How to pass configuration file that hosted in HDFS to Spark Application?
Tags: apache-spark;hadoop;configuration;apache-spark-sql;spark-structured-streaming
Question: I'm working with Spark Structured Streaming. Also, I'm working with ```Scala```. I want to pass config file to my spark application. This configuration file hosted in ```HDFS```. For example;
spark_job.conf (HOCON)
```spark {
appName: "",
master: "",
shuffle.size: 4
etc..
}
kafkaSource {
servers: "",
topic: "",
etc..
}
redisSink {
host: "",
port: 999,
timeout: 2000,
checkpointLocation: "hdfs location",
etc..
}
```
How can I pass it to Spark Application? How can I read this file(```hosted HDFS```) in Spark?
Comment: I've seen this solution. But I'm looking other ways. Because this way isn't seen good to me. Also, I'm using Scala.
Comment: Because, this solution uses hadoop configuration files. My code have not "hadoop conf" files. Also, I want to pass any "spark conf" to application like appName etc. Thus I can't use spark.sparkContext.hadoopConfiguration. I don't know how can I do this.
Comment: I'm using typesafe api. I think you are right. The only way is seems this(read file from hdfs in the each worker node) for now.
Comment: Does https://stackoverflow.com/questions/17072543/reading-hdfs-and-local-files-in-java help?
Comment: There's also an equivalent Scala API. If for whatever reason you don't want to do it that way, you should explain why not.
Comment: If you don't want to read your data into a Hadoop Configuration object, https://github.com/lightbend/config is a popular generic HOCON configuration reader. You still need to read the file using the Scala HDFS API.
Comment: It is Serializable, so you can read the config once in the driver and have it passed to the task nodes.
Here is the accepted answer: You can read the HOCON config from HDFS in the following way:
```import com.typesafe.config.{Config, ConfigFactory}
import java.io.InputStreamReader
import java.net.URI
import org.apache.hadoop.fs.{FileSystem, Path}
import org.apache.hadoop.conf.Configuration
val hdfs: FileSystem = FileSystem.get(new URI("hdfs://"), new Configuration())
val reader = new InputStreamReader(hdfs.open(new Path("/path/to/conf/on/hdfs")))
val conf: Config = ConfigFactory.parseReader(reader)
```
You can also pass the URI of your namenode to the ```FileSystem.get(new URI("your_uri_here"))``` and the code will still read your configuration.
Comment for this answer: In the `new Path("/path/to/conf/on/hdfs")`, should address be the `hdfs://path/to/conf` or just `path/to/conf` ? Also, thank you so much!
Comment for this answer: typo in import com.typesafe.config.{Cofig, ConfigFactory} .. should be "Config". This was too small of a change to edit in the post
Comment for this answer: only the path on hdfs without the `hdfs://` prefix. e.g /user/a-better-world/conf/spark_job.conf
|
Title: Change owner in a case insert trigger does not run from Community
Tags: trigger;community;lightning-community;guest-user
Question: I have a lightning component in a community that inserts a new case.
The case object has a before-insert trigger that changes the case ownerId.
I get an error ```INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY``` when this code runs from the community context (the community guest user).
I believe that this error is because I need read access on the User object which I cannot give the community guest user.
This is my trigger code (for an example):
```trigger Case_Trigger on Case (before insert, before update, after insert, after update) {
if (Trigger.isBefore && Trigger.isInsert) {
Trigger.new[0].OwnerId= 'myUserId';
}
}
```
Question
If there a way to give acees to the community guest user (or profile) for changing the ownerId of a case?
Comment: Then why not you are using assignment rule
Comment: Actually the case trigger is very very big with a lot of code inside. This ownership change is a very specific case which I need to change the ownership via code in the trigger
Comment: I'm afraid that you can do in same record which part of trigger.new; create a new instance like Case c = new Case(Id=trigger.new[0].Id, OwnerId='005....'); and update it. mind recursion.
Comment: But I do not want to create another case - this will trigger a lot of other stuff for me and is not something I want or need to deal with - it is not an option for me. But I do ask - this is not possible to do?
Comment: It iwll not create another case, it will update
Comment: I have tried that, I get an error: `UNABLE_TO_LOCK_ROW, unable to obtain exclusive access to this record`. also I don't understand this solution - how can I update a record from within the `before insert` trigger of this record. Anyway - I cannot get this working.
|
Title: How to change value of datagridview based on cell value
Tags: c#;sql;.net;ms-access
Question: i am fetching data from access table in datagridview. Access table have one lookup column.
so when i fetch table in datagridview it is showing the value in numbers.
i want to get lookup value in datagridview not numbers.
should i use some conditional formatting for is there any other way to do that.
Comment: nothing i am not sure how to do that
Here is another answer: Do not use lookup fields in table design. They only create the kind of problems that you are running into. Use a SQL statement or query as your datasource.
```Select T1.*, T2.DescriptionField FROM Table1 AS T1 INNER JOIN
TABLE2 AS T2 ON T1.LookupField = T2.LookupField
```
|
Title: Joomla textarea replaces newlines with __ (2 underscores)
Tags: model-view-controller;joomla;textarea;fieldset
Question: Good day to you all,
I am not exactly a Joomla Expert. Afters hours of searching the net for an answer, i decided to try it here.
I am writing a simple Joomla component. In the view part I have a view called 'information'. I want in the backend that the administrator can add some text.
This is how the default.xml looks like:
```<?xml version="1.0" encoding="utf-8"?>
<metadata>
<layout title="Informationform">
<message>
<![CDATA[Informationform]]>
</message>
</layout>
<fields name="request">
<fieldset name="request" label="Contactform Properties">
<field name="templatename" type="text" label="E-mail-templatename"></field>
<field name="extracss" type="textarea" rows="8" cols="40" filter="raw" label="Extra CSS"></field>
</fieldset>
</fields>
</metadata>
```
In the backend I can add the contact form as a menutitem. On the rightside I can edit my extra fields.
After I input some lines of text in the textarea and saved the menu-item. All newline-characters are replaced by __ (2 underscores).
Original text:
```This is an example
text.
As you can see there
are multiple lines.
```
After saving the text:
```This is an example__text.__As you can see there__are multiple lines.
```
Does anybody know how to solve this?
Comment: How are you making the line breaks?
Comment: I suspect it is doing \r\n and that is getting stripped out by the input filters. How about using instead?
Comment: Thats simple. Behind my keyboard I hit the enter-key, inside the text area.
|
Title: How to get data from a table by entity class name using Spring Data JPA
Tags: spring;spring-data-jpa
Question: I have a base entity class ```BaseDictionary```:
```@Entity
@Inheritance
public abstract class BaseDictionary {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Long id;
@Column(name = "code")
protected String code;
@Column(name = "is_enabled")
protected Boolean enabled = true;
}
```
any child classes
```@Entity
@Table(name = DB.DIC_RIGHTS_TYPE, schema = DB.SCHEMA_DIC)
public class DicRightsType extends BaseDictionary {}
@Entity
@Table(name = DB.DIC_ROLES_TYPE, schema = DB.SCHEMA_DIC)
public class DicRolesType extends BaseDictionary {}
```
There are many child classes like this.
Given an entity class name like ```DicRightsType``` I would like to get data from the table associated with the entity of that name. How is it possible to implement?
I wanted to use JPA repositories like this: Using generics in Spring Data JPA repositories but this does not suit my case because I only have the name of the entity class at runtime and do not know how to create a dynamic repository for the class.
Here is the accepted answer: You can write your own ```JpaRepository``` implementation to achieve this.
```
Step 1: A repository registry
```
```class RepositoryRegistrar {
private static final Map<Class<T>, Repository<T, Serializable>> DICTIONARY = new HashMap<>();
public static void register(Class<T> entityClass, Repository<T, Serializable> repository) {
DICTIONARY.put(entityClass, repository);
}
public static Repository<T, Serializable> get(Class<T> entityClass) {
return DICTIONARY.get(entityClass);
}
}
```
```
Step 2: Custom ```JpaRepository``` implementation to populate the registry
```
```@NoRepositoryBean
class RegisteringJpaRepository<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> {
public RegisteringJpaRepository(JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager) {{
super(entityInformation, entityManager);
RepositoryRegistrar.register(entityInformation.getJavaType(), this);
}
}
```
You will have to tweak the configuration to use your custom implementation. Details for this are provided in the Spring Data JPA documentation.
```
Step 3: Obtain repository references from the registrar
```
```Repository<?, ?> getRepository(String entityClassName) {
return RepositoryRegistrar.get(Class.forName(entityClassName));
}
```
|
Title: Embed HTML to render a simple browser inside swf with StageWebView
Tags: actionscript-3;flash
Question: I found a way to do this and it works when tested in Flash (Control+Enter).
But when I export movie clip as swf, the file size is only 2k and doesn't open with Acrobat Reader. This seems to be the best way for me, because then I want to insert the swf in a pdf file. My final intention is basically to have both a youtube playlist and a Facebook comment box embeded inside the pdf.
I'm using Flash CS6 and pasted this code:
```import flash.display.MovieClip;
import flash.media.StageWebView;
import flash.geom.Rectangle;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.desktop.NativeApplication;
//This will return the actual width value of our stage
var wView:int = stage.stageWidth;
//This will return the actual height value of our stage
var hView:int = stage.stageHeight;
//Create a new StageWebView object
var swv:StageWebView = new StageWebView();
//Set the size of StageWebView object created to match the screen size
swv.viewPort = new Rectangle(0,0,wView,hView);
//Load the Google Page
swv.loadURL("https://www.google.com/");
//Show the StageWebView Object
//If you want to hide it, set the stage property to null
swv.stage = this.stage;
```
Comment: StageWebView is only available for AIR runtime.
Comment: ooh... but will I be able to bring it into a pdf though?
|
Title: How to implement where condition in one-to-one relationship
Tags: hibernate;jpa
Question: I am trying to implement the below 'example' query in JPA. It is a ONE-TO-ONE relationship.
select * from Person person, Age age where person.age between age.minAge and age.maxAge
In my real project, i have multiple Where conditions like this and i want to know the most effective way of achieving the same using annotations.
Thanks in advance.
```@Entity
@Table(name = "PERSON")
public class Person
{
@Column(name = "NAME", nullable = false, precision = 0)
private String name;
@Column(name = "ADDRESS", nullable = false, precision = 0)
private String address;
@Column(name = "AGE", nullable = false, precision = 0)
private int age;
private BMIForAge bmi_age;
**@OneToOne(optional = false, fetch = FetchType.EAGER)
public BMIForAge getBmi_age() {
return bmi_age;
}
public void setBmi_age(BMIForAge bmi_age) {
this.bmi_age = bmi_age;
}**
}
@Entity
@Table(name = "BMI_FOR_AGE")
public class BMIForAge
{
@Column(name = "MIN_AGE", nullable = false, precision = 0)
private int minAge;
@Column(name = "MAX_AGE", nullable = false, precision = 0)
private int maxAge;
@Column(name = "BMI", nullable = false, precision = 0)
private int bmi;
...
}
```
Comment: Thanks Billy. What if the "WHERE" is needed to achieve the actual mapping, in my case one-to-one. Lets say Person and BMIForAge shares 2 foreign keys but that doesn't make it one to one until there a where condition is added .
person.id_1 = bmi_age.id_1 and
person.id_2 = bmi_age.id_2 and
person.age between bmi_age.minAge and bmi_age.maxAge
Can you please tell how can i achieve this ?
Comment: its not primary key, both entities just happen to share couple columns. I don't have control over the data model at this point. should i treat them as separate entities and not use mapping all together? In short using where or mapping or other mechanisms how do i achieve person.id_1 = bmi_age.id_1 and person.id_2 = bmi_age.id_2 and person.age between bmi_age.minAge and bmi_age.maxAge.
Comment: My actual entities have @Id's (plain sequence no's)
Comment: My named query generates query like: select person from PERSON person inner join BMI_FOR_AGE age on person.c_1=age.c_1 and person.c_2=age.c_2 where (person.AGE between bmi_age.MIN_AGE and bmi_age.MAX_AGE) which is correct and executing perfectly in DB2 but i get this error too: HibernateException: More than one row with the given identifier was found
Comment: A query imposes a WHERE condition. A mapping imposes relations. Define what you are asking, because you don't define a WHERE clause "using annotations"
Comment: you mean one of the sides of the relation has a composite PK? Still no need for a "WHERE" condition. Update your post with the EXACT situation you are referring to ... which at the moment it has entities with no `@Id` fields
Here is another answer: With JPQL, you would have something like:
```select p from Person p join p.bmi_age b where p.age between b.minAge and b.maxAge;
```
|
Title: ABRecordRef vCard
Tags: iphone;objective-c;ios;abaddressbook;vcf-vcard
Question: I would like to convert a ```ABRecordRef``` into an ```vCard``` or ```NSData``` to transmit it via Bluetooth. I've run into your question and I wonder if you were able to figure out how to do it.
Thank you
Here is another answer: Is very easy, I'm working with iOS 6 and I done with the following code:
```ABRecordRef person = (__bridge ABRecordRef)[_ABRecordCards objectAtIndex:0];
ABRecordRef people[1];
people[0] = person;
CFArrayRef peopleArray = CFArrayCreate(NULL, (void *)people, 1, &kCFTypeArrayCallBacks);
NSData *vCardData = CFBridgingRelease(ABPersonCreateVCardRepresentationWithPeople(peopleArray));
NSString *vCard = [[NSString alloc] initWithData:vCardData encoding:NSUTF8StringEncoding];
NSLog(@"vCard > %@", vCard);
```
I have a ```NSArray``` with ```ABRecordRef``` elements...
Comment for this answer: No need for temporary ABRecordRef array. You can just use CFArrayRef peopleArray = CFArrayCreate(NULL, (void *)&person, 1, &kCFTypeArrayCallBacks);
Comment for this answer: hello can you tell me how can i add all contact in one v card ?
Comment for this answer: yes this is possible and i have one Application and i have to do this after long time !!!
|
Title: How to add a string to both sides of a found substring
Tags: php;regex
Question: I have an input string:
```10 birds have found 5 pears and 6 snakes.
```
How can I put html tags around substrings found with a regular expression?
For instance, I want all numbers to be bold, like this:
``` <b>10</b> birds have found <b>5</b> pears and <b>6</b> snakes.
```
Comment: That's not difficult, have you tried anything?
Comment: preg_replace_callback()
Comment: @LarsStegelitz: this function is not needed `preg_replace` should suffice.
Comment: When you're asking for specific help with debugging something, you need to show what you've tried.
Comment: I have tried, still don't which PHP functions to use. To find the substring is not hard, to put string in front and behind is harder. I tried combination of preg_mach and str_pad() but it wasnt the best solution.
Here is the accepted answer: You can try use ```preg_replace()``` function:
```$str = '10 birds have found 5 pears and 6 snakes.';
echo preg_replace('/(\d+)/', '<b>$1</b>', $str);
```
Output:
```<b>10</b> birds have found <b>5</b> pears and <b>6</b> snakes.
```
Comment for this answer: For god sake. I forgot I can use the found string as variable. That was it. Thanks a lot.
Here is another answer: Without regex you can do that:
```$items = explode(' ', $text);
$result = array_reduce($items, function ($c, $i) {
return ($c ? $c . ' ' : $c)
. (is_numeric($i) ? '<b>' . $i . '</b>' : $i);
});
```
Comment for this answer: @PiotrOlaszewski: Because this way, when it's possible to use it, is 2x faster for this kind of string length.
|
Title: Remove extension when creating a new image from resizing
Tags: php
Question: i have this code, which i kind of modified a little bit ago.. my problem is that this creates a new thumbnail of the image i upload but it adds a .PNG,.JPEG etc etc extension which i don't need! now, my problem is that if i try to remove from the function the extensions it won't let me create the new image...
What i mean is that if i remove : '.'.$this->ext from the createFile function it won't create the file anymore...
Here is the code... it seems to be a little long but it isn't..
```if (!empty($_FILES)) {
function setFile($src = null) {
$this->ext = strtoupper(pathinfo($src, PATHINFO_EXTENSION));
if(is_file($src) && ($this->ext == "JPG" OR $this->ext == "JPEG")) {
$this->img_r = ImageCreateFromJPEG($src);
} elseif(is_file($src) && $this->ext == "PNG") {
$this->img_r = ImageCreateFromPNG($src);
} elseif(is_file($src) && $this->ext == "GIF") {
$this->img_r = ImageCreateFromGIF($src);
}
$this->img_w = imagesx($this->img_r);
$this->img_h = imagesy($this->img_r);
}
function resize($largestSide = 100) {
$width = imagesx($this->img_r);
$height = imagesy($this->img_r);
$newWidth = 0;
$newHeight = 0;
if ($width > $height) {
$newWidth = $largestSide;
$newHeight = $height * ($newWidth / $width);
} else {
$newHeight = $largestSide;
$newWidth = $width * ($newHeight / $height);
}
$this->dst_r = ImageCreateTrueColor($newWidth, $newHeight);
imagecopyresampled($this->dst_r, $this->img_r, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
$this->img_r = $this->dst_r;
$this->img_h = $newHeight;
$this->img_w = $newWidth;
}
function createFile($output_filename = null) {
if ($this->ext == "JPG" OR $this->ext == "JPEG") {
imageJPEG($this->dst_r, $this->uploaddir.$output_filename.'.'.$this->ext, $this->quality);
} elseif($this->ext == "PNG") {
imagePNG($this->dst_r, $this->uploaddir.$output_filename.'.'.$this->ext);
} elseif($this->ext == "GIF") {
imageGIF($this->dst_r, $this->uploaddir.$output_filename.'.'.$this->ext);
}
$this->output = $this->uploaddir.$output_filename.'.'.$this->ext;
}
function setUploadDir($dirname) {
$this->uploaddir = $dirname;
}
function flush() {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
imagedestroy($this->dst_r);
unlink($targetFile);
imagedestroy($this->img_r);
}
}
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
move_uploaded_file ($tempFile, $targetFile);
$image = new Image();
$image->setFile($targetFile);
$image->setUploadDir($targetPath);
$image->resize(800);
$image->createFile($_FILES['Filedata']['name']);
$image->flush();
}
```
Comment: Hey thanks, i'm just modifying it, if i were that capable to build it i wouldn't ask... i mean i understand the logic... but i can't rearrange it the way i need..
Comment: Please don't define functions within an `if` statement. That is a terrible practice, even if it *is* valid PHP.
Comment: BTW you never call any of those functions within the `if` statement; you only define them. That may be why your code isn't working.
Comment: Also, you have an extra close-curly at the end there.
Here is another answer: After formatting your code and removing the extra close-curly at the end (while moving your function definitions outside of your ```if``` statement), your code should look something like this:
```<?php
function setFile($src = null) {
$this->ext = strtoupper(pathinfo($src, PATHINFO_EXTENSION));
if (is_file($src) && ($this->ext == "JPG" OR $this->ext == "JPEG")) {
$this->img_r = ImageCreateFromJPEG($src);
} elseif (is_file($src) && $this->ext == "PNG") {
$this->img_r = ImageCreateFromPNG($src);
} elseif (is_file($src) && $this->ext == "GIF") {
$this->img_r = ImageCreateFromGIF($src);
}
$this->img_w = imagesx($this->img_r);
$this->img_h = imagesy($this->img_r);
}
function resize($largestSide = 100) {
$width = imagesx($this->img_r);
$height = imagesy($this->img_r);
$newWidth = 0;
$newHeight = 0;
if ($width > $height) {
$newWidth = $largestSide;
$newHeight = $height * ($newWidth / $width);
} else {
$newHeight = $largestSide;
$newWidth = $width * ($newHeight / $height);
}
$this->dst_r = ImageCreateTrueColor($newWidth, $newHeight);
imagecopyresampled($this->dst_r, $this->img_r, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
$this->img_r = $this->dst_r;
$this->img_h = $newHeight;
$this->img_w = $newWidth;
}
function createFile($output_filename = null) {
if ($this->ext == "JPG" OR $this->ext == "JPEG") {
imageJPEG($this->dst_r, $this->uploaddir . $output_filename . '.' . $this->ext, $this->quality);
} elseif ($this->ext == "PNG") {
imagePNG($this->dst_r, $this->uploaddir . $output_filename . '.' . $this->ext);
} elseif ($this->ext == "GIF") {
imageGIF($this->dst_r, $this->uploaddir . $output_filename . '.' . $this->ext);
}
$this->output = $this->uploaddir . $output_filename . '.' . $this->ext;
}
function setUploadDir($dirname) {
$this->uploaddir = $dirname;
}
function flush() {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetFile = str_replace('//', '/', $targetPath) . $_FILES['Filedata']['name'];
imagedestroy($this->dst_r);
unlink($targetFile);
imagedestroy($this->img_r);
}
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetFile = str_replace('//', '/', $targetPath) . $_FILES['Filedata']['name'];
move_uploaded_file($tempFile, $targetFile);
$image = new Image();
$image->setFile($targetFile);
$image->setUploadDir($targetPath);
$image->resize(800);
$image->createFile($_FILES['Filedata']['name']);
$image->flush();
}
```
This still will not work because you're calling these methods as though they're member functions of an ```Image``` object which isn't defined anywhere. Take a look at Objects and Classes in the PHP manual.
Comment for this answer: Hey thanks for the help, but this is supposed to not add the extension after the files?
Comment for this answer: Hey thanks...well, the code works as it is in fact.. i mean what i needed is just that when the new image is created not to take any extension as it oes for the moment.. but anyways i'm going to take a look again
Comment for this answer: @Al12 This is all your code - I just cleaned it up a bit. Make sure that you're defining an `Image` object as well (you're not doing that here).
|
Title: Git diff - ignore specific texts per file type
Tags: git;diff;atlassian-sourcetree;git-config
Question: What I am trying to do is to have git ignore specific pieces of text per file type, and store those settings so can be used through out a project.
The issue is that my IDE adds specific lines/text on files, that I would like Git to ignore and not count as changes. For example:
for .xml files, ignore text like this: ```<modified>2019-01-01</modified>```.
for .txt files, ignore text like this: ```"# last comment by" and "sequence:"```
for .properties files, ignore text like this: ```"some text to ignore"```
etc etc
So, using the examples above, if the only change to an .xml file is the ```<modified>``` tag data, git should not consider this as a modified file.
What I would like to do is store those settings in a config file so that can be used though out the project. I am currently using SourceTree so if there is a SourceTree specific solution it would be nice to use but I couldn't find anything.
Comment: Possible duplicate of [Can git ignore a specific line?](https://stackoverflow.com/questions/6557467/can-git-ignore-a-specific-line)
Comment: Possible duplicate of [How to tell git to ignore individual lines, i.e. gitignore for specific lines of code](https://stackoverflow.com/questions/16244969/how-to-tell-git-to-ignore-individual-lines-i-e-gitignore-for-specific-lines-of) or of https://stackoverflow.com/questions/6557467/can-git-ignore-a-specific-line (better)
|
Title: How to change a CACHE variable in cmake file run by -P mode
Tags: caching;cmake
Question: I have a cache variable created with
```set(firmware_version ${FirmwareVersion} CACHE STRING "firmware")
```
and passed this variable to a cmake file with
```COMMAND ${CMAKE_COMMAND} -Dfirmware_version:STRING=${firmware_version} -P "C:/Projekt/Lapp/PDM/Versioning.cmake"
```
Now I am changing this variable in ```Versioning.cmake``` with a variable
```set(firmware_version ${FirmwareVersion} CACHE STRING "firmware" FORCE)
```
But I cannot see the changes made to the variable visible to ```CMakeLists.txt``` file.
I am forcing the reconfigure of the cmake with
```add_custom_target(versioning ALL
DEPENDS version_tag
)
add_custom_command(
OUTPUT version_tag
PRE_BUILD
COMMAND ${CMAKE_COMMAND} -Dfirmware_version:STRING=${firmware_version} -P "C:/Projekt/Lapp/PDM/Versioning.cmake"
)
```
Comment: Putting an absolute path like `C:/Projekt/Lapp/PDM/Versioning.cmake` is a terrible idea. You should instead make it relative to the current source directory like `${CMAKE_CURRENT_SOURCE_DIR}/PDM/Versioning.cmake` (or whatever the actual path is).
Comment: You mentioned "Now I am changing this variable in Versioning.cmake with a variable". The type of `add_custom_command()` being used will only run during pre build, this means if the target is not out of date the command won't run again. You may want to use a custom command that `DEPENDS` on `Versioning.cmake`.
Comment: CMake variables are accessible only during the **configuration** stage, because only this stage is processed by CMake. **Build** stage is controlled by make,nmake or other **build utility**. That is, you cannot change CMake variables when you project is built. The only way for change CMake variables is to re-configure the project.
|
Title: How to create a folder in codeigniter
Tags: php;directory
Question: I am creating a folder with mkdir() in php but I don't know how to create a folder in CodeIgniter. Anyone can tell me how to create that with mkdir() function.
Comment: CodeIgniter _is_ PHP. It's just a framework.
Comment: Does this answer your question? [Codeigniter make directory if not exist](https://stackoverflow.com/questions/16435597/codeigniter-make-directory-if-not-exist)
Comment: follow this link https://stackoverflow.com/a/18217147/10430605
Comment: follow the given link.
https://stackoverflow.com/a/58428797/7327310
perhaps, it will help you.
Comment: @NikhileshAgrawal Actually that's a PHP code...I need to Codeigniter customized code
Here is the accepted answer: You can create a folder using ```mkdir()``` like this ```mkdir($path,0777,true)```.
For example if your codeigniter project structure is like ```C:\xampp\htdocs\Prjects Folder\...``` and you want to create a folder inside assets folder (i.e for images you want to create an Image folder) then you can create it like this.
```if(!is_dir('././assets/images') )
{
mkdir('././assets/images',0777,TRUE);
}
```
Note: To know more about mkdir() check this link https://www.php.net/manual/en/function.mkdir.php
Here is another answer: First add your path using ```realpath``` function which gives you absolute path and then use ```mkdir``` to create folder.
Example:
Here i am store one image within folder because it is not exist so i have to create folder first then i have to add.
```$path = realpath(APPPATH . 'images/test.jpg');
if(!file_exists($path))
{
mkdir($path,0777,TRUE);
}
```
Note: PHP or Codeigniter, we can follow same process to create directory.
|
Title: MVC Form with PartialViewResult on submit, doesn't post the data in the PartialViewResult
Tags: model-view-controller;submit
Question: I am learning mvc and jquery. Requirmeent => There are "Categroies". Each categories can have a list of "Tasks". User should be able to resort the "Tasks" as he wishes by drag-drop and save to the db.
The form that I am working on contains the following
A list of Categories displayed in a element. When the user selects a list item
an ajax request is made to get the list of "Tasks"
A list of Tasks displayed in a list.
A button to save the changes
I am able to implement all of the functionality including displaying categories, getting tasks and resorting. But the Save part is not working. When the form posts, I don't see the data for the Tasks in the FormCollection.
Here is the html.
```@using (Html.BeginForm("Settings", "Settings", FormMethod.Post, new { id = "formSettings" }))
{
<div style="width: 100%; background-color: Aqua; vertical-align: top">
<div style="width: 50%; text-align: right; vertical-align: top; float: left; display: block;
height: 300px;">
<select id="listSettings" name="listSettings" style="width:200px;height:280px;text-align:left;" size="@Model.Categories.Count()" data-tasks="@Url.Action("GetTasks", "Settings", new { })">
@foreach (string category in @Model.Categories)
{
<option title="category" value="@category">@category</option>
}
</select>
</div>
<div id="taskListId" style="display: block; width: 30%; float: left; height: 300px;">
This will be replaced
</div>
</div>
<div style="text-align: center; width: 100%">
<input type="submit" id="btnSubmit" title="Save" value="Save" />
</div>
}
```
The ```<div id="taskListId".../>``` above will be replace by ajax call to the server. Here is the partialviewresult html
```<div id="taskListId" style="display: block; width: 30%; float: left; height: 300px;">
<ul id="sortable" style="height: 280px;">
@foreach (string s in Model)
{
<li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>@s</li>
}
</ul>
</div>
```
When the form is submitted, why is it the FormCollection contain just 1 key "listSettings", but not the "sortable"?
Please let me know if I am doing something wrong.
Thanks,
Ravi.
Here is another answer: I figured a way to do that. Actually form post will not have ```<ul>``` data in it. ```<ul>``` doesn't have a name attribute attached to it. so I wont find in form post data.
I solved the issue by using jquery to find the ```<ul>``` and ```<li>``` items and attaching them as name value pair to the form post data. Then I posted the data using ajax.
|
Title: Is there an editing tool to create a binary PE file in windows?
Tags: reverse-engineering;portable-executable
Question: This answer provided a way to create a binary file in linux, is there such a convenient tool for windows?
Comment: The linker does this. What are you trying to create the binary from?
Comment: No,I need an editing tool to do this.Just to facilitate learning PE.
Here is another answer: You can start from here: http://www.phreedom.org/solar/code/tinype/ , then modify one of the files using a PE editor (e.g. CFF Explorer).
Programmatically, in Python you can use pefile to read/write the PE structure.
Here is another answer: Try LordPE or PEBrowser.
Comment for this answer: It is an error start from scratch a PE. Leave it to the linker. Compile a simple program, open it with a PE Editor and modify all that you want. Check this http://www.woodmann.com/collaborative/tools/index.php/Category:RCE_Tools
Here is another answer: Recompile those tools on windows? Shouldn't be too hard to do against a cygwin or mingw base environment.
|
Title: Unique counter for all foot, side and end notes
Tags: footnotes;counters;endnotes
Question: When used together, as in the MWE, the text might be plagued of identical numbered marks, that is rather confusing.
I want to have marks in this MWE ordered from 1 to 9 instead of three indistinguishable series from 1 to 3.
More clever solutions (using marks of different colors, mixing arabic and roman numbers with alphabetic marks, other that you can imagine ...) are also welcome.
```\documentclass{article}
\usepackage{sidenotes}
\usepackage{endnotes}
\begin{document}
See the sidenote\sidenote{A side note} and the footnote \footnote{A foot note}.
See the sidenote\sidenote{A side note} and the footnote \footnote{A foot note}.
See the endnote\endnote{An end note}. See the endnote\endnote{An end note}.
See the note\sidenote{A side note} (of what type?) and the
note\footnote{A foot note}(what type?) and the note\endnote{An end note}
(where?).
\theendnotes
\end{document}
```
Here is the accepted answer: I'm not so sure it's wise to have three different kinds of notes. This seems to be predestined to confuse readers. Having them all numbered with the same counter seems even more confusing to me: why is number 1 in the margin, number 2 in the footer and number 3 at the end of the section? Is there some pattern to it?
If really all three note types are required the simplest thing to me seems to use different kinds of counter formats:
```\documentclass{article}
% use symbols for footnotes:
\usepackage[symbol]{footmisc}
\usepackage{sidenotes}
% change the sidenote counter format:
\renewcommand*\thesidenote{\alph{sidenote}}
\usepackage{endnotes}
\begin{document}
See the sidenote\sidenote{A side note} and the footnote \footnote{A foot note}.
See the sidenote\sidenote{A side note} and the footnote \footnote{A foot note}.
See the endnote\endnote{An end note}. See the endnote\endnote{An end note}. See
the note\sidenote{A side note} (of what type?) and the note\footnote{A foot note}%
(what type?) and the note\endnote{An end note} (where?).
\theendnotes
\end{document}
```
Comment for this answer: Thanks for your solution. You're absolutely right. It's confusing so many types of notes, but in long documents with many short, medium and long notes (very few words, short sentences and long paragraphs) may make sense to place them respectively as marginal notes, footnotes or endnotes (at least for personal use :D ).
|
Title: Firefox using a dark theme on Vue app for no reason
Tags: vue.js;leaflet;vuetify.js
Question: I have a Vue app that uses Vuetify. When I'm running the development server on MacOS Mojave, the page opens with a dark theme that I certainly didn't put anywhere into the styles. Besides using the dark theme, there are some components missing from the view.
If I open the app in a Firefox private window, I get the light theme and everything works as expected.
I noticed a few items in local storage that seem to be related to this:
No results show in google for the "darky" keys (```darkyMode```, ```darkyState``` and ```darkySupported```). I'm not sure what writes and/or reads these keys and changes the theme to dark.
Other packages I'm using are leaflet and SVGjs.
Comment: I am using Night Eye but I disabled it. I'll try removing.
Comment: It did the trick! Silly of me thinking disabling would be enough.
Comment: Are you using a dark mode plugin for Firefox? Would explain why it doesn't affect the browser in private mode
|
Title: Can jQ assess the code itself and execute based on findings?
Tags: javascript;jquery
Question: Is such function even possible using jQ...
look through code, find all vars/functions which name contains 'blah'
make array of such var names
as the code in each ..._blah var/function is executed, last line of it would declare that the code has been processed, this would then report back to the array matching each corresponding element in array with a 'completed' kind of a value
once all ..._blah var names have been matched (i.e. all code in them has been executed), the function would return 'all ok' and then execute whatever as result
It's kind of like building a custom event listener I guess but listening to the code execution itself
Comment: yes, can it evaluate itself
Comment: By 'the code' do you mean the JavaScript running on the page?
|
Title: Position of a headline in a multicolumn poster using flow/window/frame
Tags: positioning;multicolumn;posters;parcolumns;flowfram
Question: ```
An answer which is sufficient but not optimal OP has been found. Any improvements are welcome.
```
Requirements:
a landscape poster in A3 with four (possibly a different number later) columns,
the headline of the poster on top of the two columns in the middle,
the text of the poster "floating" around the headline box in the regular order ```(1,2,3,4)``` whereas my example has order ```(1,3,4,2)``` (just compare the section titles, the second page is in correct order),
LuaLaTeX compatibility,
if possible: integration as a separate page in a non-poster document of the KOMA-classes (https://ctan.org/pkg/koma-script) after ```\KOMAoptions{paper=A3,paper=landscape,DIV=18,fontsize=11pt,twoside=false}\recalctypearea```. I am aware that I can include a PDF otherwise.
The contents of the poster are not boxes unlike other posters on How to create posters using LaTeX but rather a single text with several sections. So my project might not be a poster in the classical ```TeX``` notion.
The solution does not have to use the package https://ctan.org/pkg/flowfram, but that package is the closest I got (failing requirement 3 and 5).
Other attempts with https://ctan.org/pkg/insbox, https://ctan.org/pkg/cutwin, or https://ctan.org/pkg/picinpar failed, too. This kind of typesetting is used occasionally in newspapers or magazines as well. I could not find a similar question, nor a template with this feature, but I am sure someone must have had this problem before.
```\documentclass[paper=A3,paper=landscape,DIV=18,fontsize=11pt,oneside]{scrartcl}
\usepackage{microtype,tikz,calc,lipsum}
\usepackage{flowfram}
\Ncolumn{4}
\newlength{\windowWidth} \setlength{\windowWidth}{2\columnwidth+1\columnsep}
\newlength{\windowHeight} \setlength{\windowHeight}{8em}
\Ncolumntopinarea[1]{static}{2}{\windowHeight}{\windowWidth}{\flowframeheight{1}}{\columnwidth+\columnsep}{0pt}
\newstaticframe[1]{\windowWidth}{\windowHeight}{\columnwidth+\columnsep}{\textheight-1.14\windowHeight}[headlineWindow]
\setflowframe{2,3}{pages={>1}}
\begin{document}
\begin{staticcontents*}{headlineWindow}
\tikz \fill[yellow] (0,0) rectangle node{\huge\bfseries\color{black}Headline} (\windowWidth,\windowHeight);
\end{staticcontents*}
\noindent\lipsum[1]
\section{foo}\lipsum[1]
\section{foo}\lipsum[1]
\section{foo}\lipsum[1]
\section{foo}\lipsum[1]
\section{foo}\lipsum[1]
\section{foo}\lipsum[1]
\section{foo}\lipsum[1]
\section{foo}\lipsum[1]
\section{foo}\lipsum[1]
\section{foo}\lipsum[1]
\section{foo}\lipsum[1]
\section{foo}\lipsum[1]
\section{foo}\lipsum[1]
\section{foo}\lipsum[1]
\section{foo}\lipsum[1]
\section{foo}\lipsum[1]
\section{foo}\lipsum[1]
\section{foo}\lipsum[1]
\end{document}
```
Honorable mention: Book on a Single (Poster) Page.
Here is the accepted answer: The following code does not satisfy requirement 5, but all other. It manually imitates the multicols by the mechanisms of https://ctan.org/pkg/flowfram. Thus, it lacks many features of the package https://ctan.org/pkg/multicol.
```\documentclass[paper=A3,paper=landscape,DIV=18,fontsize=11pt,oneside]{scrartcl}
\usepackage{microtype,tikz,calc,lipsum,flowfram}
\pagestyle{empty}
%The following loc define lengths for the columns. The first two are manually calculated for 4 columns. An automatic calculation should not be too difficult and is left for the reader.
\setlength{\columnsep}{0.01\textwidth}% this weird definition makes calculations a bit easier than in unit em
\setlength{\columnwidth}{0.2425\textwidth}
\newlength{\columnSepWidth} \setlength{\columnSepWidth}{\columnsep+\columnwidth}
\newlength{\windowWidth} \setlength{\windowWidth}{2\columnSepWidth-\columnsep}
\newlength{\windowHeight} \setlength{\windowHeight}{0.1\textheight}
%The window for the headline which does only appear on the first page
\newstaticframe[1]{\windowWidth}{\windowHeight}{\columnSepWidth}{\textheight-\windowHeight}[headlineWindow]
%The following loc generate the columns. A different number of columns requires manual change.
%The four columns of the first page
\newflowframe[1]{\columnwidth}{\textheight}{0\columnSepWidth}{0pt}
\newflowframe[1]{\columnwidth}{\textheight-\windowHeight-\columnsep}{1\columnSepWidth}{0pt}
\newflowframe[1]{\columnwidth}{\textheight-\windowHeight-\columnsep}{2\columnSepWidth}{0pt}
\newflowframe[1]{\columnwidth}{\textheight}{3\columnSepWidth}{0pt}
%The four columns of all other pages
\newflowframe[>1]{\columnwidth}{\textheight}{0\columnSepWidth}{0pt}
\newflowframe[>1]{\columnwidth}{\textheight}{1\columnSepWidth}{0pt}
\newflowframe[>1]{\columnwidth}{\textheight}{2\columnSepWidth}{0pt}
\newflowframe[>1]{\columnwidth}{\textheight}{3\columnSepWidth}{0pt}
\begin{document}
\begin{staticcontents*}{headlineWindow}
\tikz \fill[yellow] (0,0) rectangle node{\huge\bfseries\color{black}Headline} (\windowWidth,\windowHeight);
\end{staticcontents*}
\sloppy% gives better results in narrow columns, see https://tex.stackexchange.com/a/241355/128553
\noindent\lipsum[1]
\section{foo}\lipsum[1]\lipsum[1]
\section{foo}\lipsum[1]\lipsum[1]
\section{foo}\lipsum[1]\lipsum[1]
\section{foo}\lipsum[1]\lipsum[1]
\section{foo}\lipsum[1]\lipsum[1]
\section{foo}\lipsum[1]\lipsum[1]
\section{foo}\lipsum[1]\lipsum[1]
\section{foo}\lipsum[1]\lipsum[1]
\section{foo}\lipsum[1]\lipsum[1]
\end{document}
```
Comment for this answer: Thank you very much.
|
Title: merge 'if out of range' and 'if item equals' in one condition
Tags: python
Question: ``` if col-2 > 0:
if matrix[row, col-2] != 0:
col -= 2
# some code here 1
else:
# some code here 2
else:
# some code here 2
```
I have many pieces of code like this. Not exactly like this one, but many conditions in my code work the same way. I'd like to merge ```if col-2 > 0:``` and ```if matrix[row, col-2] != 0:``` to get rid of many duplicated lines all over the code (# some code here 2). The problem of merging is checking if an item is non-zero even if that item is out of range.
Comment: IMHO, how about just write `if col-2 > 0 && matrix[row, col-2] != 0: #branch1... else: #branch2...`?
Comment: You could put the condition in its own method so you could call something like `if outOfRange() and itemEquals(matrix[row,col-2], 0)`
Here is the accepted answer: This is as simple as
```if col-2 > 0 and matrix[row, col-2] != 0:
# code 1
else:
# code 2
```
Note that ```matrix[row, col-2] != 0``` will not be executed if ```col-2 > 0```is not true.
You can see this more clearly with something like:
```def raiseError():
raise ValueError()
if False and raiseError():
print("Won't get here")
else:
print("No error was raised")
```
|
Title: Display a customized confirm box in angularjs when user leaves a page
Tags: javascript;angularjs;angularjs-material
Question: My requirement is to display a customized confirm box when the user leaves a page without saving form data.
I used the ```window.onbeforeunload``` event it is displaying google chrome related predefined confirm box. When the user changes any form and trying to reload, tab close or route change I want to display a $mdDialog.confirm and asking user to leave the page or stay on the same page. How do I make one?
Comment: I don't think that's possible and that's by design. The only notification you can give is using the browser's own dialog. This is so pages can't hijack users indefinitely.
Here is another answer: For security reasons, this cannot be done. You can find more details in the MDN page on the beforeunload event.
In the past, you could return a custom string that was displayed to the user, but these days even that is ignore. The best you can do is instruct the page to show the standard dialog that you already have. (And in some browsers and some scenarios, even that instruction may be ignored.)
An alternative is to include a button in the page for leaving the form. Although that still does not prevent users from navigating away from the page directly, if it is sufficiently visible, in many cases users are more likely to click that than navigating directly. It also serves as a passive reminder that the form needs explicit saving or cancelling (depending on your specific details, of course).
|
Title: Failed to start MySQL Community Server
Tags: server;mysql
Question: I'm trying install mysql but I can not start the server.
The ```journalctl -xe``` return this:
```Unit mysql.service has begun starting up.
oct 24 18:37:11 carlosPc audit[20528]: AVC apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/
oct 24 18:37:11 carlosPc audit[20528]: AVC apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/
oct 24 18:37:11 carlosPc audit[20528]: AVC apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/
oct 24 18:37:11 carlosPc kernel: audit: type=1400 audit(1508863031.769:402): apparmor="DENIED" operation="open"
oct 24 18:37:11 carlosPc kernel: audit: type=1400 audit(1508863031.769:403): apparmor="DENIED" operation="open"
oct 24 18:37:11 carlosPc kernel: audit: type=1400 audit(1508863031.769:404): apparmor="DENIED" operation="open"
oct 24 18:37:14 carlosPc systemd[1]: mysql.service: Main process exited, code=exited, status=1/FAILURE
oct 24 18:37:41 carlosPc systemd[1]: Failed to start MySQL Community Server.
-- Subject: Unit mysql.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit mysql.service has failed.
--
-- The result is failed.
oct 24 18:37:41 carlosPc systemd[1]: mysql.service: Unit entered failed state.
oct 24 18:37:41 carlosPc systemd[1]: mysql.service: Failed with result 'exit-code'.
oct 24 18:37:42 carlosPc systemd[1]: mysql.service: Service hold-off time over, scheduling restart.
oct 24 18:37:42 carlosPc systemd[1]: Stopped MySQL Community Server.
-- Subject: Unit mysql.service has finished shutting down
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit mysql.service has finished shutting down.
oct 24 18:37:42 carlosPc systemd[1]: Starting MySQL Community Server...
-- Subject: Unit mysql.service has begun start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit mysql.service has begun starting up.
oct 24 18:37:42 carlosPc audit[20630]: AVC apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/
oct 24 18:37:42 carlosPc audit[20630]: AVC apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/
oct 24 18:37:42 carlosPc audit[20630]: AVC apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/
oct 24 18:37:42 carlosPc kernel: audit: type=1400 audit(1508863062.269:405): apparmor="DENIED" operation="open"
oct 24 18:37:42 carlosPc kernel: audit: type=1400 audit(1508863062.269:406): apparmor="DENIED" operation="open"
oct 24 18:37:42 carlosPc kernel: audit: type=1400 audit(1508863062.269:407): apparmor="DENIED" operation="open"
```
Comment: Did `sudo command` play a role in its install?
Comment: AppArmor is blocking the execution. How'd you install MySQL?
Comment: @ThomasWard I don't remember how I installed MySQL. I think I installed following this tutorial (https://www.digitalocean.com/community/tutorials/how-to-install-mysql-on-ubuntu-16-04). Doing `sudo apt-get install mysql-server`
|
Title: Date format in hosting server
Tags: asp.net;iis-7;web-config
Question: in our search and business process in the site we depend on date format dd/mm/yyyy and time format HH:MM
but I discovered that the site and hosting server date format look like M/dd/yyyy H:MM PM/AM.
I tried to use the following in web.config to override that but I failed
``` <globalization
requestEncoding="utf-8"
responseEncoding="utf-8"
culture="en-GB"
uiCulture="es" />
```
any other ideas to solve that , I don't have access on the server to change the date , it's godaddy hosting
Comment: Try this http://stackoverflow.com/questions/2468312/setting-a-date-format-in-asp-net-web-config-globalization-tag
Here is another answer: Date and string conversions can be a long modification, and be a bit messy. Add the below to your web.config. Be careful not to add duplicate globalization or system.web tags.
```<system.web>
<globalization culture="en-NZ" uiCulture="en-NZ"/>
</system.web>
```
Tested in ASP.NET 4.5 GoDaddy host and it works.
Here is another answer: You will not be able to overwrite any server settings with your web.config. However, in your code you can format the datetime string that way. You can see more on how to do this here: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Here is another answer: As Josh Harris mentions, add configuration in web config:
```<system.web>
<globalization culture="es" uiCulture="es-MX"/>
</system.web>
```
It worked for me for website hosting in goDaddy -
|
Title: Alternative to rename_function in php7.3
Tags: php;function;rename
Question: I need to use ```rename_function``` into php7.3 under Debian 10 Buster.
I'm trying to install apd library but when I run the install command I receive the following error:
```# pecl install apd
pear/apd requires PHP (version >= 5.0.0RC3-dev, version <= 6.0.0), installed version is 7.3.6-1+0~20190531112735.39+stretch~1.gbp6131b7
No valid packages found
install failed
```
Is there any alternative to ```rename_function``` in php7.3?
Comment: [That extension](https://pecl.php.net/package/apd) is abandoned since 2004 so you need a PHP version around that age.
Comment: Thanks. Is there any alternative to `rename_function` in php7.3?
|
Title: How to pass textfield data from html to servlet without using forms
Tags: java;javascript;ajax;jsp;jakarta-ee
Question: I am making an online shopping website. I want to provide an option to user that he/she can select different shipping address :-
Shipping Details
``` <input type="button" value="Same as billing address" style="color: #FFFFFF;" class="link-style" onclick="test();" />
<table cellpadding="20">
<tr>
<td >Name : * </td>
<td><input type="text" id="name" name="name" /></td>
</tr>
<tr>
<td>Contact Number : </td>
<td><input type="text" name="cno" id="cno" /></td>
</tr>
<tr>
<td>Address : * </td>
<td><input type="text" name="address "id="address" /></td>
</tr>
<tr>
<td>City : *</td>
<td><input type="text" name="city" id="city" /></td>
</tr>
<tr>
<td>State : * </td>
<td><input type="text" name="state" id="state" /></td>
</tr>
<tr>
<td>Country : *</td>
<td><input type="text" name="country" id="country" /></td>
</tr>
</table>
```
if user clicks on button then all fields are disabled. Otherwise he/she can fill diffrent shipping address. Problem is i don't want to use forms here. How to pass these parameters to a jsp or servlet in session or post? I already tried AJAX but i am unable to work with it properly
```function setValue() {
alert("hi");
var name = document.getElementById("name").value;
var cno = document.getElementById("cno").value;
var address = document.getElementById("address").value;
var city = document.getElementById("city").value;
var state = document.getElementById("state").value;
var country = document.getElementById("country").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("post", "test.jsp", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form- urlencoded");
xmlhttp.send("name=" + name);
xmlhttp.send("cno=" + cno);
xmlhttp.send("address=" + address);
xmlhttp.send("city=" + city);
xmlhttp.send("state=" + state);
xmlhttp.send("country=" + country);
}
```
Test.jsp is not getting the parameters.
Here is the accepted answer: You must only call ```xmlhttp.send``` once, which requires you to concatenate the request parameters.
``` xmlhttp.send("name="+name+"&cno="+cno+"&address="+address+"&city="+city+"&state=" + state + "&country="+country);
```
Here is another answer: try like this:
```var inputParam='{"name":"'+name+'","cno":"'+cno+'","address":"'+address+'","city":"'+city+'","state":"'+state+'","country":"'+country+'"}';
$.ajax({
type: "POST",
url: your base_url,
data: {inputParam:inputParam,module :'your module name'},
dataType: "json",
async:false,
success: function(msg)
{
console.log(msg);
}
});
```
|
Title: Books by category published annually in Ireland
Tags: data-request;books;ireland
Question: UNESCO monitors both the number and type of books published per country per year.
It's very intriguing for me to notice that Ireland is missing from this list.
I was wondering how can I get such figures, at least a rough estimate, for any year for Ireland. Does anyone know a source for the numbers and categories of books published in Ireland?
|
Title: What size for a SqlDbType parameter with bigint?
Tags: c#;sql-server;size;sqlparameter;sqldbtype
Question: What is the size to specify for a bigint parameter?
```SqlParameter param = new SqlParameter("@Param", SqlDbType.Bigint);
param.Size = ???
```
Or can specifying the size be omitted altogether?
Comment: sql server BIGINT data type is 8 byte data type and you do not specify any size with it.
Comment: Thanks. Could you provide an answer with a supporting link for that information? I'll select that answer
Here is the accepted answer: SQL Server Integer Data types INT, TINYINT, SMALLINT OR BIGINT all has a specific Range and fixed storage space required.
In Sql Server when consuming these data types we cannot limit the range or space required to store these data types by defining a size.
For more information on size and range of these data types have a look here ```SQL SERVER int, bigint, smallint, and tinyint```
```╔═══════════╦══════════════════════════════════════════════════════════════════════════╦═════════╗
║ Data type ║ Range ║ Storage ║
╠═══════════╬══════════════════════════════════════════════════════════════════════════╬═════════╣
║ bigint ║ -2^63 (-9,223,372,036,854,775,808) to 2^63-1 (9,223,372,036,854,775,807) ║ 8 Bytes ║
║ int ║ -2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647) ║ 4 Bytes ║
║ smallint ║ -2^15 (-32,768) to 2^15-1 (32,767) ║ 2 Bytes ║
║ tinyint ║ 0 to 255 ║ 1 Byte ║
╚═══════════╩══════════════════════════════════════════════════════════════════════════╩═════════╝
```
Here is another answer: Correct you don't need to specify the size when creating the integer type parameters for the command
```Command.Parameters.Add("@p0", SqlDbType.TinyInt) // omit size, name.
```
|
Title: Infinite loop when using a key multiple times in HashMap
Tags: java;hash;hashmap;stack-overflow
Question: ```HashMap``` falls into an infinite loop.
I am not able to understand why ```HashMap``` throws stackoverflow error when the same key is used multiple times.
Code:
```import java.util.HashMap;
public class Test {
public static void main(String[] args) {
HashMap hm = new HashMap();
hm.put(hm, "1");
hm.put(hm, "2");
}
}
```
Error:
```
Exception in thread "main" java.lang.StackOverflowError
```
Comment: You can't use key as its own object
Comment: Yeah, that's fine but why stack overflow...:(
Comment: thanks , as from java docs it has been cleared.
Comment: dont use raw types with HashMap
Comment: And don't use mutable types as hash map keys.
Comment: You use the map itself as a key??
Comment: Can you post the full stacktrace? I think there are hints on why it cause the stack overflow.
Comment: if you dig a little in the code of the `put` method, and if you look at the stacktrace, you'll find that the key depends on the keys.
Here is the accepted answer: It is not possible to add to a ```Map``` itself as a key. From javadoc:
```
A special case of this prohibition is that it is not permissible for a map to contain itself as a key.
```
The problem is that you are using as key not a standard object (any object with well defined ```equals``` and ```hashCode``` methods, that is not the map itself), but the map itself.
The problem is on how the ```hashCode``` of the ```HashMap``` is calculated:
```public int hashCode() {
int h = 0;
Iterator<Entry<K,V>> i = entrySet().iterator();
while (i.hasNext())
h += i.next().hashCode();
return h;
}
```
As you can see, to calculate the hashCode of the map, it iterates over all the elements of the map. And for each element, it calculates the hashCode. Because the only element of the map has as key is the map itself, it becomes a source of recursion.
Replacing the map with another object that can be used as key (with well defined ```equals``` and ```hashCode```) will work:
```import java.util.HashMap;
public class Test {
public static void main(String[] args) {
HashMap hm = new HashMap();
String key = "k1";
hm.put(key, "1");
hm.put(key, "2");
}
}
```
Comment for this answer: This is imho now a good answer. Downvote converted to upvote.
Comment for this answer: Why isn't this a compile time error if it's explicitly prohibited in the docs.
Comment for this answer: What is a standard object?
Comment for this answer: Why not just have `public int hashCode() {throw new RuntimeException("Hashcode of a Hashmap is undefined!");}`? Sure in this way you prevent the `HashMap` to be used as a key for a *different* mapping, but that's probably a bad idea anyway...
Comment for this answer: Any object that can be used as key. So with well defined hashCode and equals methods
Comment for this answer: @SleimanJneidi I added also an explicit reference from the javadoc telling that is not possible to add a Map to itself as key.
Comment for this answer: @AshBurlaczenko there are too many ways to put a key on the map. Is not simple (and not correct to check all of them at compile time). Additionally is counter intuitive to add a data structure to itself.
Here is another answer: You are using same object name as a key so it is infinite loop.
so it is stack overflow.
Here is another answer: Problem is not that hash map blows up the stack for "same key" entered twice, but because your particular choice of map key. You are adding hash map to itself.
To explain better - part of Map contract is that keys must not change in a way that affects their equals (or hashCode for that matter) methods.
When you added map to itself as a key, you changed key (map) in a way that is making it return different hashCode than when you first added map.
For more information this is from JDK dock for Map interface:
```
Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map. A special case of this prohibition is that it is not permissible for a map to contain itself as a key. While it is permissible for a map to contain itself as a value, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a map.
```
Here is another answer: In order to locate a key in the ```HashMap``` (which is done whenever you call ```put``` or ```get``` or ```containsKey```), ```hashCode``` method is called for the key.
For ```HashMap```, ```hashCode()``` is a function of the ```hashCode()``` of all the entries of the ```Map```, and each entry's ```hashCode``` is a function of the key's and value's ```hashCode```s. Since your key is the same ```HashMap``` instance, computing the ```hashCode``` of that key causes an infinite recursion of ```hashCode``` method calls, leading to ```StackOverflowError```.
Using a ```HashMap``` as a key to a ```HashMap``` is a bad idea.
Comment for this answer: Using a HashMap as a key is generally a bad idea, and especially it is forbidden adding the map as key to itself (as defined in the Map javadoc, see my answer)
|
Title: SQL : I search the good query with select max() and select count()
Tags: mysql;sql;select;count;max
Question: I have a table named arrived (this table is simple, and it just saves the users that arrive at school at such day and at such hour) with the following data :
```id name day hour
1 Alice Monday 11
2 Alice Monday 13
3 Alice Tuesday 11
4 Céline Wednesday 14
5 Céline Wednesday 13
6 Céline Thursday 14
7 Maud Friday 15
8 Maud Saturday 15
9 Maud Saturday 16
```
Now, I search the good query that find for each user : the most frequent day and the most frequent hour, that is say, the result of the query must return this lines :
```Alice Monday 11
Céline Wednesday 14
Maud Saturday 15
```
=> because :
Alice frequently arrives at Monday, and frequently at 11h
Céline frequently arrives at Wednesday, and frequently at 14h
Maud frequently arrives at Saturday, and frequently at 15h
My query is below, but it doesn't give me the good result :
```SELECT NAME,
day,
Max(count_hour)
FROM (SELECT NAME,
day,
Count(hour) AS count_hour
FROM arrived
GROUP BY NAME,
day) AS alias_table
GROUP BY NAME
```
Thank you, cordially.
Comment: If you can, instead of `day` and `hour`, just store `datetime`.
Here is the accepted answer: Not sure is this the right way to do it but should work!
```SELECT *
FROM arrived A
WHERE hour = (SELECT hour
FROM arrived B
WHERE a.NAME = b.NAME
GROUP BY b.hour,
b.NAME
ORDER BY Count(b.hour) DESC Limit 1)
AND day = (SELECT day
FROM arrived B
WHERE a.NAME = b.NAME
GROUP BY b.day,
b.NAME
ORDER BY Count(b.day) DESC Limit 1)
```
SQLFIDDLE DEMO
Comment for this answer: This query will fail to return a row if the combination (max(day),max(hour)) does not exist, see http://sqlfiddle.com/#!2/489a2c/1/0
Comment for this answer: This is a modified version returning the correct result: http://sqlfiddle.com/#!2/489a2c/3/0
Comment for this answer: Thanks for your reply. But I just have one table named "arrived". Why do you use two tables ?
Comment for this answer: Thank you very much, it works ! effectively, you use A and B as alias tables. Thank you very much !!!
Comment for this answer: @totoaussi - Even i have used only one table named **Yourtable**. Now edited the name to **arrived**
Comment for this answer: @totoaussi - Glad it helped you, Cheers :)
Here is another answer: Try the ```greatest(day, hour)``` when selecting columns. You can also try ```greatest(max(day), max(hour))```
Cheers!
Comment for this answer: Even if greatest is not appropriate, thank you for your reply.
|
Title: How to Change the user settings file loc to other disk
Tags: visual-studio-code;settings;diskspace;file-location
Question: I want to change this folder's location
enter image description here
& I have tried to use the command line ```code --user-data-dir d:/IDE/VSC_Denpendency/User_data```
,after the command, it does create the same files in the target folder. However, I still can't delete the ```%APPDATA%/Code```, besides, every time I start the vscode, it will appears again and can not be delete.
Disk C has no more space so I want to change it, Using the spacesniffer tool, I find it that the ```%APPDATA%/Code/User/workspacestorage``` has cost me about 2GB of space.
Help me please!!
Comment: Please provide enough code so others can better understand or reproduce the problem.
|
Title: Create a topic with authorization rule using azure-messaging-servicebus
Tags: java;azure;groovy;azureservicebus
Question: I'm trying to create a topic using ServiceBusAdministrationClient connected through a namespace's root manage access key
(com.azure:azure-messaging-servicebus:7.8.0)
```def createOptions = new CreateTopicOptions()
def authRule = new SharedAccessAuthorizationRule(authRuleName, [AccessRights.SEND, AccessRights.LISTEN])
createOptions.authorizationRules.add(authRule)
def topicProps = administrationClient.createTopic(topicName, createOptions)
```
but there are no AuthorizationRules associated with the topic.
I did the same thing when creating a queue and it worked.
Any ideas what I might be missing?
Here is another answer: For the authorization rule, you need to use Azure Resource Management library
Below is a sample to create an authorization rule
```final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);
final TokenCredential credential =
new DefaultAzureCredentialBuilder()
.authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint())
.build();
var azureResourceManager =
AzureResourceManager.configure()
.withLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.authenticate(credential, profile)
.withSubscription("subscription");
ServiceBusManager manager = azureResourceManager.serviceBusNamespaces().manager();
SBAuthorizationRuleInner authorizationRule =
manager
.serviceClient()
.getTopics()
.createOrUpdateAuthorizationRule(
"resourceGroupName", "namespaceName", "topicName", "authorizationRuleName");
```
Comment for this answer: Yes, in the end I used this library because I could not find why azure-messaging-servicebus is not working as I assumed. Maybe someone can still figure it out.
Comment for this answer: Agree, it's confusing. I think the Azure team should move all management-related stuff to the resource management library. BTW, if you had already figured it out then please post the answer, it would have helped others. I spent countless hours :-)
|
Title: JavaScript check if object has inherited property
Tags: javascript;inheritance
Question: ```function Employee(name, dept) {
this.name = name || "";
this.dept = dept || "general";
}
function WorkerBee(projs) {
this.projects = projs || [];
}
WorkerBee.prototype = Object.create( Employee.prototype );
function Engineer(mach) {
this.dept = "engineering";
this.mach = mach || "";
}
Engineer.prototype = Object.create(WorkerBee.prototype);
var jane = new Engineer("belau");
console.log( 'projects' in jane );
```
Trying to check if ```jane``` inherited the ```projects``` property.
Outputs ```false```. Why?
Here is the accepted answer: ```
Outputs ```false```. Why?
```
Because ```this.projects``` is set inside ```WorkerBee```, but that function is never executed.
This is the same issue as in your previous question: JavaScript inheritance Object.create() not working as expected
Comment for this answer: Just realized that. What confused me was the use of `new` instead of `Object.create()`
Here is another answer: If you are testing for properties that are on the object itself (not a part of its prototype chain) you can use .hasOwnProperty():
```if (x.hasOwnProperty('y')) {
// ......
}
```
Object or its prototype has a property:
You can use the in operator to test for properties that are inherited as well.
```if ('y' in x) {
// ......
}
```
Comment for this answer: `x = "test"; try { if ('indexOf' in x) { console.log('it is correct answer'); }} catch (e) {console.log('it is wrong answer, actually'); }`
Comment for this answer: While you are right, this doesn't answer the OP's question.
|
Title: mocha - Retry Whole Test
Tags: javascript;testing;mocha.js;appium;webdriver-io
Question: Is there a way to retry an entire test case if any test suite within it fails?
I have tried using ```this.retries()``` but for some reason whenever my test fails, it just stops after one run. Using it in a specific test suite works but it gives me false positives (test passes even though it's on the wrong screen) plus this won't work if my test fails on the before hook. I've also tried using the ```retries``` option but it also stopped after one failed run.
I'm using ```Appium``` with ```MochaJS``` and ```WebdriverIO``` to test an Android app.
EDIT: Not using TestNG or any other frameworks other than those listed above.
Here is another answer: You can use Retry Analyzer, just create a method:
```public class RetryAnalyzer implements IRetryAnalyzer {
int counter = 1;
int retryLimit = 3; //Change the limit, how many time you want to retry
@Override
public boolean retry(ITestResult result) {
if(counter < retryLimit) {
counter++;
return true;
}
return false;
}
}
```
Use above method in ```@Test``` annotation like below:
```@Test(retryAnalyzer = RetryAnalyzer.class)
public void testCaseName() throws Exception {
//Your code
}
```
Comment for this answer: Yeah, you have to use TestNG framework for this feature.
Comment for this answer: This is in C# and TestNG right? Would this be similar in Javascript and without testNG?
Comment for this answer: I see my mistake so its not possible without TestNG right? Do you have any suggestions for Mocha/WebdriverIO?
Comment for this answer: Are there any alternatives for non TestNG testers?
Here is another answer: Ideally this.retries option in mocha should work just fine in Webdriverio unless you are using fat arrow functions in your test suites/test cases. Please try to reach out Webdriverio gitter channel for latest issues or for work around. They are extremely helpful.
|
Title: calling POST request through jBPM
Tags: jbpm
Question: I am trying to call a POST service through jBPM and getting the following error
```Caused by: java.lang.IllegalArgumentException: Content type may not be null```
my POST request is
``` public String changeOrderStatus(@RequestBody String order){
System.out.println("Post");
return "success";
}
```
and my jBPM service task has these input/output
What is the reason for the error. When I omit the ```@RequestBody```, the post works. but I need to send data. can someone explain.
Also I do not find any online content for different REST calls for jBPM. I am working on a new project and we are planning to use jBPM. Should I use it or try other BPM opensource engine?
Comment: what is the ContentType?
Comment: I mean what is it's value here?
Comment: you will have the same problem in any other BPM engine, the problem is in your code and in how you are calling your service, please provide more details of your code to solve it
Comment: great to hear that
Comment: ContentType variable is the parameter which is added by default when u add REST service Task in jBPM
Comment: application/json
Comment: You were right, there was a trailing SPACE in Variable name for ContentType.
Here is another answer: We can close this question as owner of this question @Afroz Shaikh answered his question inside comments:
"You were right, there was a trailing SPACE in Variable name for ContentType."
|
Title: AVPlayerStatus vs AVPlayerItemStatus
Tags: iphone;nstimer;avplayer;nsrunloop
Question: The issue is that player.status returns ```AVPlayerStatusReadyToPlay``` a full 2 seconds before player.currentItem.status returns ```AVPlayerItemStatusReadyToPlay```. Does anyone have any helpful explanations as to why this is happening?
This is just sample code to show the basic idea of what's happening so if there are any typos or whatever please ignore them.
```- (void) someMethod
{
player = [[AVPlayer alloc] initWithURL:someValidURL];
[player play];
NSTimer *timer = [NSTimer timerWithTimeInterval:0.1 target:self selector:@selector(checkStatus:) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}
- (void) checkStatus: (NSTimer *)timer
{
NSLog(@"player status: %i", player.status]);
NSLog(@"player item status: %i", player.currentItem.status]);
}
```
Comment: were you able to figure this out? I'm experiencing a similar issue here http://stackoverflow.com/questions/13977805/avplayer-skips-the-beginning-of-a-video and I think it might be related
Comment: Hmmm... no answers. There also seems to be an arbitrary delay between calling [player play] and actually hearing audio; and this is after either or both Status' say they are ready. I can only imagine that these are just bugs/quirks of AVPlayer and that's why there is no real explanation as to what is happening...?
Comment: Never found an answer. I'll take a look at your question though.
Here is another answer: In our experience building Ultravisual the ```AVPlayerStatus``` and ```AVPlayerItemStatus``` are only kind of related to each other, and often depend on async states -- ie, the implementations tend to be heavily multithreaded, and are often buggy or poorly defined.
We found ```AVPlayerItemStatus``` to be the most reliable indicator of actually really ready to play, but there were some gotchas especially when dealing with ```AVQueuePlayer``` or ```AVPlayerItem```s built from ```AVMutableComposition``` instances.
|
Title: Firefox glitched glyphs
Tags: firefox;fonts
Question: When browsing with Firefox, some pieces of text will randomly render with bizarre glyphs, which immediately go away if selected or some other action happens on the page or even outside of it. For example, the simple fact of taking this snapshot triggered the numbers to render normally:
```
```
Note that this can happen on any character, even simple ascii ones like in the pictures, and the glitched glyphs which appear instead of the correct ones are not always the same.
I'm on an up to date Kubuntu 14.04 with noscript, flashblock, ghostery and adblock on Firefox. I had to install some fonts to display Korean characters previously, and I can't remember having this bug beforehand
As requested, here's the output of ```glxinfo | grep OpenGL```:
```OpenGL vendor string: X.Org
OpenGL renderer string: Gallium 0.4 on AMD CAPE VERDE
OpenGL core profile version string: 3.1 (Core Profile) Mesa 10.1.3
OpenGL core profile shading language version string: 1.40
OpenGL core profile context flags: (none)
OpenGL core profile extensions:
OpenGL version string: 3.0 Mesa 10.1.3
OpenGL shading language version string: 1.30
OpenGL context flags: (none)
OpenGL extensions:<nothing here>
```
Comment: Related: http://askubuntu.com/questions/492489/occasional-artifacts-when-displaying-characters - I seem to be having a similar issue, except my artifacts look a bit different, and have to be selected in order to be cleared.
Comment: Well then, it's a race to the top :D I'll keep an eye on your question as well. The first one of us that gets an answer should flag the other's question as a duplicate, by the way (of course, if the solution works for both).
Comment: Hey @nathdwek, could you tell me which graphics driver you are using? Post the output of `glxinfo | grep OpenGL`.
Comment: I have [switched to fglrx](http://askubuntu.com/questions/492489/occasional-artifacts-when-displaying-characters) briefly and haven't seen the artifacts (glitches) since. Could you test this out? To enable it, just type "drivers" in the Dash and open the Additional Drivers application (might take a while) - and select the one that has fglrx in its name. It takes a while and I suggest you reboot after the procedure.
Comment: Well 99% of the time they are cleared upon selection, and some of my artifacts do indeed look like yours. radeon hd 7770 here BTW
|
Title: Why does wetting something change its colour?
Tags: electromagnetic-radiation;visible-light;water
Question: I have noticed that wetting something almost always changes its colour. For example sprinkling water onto a t-shirt creates darker spots on the fabric; but this effect is not limited to fabric, almost everything once wet appears darker. Why is that?
Comment: Maybe almost everything _porous._ But wet metal and wet plastic don't usually look any darker. Maybe that's a clue...
Here is another answer: Wet sand, cloth and many other substances with a porous microstructure become darker when wet because they become less reflective, both because of a reduction of diffuse reflection and because light penetrates deeper into the material. This explanation was originally formulated by Ångström in 1925.
When light hits an uneven dry surface like a sand grain, it scatters in all directions (diffuse reflection) while when covered with a smooth water surface most light is reflected in particular direction (specular reflection) that makes it look dark when you are not in its path. Light that enters water also can experience total internal reflection when trying to re-enter air, getting trapped and progressing deeper into the structure where it is eventually absorbed. This is helped by the scattering angle becoming smaller due to the higher index of refraction of the water compared to the index of air.
|
Title: How to install libltdl.so.3
Tags: fedora;software-installation;printer
Question: I have Fedora 20, and am trying to install scanner software, 32-bit, for my Epson DX5000 printer. I get the messages:
```[root@localhost:/home/Harry]$ rpm -Uvh iscan-2.29.3-1.usb0.1.ltdl3.i386.rpm
error: Failed dependencies:
libltdl.so.3 is needed by iscan-2.29.3-1.usb0.1.ltdl3.i386
[root@localhost:/home/Harry]$ yum install libltdl.so.3
Loaded plugins: langpacks, refresh-packagekit
No package libltdl.so.3 available.
Error: Nothing to do
[root@localhost:/home/Harry]$
```
I have tried searching on the Internet for ```libltdl.so.3```, but I find the results very confusing. Is it perhaps part of another package? Please can anyone help me?
Thanks for the answers so far. I think this is another time when I asked X when I should have asked Y. I already have ```libtool``` installed (see the screen shot) So now the question is: why does it say ```libltdl.so.3 is needed``` when ```libtool``` is already installed? Unless I have misunderstood what is going on, again.
```[root@localhost:/home/Harry]$ yum install libtool-ltdl
Loaded plugins: langpacks, refresh-packagekit
Package libtool-ltdl-2.4.2-23.fc20.i686 already installed and latest version
Nothing to do
[root@localhost:/home/Harry]$
```
Also:
```[root@localhost:/home/Harry]$ yum install libltdl7
Loaded plugins: langpacks, refresh-packagekit
No package libltdl7 available.
Error: Nothing to do
[root@localhost:/home/Harry]$
```
Meta question: should I also change the title?
Comment: Looks like you want libltdl7.
Here is another answer: Whenever you encounter a stray missing library file such as this one you can use the command ```repoquery``` to find out what package provides it.
Example
```$ repoquery -q -f */libltdl.so*
libtool-ltdl-devel-0:2.4.2-16.fc19.x86_64
libtool-ltdl-0:2.4.2-23.fc19.x86_64
libtool-ltdl-devel-0:2.4.2-16.fc19.i686
libtool-ltdl-0:2.4.2-23.fc19.i686
libtool-ltdl-devel-0:2.4.2-23.fc19.i686
libtool-ltdl-0:2.4.2-16.fc19.i686
libtool-ltdl-devel-0:2.4.2-23.fc19.x86_64
libtool-ltdl-0:2.4.2-16.fc19.x86_64
```
I like to relax the query a bit and look for any ```.so``` files, so I've swapped the ```.3``` out for a ```*```.
NOTE: The above is quering (```-q```) for files (```-f```) matching the pattern (```*/libltdl.so*```). The first star is important since the query is looking for matches against the full paths of the files within the RPMs stored on the various YUM repos your system is aware of.
Here is another answer: This worked for me on Fedora 21 (x64):
```rpm -Uvh iscan-2.30.1-1.usb0.1.ltdl3.x86_64.rpm --nodeps
ln -s /usr/lib64/libltdl.so.7 /usr/lib64/libltdl.so.3
```
iscan seems to work fine with the newer library
Here is another answer: You have to install libtool-ltdl:
```yum install libtool-ltdl
```
Source: https://www.google.com/search?name=f&hl=en&q=libltdl.so.3
Comment for this answer: For headers: `libtool-ltdl-devel`
|
Title: Pass a pointer instead of return new variable in C and Go?
Tags: c;go;pointers;conventions
Question: Why is it convention in C and Go to pass a pointer to a variable and change it rather return a new variable with the value?
In C:
```#include <stdio.h>
int getValueUsingReturn() {
int value = 42;
return value;
}
void getValueUsingPointer(int* value ) {
*value = 42;
}
int main(void) {
int valueUsingReturn = getValueUsingReturn();
printf("%d\n", valueUsingReturn);
int valueUsingPointer;
getValueUsingPointer(&valueUsingPointer);
printf("%d\n", valueUsingPointer);
return 0;
}
```
In Go:
```package main
import "fmt"
func getValueUsingReturn() int {
value := 42
return value
}
func getValueUsingPointer(value *int) {
*value = 42
}
func main() {
valueUsingReturn := getValueUsingReturn()
fmt.Printf("%d\n", valueUsingReturn)
var valueUsingPointer int
getValueUsingPointer(&valueUsingPointer)
fmt.Printf("%d\n", valueUsingPointer)
}
```
It there any performance benefits or restrictions in doing one or the other?
Comment: Look at a function like `snprintf` and tell use how you would otherwise define such function.
Comment: There is no such convention. In both of your examples returning the single value normally is easier and faster.
Comment: Passing values through pointer arguments like this can be a workaround for multiple return values in languages that don't support multiple return.
Here is the accepted answer: First off, I don't know enough about Go to give a judgement on it, but the answer will apply in the case of C.
If you're just working on primitive types like ```int```s, then I'd say there is no performance difference between the two techniques.
When ```struct```s come into play, there is a very slight advantage of modifying a variable via pointer (based purely on what you're doing in your code)
```#include <stdio.h>
struct Person {
int age;
const char *name;
const char *address;
const char *occupation;
};
struct Person getReturnedPerson() {
struct Person thePerson = {26, "Chad", "123 Someplace St.", "Software Engineer"};
return thePerson;
}
void changeExistingPerson(struct Person *thePerson) {
thePerson->age = 26;
thePerson->name = "Chad";
thePerson->address = "123 Someplace St.";
thePerson->occupation = "Software Engineer";
}
int main(void) {
struct Person someGuy = getReturnedPerson();
struct Person theSameDude;
changeExistingPerson(&theSameDude);
return 0;
}
```
GCC x86-64 11.2
With No Optimizations
Returning a ```struct``` variable through the function's return is slower because the variable has to be "built" by assigning the desired values, after which, the variable is copied to the return value.
When you're modifying a variable by pointer indirection, there is nothing to do except write the desired values to the memory addresses (based off the pointer you passed in)
```.LC0:
.string "Chad"
.LC1:
.string "123 Someplace St."
.LC2:
.string "Software Engineer"
getReturnedPerson:
push rbp
mov rbp, rsp
mov QWORD PTR [rbp-40], rdi
mov DWORD PTR [rbp-32], 26
mov QWORD PTR [rbp-24], OFFSET FLAT:.LC0
mov QWORD PTR [rbp-16], OFFSET FLAT:.LC1
mov QWORD PTR [rbp-8], OFFSET FLAT:.LC2
mov rcx, QWORD PTR [rbp-40]
mov rax, QWORD PTR [rbp-32]
mov rdx, QWORD PTR [rbp-24]
mov QWORD PTR [rcx], rax
mov QWORD PTR [rcx+8], rdx
mov rax, QWORD PTR [rbp-16]
mov rdx, QWORD PTR [rbp-8]
mov QWORD PTR [rcx+16], rax
mov QWORD PTR [rcx+24], rdx
mov rax, QWORD PTR [rbp-40]
pop rbp
ret
changeExistingPerson:
push rbp
mov rbp, rsp
mov QWORD PTR [rbp-8], rdi
mov rax, QWORD PTR [rbp-8]
mov DWORD PTR [rax], 26
mov rax, QWORD PTR [rbp-8]
mov QWORD PTR [rax+8], OFFSET FLAT:.LC0
mov rax, QWORD PTR [rbp-8]
mov QWORD PTR [rax+16], OFFSET FLAT:.LC1
mov rax, QWORD PTR [rbp-8]
mov QWORD PTR [rax+24], OFFSET FLAT:.LC2
nop
pop rbp
ret
main:
push rbp
mov rbp, rsp
sub rsp, 64
lea rax, [rbp-32]
mov rdi, rax
mov eax, 0
call getReturnedPerson
lea rax, [rbp-64]
mov rdi, rax
call changeExistingPerson
mov eax, 0
leave
ret
```
With Slight Optimization
However, most compilers today can figure out what you're trying to do here, and will equalize the performance between the two techniques.
If you want to be absolutely stingy, passing pointers is still slightly faster by a few clock [email protected].
In returning a variable from the function, you still have to at least set the address of the return value.
``` mov rax, rdi
```
But in passing the pointer, not even this is done.
But other than that, the two techniques have no performance difference.
```.LC0:
.string "Chad"
.LC1:
.string "123 Someplace St."
.LC2:
.string "Software Engineer"
getReturnedPerson:
mov rax, rdi
mov DWORD PTR [rdi], 26
mov QWORD PTR [rdi+8], OFFSET FLAT:.LC0
mov QWORD PTR [rdi+16], OFFSET FLAT:.LC1
mov QWORD PTR [rdi+24], OFFSET FLAT:.LC2
ret
changeExistingPerson:
mov DWORD PTR [rdi], 26
mov QWORD PTR [rdi+8], OFFSET FLAT:.LC0
mov QWORD PTR [rdi+16], OFFSET FLAT:.LC1
mov QWORD PTR [rdi+24], OFFSET FLAT:.LC2
ret
main:
mov eax, 0
ret
```
Here is another answer: I think the short answer to you question (At least for C, I am not familiar with GO internals) is that C functions are pass by value and generally also return by value so data objects must be copied and people worried about the performance of all the copying. For large objects or objects that are complex in their depth (containing pointers to other stuff) it is often just more efficient or logical for the value being copied to be a pointer so the function can "operate" on the data without needing to copy it.
That being said, modern compilers are pretty smart about figuring out stuff like whether the parameter data will fit in registers or efficiently copying returned structures.
Bottom line is for modern C code do what seems best for your application or what is clearest to you. Avoid premature optimization if it detracts from readability at least in the beginning.
Also Compiler Explorer (https://godbolt.org/) is your friend if you want to examine the effect of different styles, especially in light of optimization.
|
Title: Ionic - The Email Address is Badly Formatted
Tags: angular;firebase;ionic-framework;firebase-authentication
Question: I am working on an ionic project where I am using firebase as back-end and I am building a signup and login form. Whenever I sign up the code is working well and. When I try to retrieve it using "```signInWithEmailAndPassword```" I am getting the following error. The email address is badly formatted Firebase. When first time created account log in successfully. But after login with same email and password error occur.
```import { Component, ViewChild} from '@angular/core';
import { IonicPage, NavController, AlertController, NavParams } from 'ionic-angular';
import { AngularFireAuth } from 'angularfire2/auth';
import { HomePage } from '../home/home';
@IonicPage()
@Component({
selector: 'page-signin',
templateUrl: 'signin.html',
})
export class SigninPage {
@ViewChild('email') email;
@ViewChild('password') password;
constructor(public alertCon: AlertController, public afAuth: AngularFireAuth, public navCtrl: NavController, public navParams: NavParams) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad SigninPage');
}
alert(title, message){
this.alertCon.create({
title: title,
subTitle: message,
buttons: ['OK']
}).present();
}
userSignin(){
this.afAuth.auth.signInWithEmailAndPassword(this.email.value, this.password.value)
.then(data=>{
console.log('loged in');
this.navCtrl.setRoot(HomePage);
this.alert('WELCOME', 'You are loged in');
})
.catch(error=>{
console.log('Error', error)
this.alert('ERROR!', 'password or Email is wrong');
});
}
}
```
Comment: Where is the code you use to sign in a user?
Comment: Sorry!! My mistake..
I have edited post.
Here is another answer: I suggest you create a User model in a separate folder.
define the User model with the following way:
export interface User{
id?: string
email: string;
password:string;
}
Then create a new obj of the User Model in LogIN ts file provided you have imported the model in the login ts file.
user= {} as User;
You can make your login function
loginUser(user:User){ this.logauth.auth.signInWithEmailAndPassword(user.email,user.password);
}
Angular works better if data is passed in an object rather than a property.
So the User Model in this aspect will hold the user data from the login html page and pass to the object in the Login TS File. Hope this helps.
Comment for this answer: i Suggest you create a User Model, in a model folder. export interface User{
id?: string;
username: string;
email: string;
password:string;
roles: Roles;
}
Comment for this answer: can you explain yourself better and add some format to your code example ?
|
Title: SVN : Cannot load /mod_status.so into server: The specified module could not be found.
Tags: apache;svn;visualsvn-server;visualsvn
Question: We have installed VisualSVN Server 2.5.8 in windows server 2012 R2. while loading the the module 'mod_status.so' in httpd-custom.conf, we are getting the following error,
```"VisualSVNServer.exe: Syntax error on line 129 of C:/Program Files (x86)/VisualSVN Server/conf/httpd.conf: Syntax error on line 7 of C:/Program Files (x86)/VisualSVN Server/conf/httpd-custom.conf: Cannot load C:/Program Files (x86)/VisualSVN Server/bin/mod_status.so into server: The specified module could not be found."
```
But the module is exist in the 'C:/Program Files (x86)/VisualSVN Server/Bin' folder. we are able to load the module in other windows machines successfully.
Here is the accepted answer: Are you sure that the mod_status.so is there? I don't think so unless you placed some custom module there. VisualSVN Server comes with mod_status module starting with version 3.0.0, so mod_status has to be missing in 2.5.8.
IMPORTANT: You should never load modules that are not included with VisualSVN Server distribution. VisualSVN Team can't guarantee that the custom-built modules will be loaded or operate properly. Please use the modules that are included with VisualSVN Server distribution only.
Therefore, you should upgrade the server to the latest 3.5 release if you want to enable mod_status.
Don't forget that VisualSVN Server 2.5 is already out of support. It is strongly recommended to upgrade your server instance to the latest version, VisualSVN Server 3.5. Please read KB95: Upgrading to VisualSVN Server 3.5 guide before beginning the upgrade. For the complete list of changes between version 2.5 and 3.5, take a look at the changelog.
I have to note that VisualSVN Server 2.5.8 is very outdated. It's not just behind 5 major updates, but behind 16 minor patch updates. You should always apply the latest patch updates to the server.
Applying a patch update is always painless and fast; patch updates contain only bug fixes and no new features. Just download and run the installer of newer version from the download page.
VisualSVN Team timely releases maintenance updates for VisualSVN Server with security and bugfixes, and it is strongly recommended to keep VisualSVN Server at the latest version. The list of fixed vulnerabilities is available for every release in VisualSVN Server's changelog and on the release announcements page.
To receive release announcements, subscribe to the official announcements list or RSS feed. You can also follow VisualSVN Team on Twitter @VisualSVN or Facebook.
|
Title: rigid body simulation
Tags: animation;rigidbody
Question: I would like to create a container full of objects (bolts) tip the box up and pour and catch them into another container to view as an animation, is this possible and any tips would be helpful as fairly new to working with physics, thank you
Comment: Hi there, I'd recommend watching a couple of Youtube videos to get started with physics simulations, as they often proved every detail needed. Blender Guru should have a few and so should a couple of other people as it's quite a popular and fun thing to do in Blender. 1 tip I'd give straight off is to be wary of how big your simulation is, because if it's big it's highly likely that it'll crash your computer and if you haven't saved you'll have to start over again. Hope you enjoy!
Comment: yes i love blender gur!, ive filled the box successfully, im just unsure how i can then move the box with the objects in situ and then gradually tip the objects out of the box again? as they currently start as a mass of objects floating in space, it may mean several separate animations and a bit of AE to construct the sequence im after
Comment: Try this video: https://www.youtube.com/watch?v=YnvCC4oyvkY it should explain how to animate and move your boxes using keyframes
Comment: thanks, im fairly confident with key frame animation, its combining it with the physics simulation thats a bit painful, ill keep researching :)
Comment: i have managed to solve this by extending the duration between keyframes on the timeline, and amending the gravity settings, this meant i could move the box with the contents and everything stay in situ as opposed to flying around like someone was flinging the products out of the box in a rage!
Comment: Great! I hope you'll show us when it's done!
|
Title: Setting and getting NdefRecord ID
Tags: java;android;format;nfc;ndef
Question: I am trying to write and read back a number of NdefRecords on Android and am having problems with retrieving the record IDs. I believe it is because they are not being written to the tag initially.
I am creating my record(s) as such:
``` private NdefRecord createRecord(String text, byte ID) throws UnsupportedEncodingException {
String lang = "en";
byte[] textBytes = text.getBytes();
byte[] langBytes = lang.getBytes("US-ASCII");
int langLength = langBytes.length;
int textLength = textBytes.length;
byte[] id = new byte[1];
id[0] = ID;
int idLength = id.length;
byte[] payload = new byte[1 + langLength + textLength + idLength];
payload[0] = (byte) langLength;
//set use id flag
payload[0] |= (1 << 3);
// copy langbytes and textbytes into payload
System.arraycopy(langBytes, 0, payload, 1, langLength);
System.arraycopy(textBytes, 0, payload, 1 + langLength, textLength);
// System.arraycopy(id, 0, payload, 1 + langLength + textLength, idLength);
NdefRecord recordNFC = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, id, payload);
return recordNFC;
}
public void addRecord(String record_contents, RECORD_IDS record_id) throws UnsupportedEncodingException {
this.records.add(createRecord(record_contents, (byte) record_id.getValue()));
}
```
I thought I was on to something with the
```// System.arraycopy(id, 0, payload, 1 + langLength + textLength, idLength);
```
But it hasn't worked for me. This method stores NdefRecords in the class object which are then sent using
```public void writeStoredRecords(Tag tag) throws IOException, FormatException {
NdefRecord[] final_records = (NdefRecord[]) this.records.toArray(new NdefRecord[0]);
NdefMessage message = new NdefMessage(final_records);
try {
Ndef ndef = Ndef.get(tag);
if (ndef != null) {
ndef.connect();
if(!ndef.isWritable())
return;
ndef.writeNdefMessage(message);
ndef.close();
}
}catch(Exception e){}
}
```
The record objects have their IDs populated after calling ```new NdefRecord``` but then when reading the tag using the app NXP TagInfo the NDEF record IDs are showing as " ".
Does anyone have any experience with this? As the record IDs are rarely used with NFC the online resources are scarce.
Here is the accepted answer: According to the NFC Forum NDEF specification, the ID field of an NDEF record must be a URI. Consequently, NXP TagInfo will treat this value as a URI string and decodes the byte array into a string (I'm not quite sure which encoding they expect though but browsing through the NDEF specification, I would expect US-ASCII encoding).
Since you use a single byte as ID field, that value probably doesn't decode to a printable character. Therefore, NXP TagInfo simply prints " " (quotation marks surrounding the unprintable string value).
|
Title: C# - Check how many times a value appears in array and find indexes
Tags: c#;arrays;indexof
Question: I have to write a simple program where you have to input student names and their average grade and then print out the highest average grade and who it belongs to. There are several topics here on how to find if value appears in array. The thing i'm struggling with is what to do if there are more than 1 students with the max average grade.
Here's what I have so far:
``` Console.WriteLine("Enter the overall count of students.");
int stuCount = Convert.ToInt32(Console.ReadLine());
string[] name = new string[stuCount];
double[] avg = new double[stuCount];
for (int i = 0; i < stuCount; i++)
{
Console.WriteLine("Enter the name of student # {0}.", i + 1);
name[i] = Console.ReadLine();
Console.WriteLine("Enter the average grade of {0}.", name[i]);
avg[i] = Convert.ToDouble(Console.ReadLine());
}
// Finding the max average
double maxAvg = avg[0];
for (int i = 1; i < stuCount; i++)
{
if (avg[i] > maxAvg)
{
maxAvg = avg[i];
}
}
// Displaying the max average
Console.WriteLine("The highest average grade is {0}.", maxAvg);
```
So, can I use ```Array.IndexOf()``` method to find multiple indices?
Thank you.
Comment: you can use `Array.IndexOf` but this will only give you the first occurence. You could delete this one and then rerun it (loop).
Comment: You can only use array or also Classes and Lists?
Comment: Use the overload of `Array.IndexOf()` with the `StartIndex` argument to find multiple indices: https://msdn.microsoft.com/en-us/library/3b2fz03t(v=vs.110).aspx
Comment: @Tinwor I have no restrictions.
Comment: Order the collection descending by grade and grab the first people having the same grade.
Comment: Recent and active question on SO which is dealing with the same issue in multiple ways - [SO link](http://stackoverflow.com/questions/38006865/how-can-i-make-my-procedure-for-finding-the-nth-most-frequent-element-in-an-arra/38008666#38008666)
Here is the accepted answer: After you've found the highest average just loop again through the averages array to see which ones are the max ones and print the stud using the index.
```Console.WriteLine("The highest average grade is {0}.", maxAvg);
Console.WriteLine("The students with this average grade are");
for (int i = 0; i < stuCount; i++)
{
if (avg[i] == maxAvg)
{
Console.WriteLine(name[i]);
}
}
```
Comment for this answer: Don't worry. It happens to me all day.
Here is another answer: Another way is creating a class containing two properties (```name``` and ```average grade```), then generate a ```List``` and fill it in a ```for``` cycle. The next step is ```order by descending``` the list through ```average grade``` and select the first N element equals. After that you can simply print the result using a ```ForEach```
Here is another answer: Consider using a class to represent the grades as so;
```class Grade {
public String Name {get;set;}
public double Average {get;set;}
}
```
Then your code can be more like;
```Console.WriteLine("Enter the overall count of students.");
int stuCount = Convert.ToInt32(Console.ReadLine());
List<Grade> allGrades = new List<Grade>();
for (int i = 0; i < stuCount; i++)
{
Console.WriteLine("Enter the name of student # {0}.", i + 1);
var name = Console.ReadLine();
Console.WriteLine("Enter the average grade of {0}.", name[i]);
var avg = Convert.ToDouble(Console.ReadLine());
Grade current = new Grade(){
Name = name,
Average = avg
};
allGrades.Add(current);
}
// Finding the max average
double maxAvg = allGrades.Max(g => g.Average);
var highestGrades = allGrades.Where(g => g.Average == maxAvg);
Console.WriteLine("The following Student(s) have the highest average grade:");
foreach(var grade in highestGrades){
// Displaying the max average
Console.WriteLine("Student: {0}. Grade: {1}.", grade.Name, grade.Average);
}
}
```
|
Title: Running a uWSGI app that uses uwsgidecorators from shell python directly
Tags: flask;uwsgi;pythoninterpreter
Question: As you may know, ```uwsgidecorators``` are only working if your app is running in the context of ```uwsgi```, which is not exactly clear from the documentation: https://uwsgi-docs.readthedocs.io/en/latest/PythonDecorators.html
My code is using these decorators, for example for locking:
```@uwsgidecorators.lock
def critical_func():
...
```
And this works just fine when I deploy my app with uwsgi, however, when starting it directly from Python shell, I'm getting an expected error:
```File ".../venv/lib/python3.6/site-packages/uwsgidecorators.py", line 10, in <module>
import uwsgi
ModuleNotFoundError: No module named 'uwsgi'
```
Is there any known solution to run my app in both modes? obviously I don't need the synchronization and other capabilities to work when using simple interpreter, but doing some try-except importing seems like really bad coding.
Here is the accepted answer: For the meantime I did the following implementation, would be happy to know there's something simpler:
```class _dummy_lock():
"""Implement the uwsgi lock decorator without actually doing any locking"""
def __init__(self, f):
self.f = f
def __call__(self, *args, **kwargs):
return self.f(*args, **kwargs)
class uwsgi_lock():
"""
This is a lock decorator that wraps the uwsgi decorator to allow it to work outside of a uwsgi environment as well.
ONLY STATIC METHODS can be locked using this functionality
"""
def __init__(self, f):
try:
import uwsgidecorators
self.lock = uwsgidecorators.lock(f) # the real uwsgi lock class
except ModuleNotFoundError:
self.lock = _dummy_lock(f)
def __call__(self, *args, **kwargs):
return self.lock(*args, **kwargs)
@staticmethod
@uwsgi_lock
def critical_func():
...
```
|
Title: C strings malloc (output)
Tags: c
Question: I have some strange output here. Could you explain me why and how to solve it?
```int inp_str(char * string, char ** pointers[])
{
char * tmp[stringsCount];
if (strlen(string) > maxlen)
return (-1);
else {
tmp[count] = malloc(sizeof(char) * strlen(string));
strcpy(tmp[count], string);
pointers[count] = &tmp[count];
count++;
}
return count;
}
int main(){
//char * strings[stringsCount];
char ** pointers[stringsCount];
inp_str( "sdasya", pointers);
inp_str( "dasd", pointers);
inp_str( "qwe", pointers);
inp_str( "dasd", pointers);
//sort(pointers, count);
printf("%s", *pointers[0]);
printf("\n%s", *pointers[1]);
printf("\n%s", *pointers[2]);
printf("\n%s", *pointers[3]);
}
```
Here is output:
```sdasya
��uNH��H�l$ H�\$L�d$(L�l$0H��8�f.�
qwe
�bs7
```
PS. stringsCount is constant; count = 0
Comment: Welcome to Stack Overflow. Please read the [About] page soon. You should read up on how to create an SSCCE ([Short, Self-Contained, Correct Example](http://sscce.org/)). You code is fairly close to being an SSCE, but it looks like it needs just four more lines of code to be complete: two `#include` lines and the definitions of `stringsCount` and `count`. Including those would save you writing the last PS line.
Here is another answer: Because ```char * tmp[stringsCount];``` is a local variable, after the function ```inp_str``` returns, the memory of ```tmp``` is reclaimed by the system. So the pointers to that location are invalid after the function returns.
Here is another answer: I'm not sure I understand what you're trying to do here. But in any case, there are a few problems:
1) You're copying string into an uninitialized pointer. I.e. you create an array of (char *)'s which point to anywhere and you then copy the string to that location. If you're trying to point tmp to your string, don't use strcpy, just assign via tmp[count]=string;
2) tmp is created on the stack, so if you assign its value to pointers** and try to reference the address outside of the scope of this function, that memory is gone and you will likely see corrupt data.
Hope this helps. Out of curiosity, what are you trying to do in this function?
Comment for this answer: thanks, that helps. Function is for processing of input string: create pointer (in array of pointers for faster sorting), returns pointers/strings count.
Here is another answer: In addition to losing the ```tmp[]``` pointer after the function returns, you're also always allocating one byte short of the actual amount needed: ```strlen(s)``` returns the length of a string, which does not include the terminating NUL byte. What you need is (note that sizeof(char) is 1 by definition):
``` char *p = malloc(strlen(string) + 1);
strcpy (p, string);
```
to duplicate a string.
Comment for this answer: why not malloc( strlen(string) * sizeof(char) + 1 )?
Comment for this answer: @user2858814 Because as mentioned already, sizeof(char) is 1 by definition. Always. On any compiler. It will never be a different value. Multiplying by 1 is pointless and a tell-tale of not grasping the C type system.
|
Title: Date difference from current date in java
Tags: java
Question: I am developing an application in JAVA swing, in that I wanted the date difference from current date like if today is ```16/04/2013``` then it should return ```15/04/2013```. I have tried the following code:
```Calendar cal = new GregorianCalendar();
Calendar cal2 = new GregorianCalendar();
cal.roll(Calendar.DAY_OF_YEAR, -1);
//if within the first 30 days, need to roll the year as well
if(cal.after(cal2)){
cal.roll(Calendar.YEAR, -1);
}
System.out.println("Year " + cal.get(Calendar.YEAR));
System.out.println("Month " + cal.get(Calendar.MONTH));
System.out.println("Day " + cal.get(Calendar.DAY_OF_MONTH));
```
In this code I was expecting to get one day back date. But instead I am getting one month back date.
Ex. if today is ```16/04/2013```, the expected output is ```15/04/2013```, but I am getting 15/03/2013 ( one month one day back) as an output.
Comment: Are you obliged to use Calendar or would it be acceptable to use JodaTime?
Comment: This has been answered before: http://stackoverflow.com/questions/3299972/difference-in-days-between-two-dates-in-java
Comment: Joda library stuns, I suggest it.
Comment: try `cal.add(Calendar.DAY_OF_MONTH, -1);`
Here is another answer: That's a classic example why java.util.Date implementation sucks: Months numeration starts in zero:
```0-> January
1-> February
2-> March
3-> April.
```
What you mean:
```new Date(10,1,2013) //10th of January of 2013
```
What you get: 10th of February of 3983 (1970+2013)
Here is another answer: You dont need any manual manipulations, Calendar will do all necessary date arithmetic automatically, simply do this
``` Calendar cal = new GregorianCalendar();
cal.add(Calendar.DATE, -1);
```
Note that months in Calendar start from 0 so April is 3
Comment for this answer: I added output to my test, it's 15 Apr 2013
Comment for this answer: Ah, got you, 3 is Apr, months start from 0 in Calendar
Comment for this answer: `Calendar cal = new GregorianCalendar();
cal.add(Calendar.DATE, -1);
System.out.println("Year " + cal.get(Calendar.YEAR));
System.out.println("Month " + cal.get(Calendar.MONTH));
System.out.println("Day " + cal.get(Calendar.DAY_OF_MONTH));` this is what output im getting
`Year 2013
Month 3
Day 15`
|
Title: Sesiones con roles php
Tags: php;sesiones
Question: Tengo que realizar una aplicación en la que depende del usuario que esté logueado, entre en una página u otra.
Tengo en la base de datos dos tablas:
Propietarios (Dni,apellnom,password,telefono) donde:
- Dni contiene el dni de cada uno de los propietarios
- apellnom, contiene el nombre y apellidos de los propietarios
- telefono: contiene el teléfono del propietario
Clientes (Dni,apellnom,password,telefono) donde:
- Dni contiene el dni de cada uno de los clientes
- apellnom, contiene el nombre y apellidos de los clientes
- telefono: contiene el teléfono del cliente
Dentro de Propietario tengo un usuario que se llama administrador. Quiero que al loguearme con su dni"1111A" y su contraseña acceda a una página que solo pueda visualizar el.
Tambien necesito que en otras páginas puedan verla o los clientes, o los propietarios.
Os dejo el código del manejador de sesiones:
```<?php
//Recibimos las dos variables
$usuario=$_POST["usuario"];
$password=$_POST["password"];
session_start();
$conexion=mysqli_connect("localhost","root","","inmobiliaria");
mysqli_set_charset($conexion, "utf8");
$consulta="SELECT * FROM `clientes` WHERE Dni='".$usuario."' AND PASSWORD='".$password."'";
$resultado=mysqli_query($conexion,$consulta);
//si es cliente
if(mysqli_num_rows($resultado)==1){
$fila=mysqli_fetch_assoc($resultado);
$_SESSION['clientes']=$fila;
header("Location: index.php");
}
//si es propietario
$consulta="SELECT * FROM `propietarios` WHERE Dni='".$usuario."' AND PASSWORD='".$password."'";
$resultado=mysqli_query($conexion,$consulta);
if(mysqli_num_rows($resultado)==1){
$fila=mysqli_fetch_assoc($resultado);
$_SESSION['propietarios']=$fila;
header("Location: index.php");
}
/* Si no el usuario no se encuentra en ninguna de las dos tablas
imprime el siguiente mensaje */
$mensajeaccesoincorrecto = "El usuario y la contraseña son incorrectos, por favor vuelva a introducirlos.";
echo "<a href='index.php'>". $mensajeaccesoincorrecto."</a>";
?>
</body></html>`
y esta la página a la que intento entrar con el usuario con dni 1111A de la tabla propietarios.
<?php
echo
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<html>
<head>
<title>Roles y sesiones</title>
</head>
<body>';
session_start();
include('funciones.php');
cabecera('INMOBILIARIA');
echo "<div id=\"contenido\">\n";
echo "<h1>Bienvenidos - Inmobiliaria</h1>";
echo "</div>";
if(isset($_SESSION['propietarios'])){
$conexion=mysqli_connect("localhost","root","","inmobiliaria");
mysqli_set_charset($conexion, "utf8");
$sqlListado="SELECT Dni, apellnom, telefono FROM propietarios";
$sqlListado.=" order by Dni";
$resultPrincipal=$conexion->query($sqlListado);
$numLineas=$resultPrincipal->num_rows;
if($numLineas>0){
echo "<table align=center border=2 bgcolor='#F0FFFF' >";
echo "<td align=center width='70px'><b>Listado de Propietarios: </b></td>";
echo '<table border="1" bgcolor="efd5c4" width="300px" align=center><tr><th>DNI</th><th>Nombre y apellidos</th><th>Teléfono</th></tr>';
while ($fila=$resultPrincipal->fetch_assoc()){
extract($fila);
echo "<tr><td>$Dni</td><td>$apellnom</td><td>$telefono</td>";
echo " </td> </tr>";
}
}
else{
echo "<h3>No hay ningun propietario registrado.</h3>";
}
$sqlListado="SELECT Dni, apellnom, telefono FROM clientes";
$sqlListado.=" order by Dni";
$resultPrincipal=$conexion->query($sqlListado);
$numLineas=$resultPrincipal->num_rows;
if($numLineas>0){
echo "<table align=center border=2 bgcolor='#F0FFFF' >";
echo "<td align=center width='70px'><b>Listado de Clientes: </b></td>";
echo '<table border="1" bgcolor="efd5c4" width="300px" align=center><tr><th>DNI</th><th>Nombre y apellidos</th><th>Teléfono</th></tr>';
while ($fila=$resultPrincipal->fetch_assoc()){
extract($fila);
echo "<tr><td>$Dni</td><td>$apellnom</td><td>$telefono</td>";
echo " </td> </tr>";
}
}
else{
echo "<h3>No hay ningun cliente registrado.</h3>";
}
}else{
// nos envía a la siguiente dirección en el caso de no poseer autorización
header("location:index.php");
}
?>
```
Comment: ¿Qué has intentado? ¿Qué errores has obtenido?
Comment: En el indice tengo un login, inicio sesion con un usuario de la tabla propietarios e intengo entrar a esa página, y me lo deja ver. Pero si entro con un usuario de la tabla clientes tambien me deja entrar en esa página. Por lo que deja entrar a cualquier usuario que esté logueado. Lo que necesito es que por ejemplo ahí solo entre un usuario concreto de la tabla propietarios. Si necesitas algún dato más te lo pongo.
Here is the accepted answer: Para empezar, te sugiero que aprendas el uso de variables de sesión con un ejemplo mucho más simple, fácil de entender y de seguir. Una vez que tengas clara su lógica, ya le puedes añadir todo lo que vayas necesitando. Algo así:
```<?php
// inicias sesión
session_start();
// inicias la conexión a tu base de datos
$conn = new mysqli('localhost','root','','stackoverflow');
// si el usuario te pide que cierres su sesión, la reinicias
if(isset($_GET['logout'])){
session_destroy();
session_start();
}
// si te han enviado el formulario de login, valida al usuario
if(isset($_POST['usuario'])){
$rs=$conn->query("
SELECT * FROM clientes
WHERE dni='".$_POST['usuario']."'
AND `password`='".$_POST['password']."';
");
if($rs->num_rows) $_SESSION['usuario']='cliente';
$rs=$conn->query("
SELECT * FROM propietarios
WHERE dni='".$_POST['usuario']."'
AND `password`='".$_POST['password']."';
");
if($rs->num_rows) $_SESSION['usuario']='propietario';
}
// si no se ha logueda correctamente, solicita datos de acceso
if(!isset($_SESSION['usuario'])){
echo '
<form method="post">
<input name="usuario" autofocus>
<input name="password" type="password">
<button>Acceder</button>
</form>
';
exit();
}
echo '
<div style="background-color:pink">
Si has llegado hasta aquí es que eres: '.$_SESSION['usuario'].'
</div>
<div>
<a href="?logout=1">Salir</a>
</div>
';
```
No me hace mucha gracia que las consultas no sean preparadas o ese modelo de datos con dos tablas diferentes para validar usuarios, pero bueno, se trata de que veas los pasos que habría que dar. Tampoco se trata de hacer una primera versión perfecta, sino de que se entienda y te permita crecer. De hecho, podrías haberte hecho una validación hardcodeada y te evitabas toda la parte de la base de datos.
Fíjate que lo tienes todo en el mismo fichero y, si algo te falta, lo vas pidiendo: ¿No tengo variable de sesión? Muestro formulario de login ¿Me envían datos de login? Los valido en la base de datos. Si ya lo tienes todo, pues directamente lo muestras. Prueba y me dejas las dudas en los comentarios. Ánimo con ello.
Comment for this answer: Muchas gracias así lo veo mucho mas claro y creo que he logrado realizar lo que quería. Estoy estudiando un ciclo de DAW y de momento es la forma de la que nos están "enseñando".
Comment for this answer: Pues, ya sabes: divide y vencerás :) [Recuerda validar y votar](https://es.stackoverflow.com/help/someone-answers) y [Gana +2 de reputación](https://es.meta.stackoverflow.com/a/3762/119615)
|
Title: Cannot store Date variable in database in Java
Tags: java;database;jsp;jakarta-ee;servlets
Question: I am trying to keep the last login date of a user in the database. Here are the necessary parts:
In my login page, I create a Date object and put it into my session, I import java.util.Date:
```<%
Calendar c = Calendar.getInstance();
Date l = new Date(c.get(Calendar.YEAR),c.get(Calendar.MONTH),c.get(Calendar.DAY_OF_MONTH),c.get(Calendar.HOUR),c.get(Calendar.MINUTE)); //the midnight, that's the first second of the day.
//Globals.customer.lastlogin=l;
session.setAttribute("lastlogin", l); %>
```
Then when login is successful, I update my database in my servlet, this servlet is called when login button is clicked:
```try {
int result=-1;
PreparedStatement checkDB = (PreparedStatement) con.prepareStatement(
"UPDATE users set lastlogin='"+(Date)session.getAttribute("lastlogin")+"' where username='"+session.getAttribute("username")+"'");
result= checkDB.executeUpdate();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
```
I keep lastlogin as a Date variable in my Database. But I get the following error when trying to update last login:
```com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect date value: 'Wed Jul 02 05:49:00 VET 3913' for column 'lastlogin' at row [email protected](MysqlIO.java:2936)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1601)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1710)
at com.mysql.jdbc.Connection.execSQL(Connection.java:2436)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1402)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1694)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1608)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1593)
at classes.LoginServlet.service(LoginServlet.java:94)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:662)
```
Can anyone help me with this? Thanks
Comment: May be this can help - http://stackoverflow.com/questions/530012/how-to-convert-java-util-date-to-java-sql-date
Here is another answer: You should take advantage of the PreparedStatement and use ? placeholders for your parameters.
```PreparedStatement checkDB = (PreparedStatement) con.prepareStatement(
"UPDATE users set lastlogin=? where username=?");
checkDB.setDate(1, (Date)session.getAttribute("lastlogin"));
checkDB.setString(2, session.getAttribute("username"));
```
That will format the date correctly as required by your database.
Comment for this answer: Thanks, but by using java.sql.date i cannot store hours and minutes is there any way to do this?
Comment for this answer: Use java.sql.Timestamp to store date with time. `java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(utilDate.getTime());` and then use `checkDB.setTimestamp` instead of `checkDB.setDate`.
Here is another answer: ```try {
int result=-1;
String dateToInsert = new SimpleDateFormat(yyyy-MM-dd).parse((Date)session.getAttribute("lastlogin"));
PreparedStatement checkDB = (PreparedStatement) con.prepareStatement(
"UPDATE users set lastlogin='"+dateToInsert+"' where username='"+session.getAttribute("username")+"'");
result= checkDB.executeUpdate();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
```
Try with this .
The problem was you have date object in your session in the format that cannot insert into D.B. The date should be in format that compatible with D.B
Here is another answer: You should use a question mark to parametrise PreparedStatements.
Try this (Make sure the Date is java.sql.Date):
```String getUserLastLogin = "UPDATE users set lastlogin=? where username=?";
Date lastLogin = (Date)session.getAttribute("lastlogin");
String username = session.getAttribute("username");
PreparedStatement checkDB = (PreparedStatement) con.prepareStatement(getUserLastLogin);
checkDB.setDate(1, lastLogin);
checkDB.setString(2, username);
result= checkDB.executeUpdate();
```
Also, add a finally block after the catch and make sure you close your PreparedStatement, and then your Connection so you don't leave open database connections.
Comment for this answer: Use the Calendar, and then convert it to a date when you need to store it in the database.
Comment for this answer: Sorry, you should be using java.sql.Timestamp.
Comment for this answer: Thanks, but by using java.sql.date i cannot store hours and minutes is there any way to do this?
Comment for this answer: yes, but this can be done in java.util.date, java.sql.date has no proper constructors for this, or i do not know
Here is another answer: you need to take the ```java.sql.timestamp``` to get the time as well ...
Here is another answer: You may need to check whether you are using java.sql.Date or java.util.Date. Use java.sql.date to avoid any compatibility issues.
Comment for this answer: @constructor If you can, then consider stroring the time in milliseconds in DB and format it when you read it.
Comment for this answer: i am using java.util.date, but when i use sql.date i cannot store minutes and hour right? How can i do it?
|
Title: Why I can see project in Google Cloud Platform which I didn't created?
Tags: google-cloud-platform
Question: On resources pending deletion page in Google Cloud Platform Console I can see project which I didn't created.
```Name: Global Site Operations 602748
ID: projects/tamzidms-github-io
```
Can someone explain this or does someone else experience similar issue?
Comment: @JohnHanley what if there is no any other project member, and this is a simple account I created recently with no [email protected].
Comment: @JohnHanley I got the same projects in my cloud console and I never created them. and I have nobody related to this account, I even created the gmail account recently and never told anyone about it.
but yet, I found 3 projects that I have never seen before, even worse, one had billing enabled.
Comment: @JohnHanley this are the projects on my account:https://i.stack.imgur.com/pXvpw.png. They all seem too meaningful to believe they are generated by google.
All the first 3 in the image are projects I haven't created.
Comment: I've never created those projects. It's the project IDs as you stated that made me really suspicious and changed my password. I disabled billing on those projects and immediately deleted them. I can't see the audit log since they're deleted. But I'm dead sure I never created those projects, I even had searched them on google to see If anyone had same thing happen before. I've even never thought of those words on the Project ID before. and the number `-308710` at the end made me even more suspicious. Incase it's an ID by the creator, for many victims, operating like those crypto mining malware.
Comment: Thanks for the reply. I don't have an organization, it is my solo account. Do you suggest someone could add me to his project?
Comment: We would need more information. Do you have an organization? If yes, and you have the correct roles, you can see all projects beneath the organization level. To obtain access to a project is as simple as adding your email address to my project. Google has good documentation on IAM plus there are good videos on YouTube.
Comment: Yes, a Project member with the correct roles can add any email address to their project. To see the projects that you can access `gcloud projects list`. This does not make you responsible for the project.
Comment: @Abraham - How does your comment apply to the question asked?
Comment: @Abraham - I cannot answer. The project IDs are interesting in that these appear to be Google created project IDs. Are the Project IDs (not names) exactly the same? I have dozens of projects, and I have never seen this. Do you see anything in Cloud Logging under Audited Resource?
Comment: @Abraham - Your comment was that you had the "same" projects. Those Project IDs do not have numbers at the end, which indicates they were either created a long time ago, or those are GCP names. Your Project IDs look very much like you created them. The Cloud Logging audit logs will tell you who (IAM Identity) created your projects.
|
Title: Did I install correctly the wireless card driver?
Tags: linux;firmware;wifi-driver
Question: I am trying to fix the WiFi connection on an Asus E200 laptop, following these instructions: https://wiki.debian.org/InstallingDebianOn/Asus/E200HA.
The laptop has the latest LXLE distribution, with a kernel updated to version 4.15. The wireless card is Qualcomm Atheros QCA9377.
I have downloaded the non free driver (https://packages.debian.org/buster/firmware-atheros) and run:
```sudo apt-get install ./firmware-atheros-20190114-1_all.deb
```
I had to uninstall the ```linux-firmware``` package to install the non free driver. Then I ran:
```sudo modprobe -r ath10k_pci
sudo modprobe ath10k_pci
```
and rebooted. I am not sure this is the right procedure and, since I am getting the same errors as with the free driver, I am wondering if I made a mistake or missed a step somewhere.
Comment: LXLE is based on Ubuntu. so, you should be following instructions for Ubuntu. Installing Debian specific packages, especially those related to firmware/drivers is usually NOT a good idea.
Here is the accepted answer: After spending way too much time following various threads and possible solutions, I am giving up. If somebody has a Linux laptop with this wireless card, my suggestion is to get a USB cable and set up tethering with an Android smartphone. Takes 5 min and works quite well.
|
Title: With reactor-netty-http:1.0.20, on setting HttpServer.idleTimeout(idleTimeoutInMs), no GOWAY packet is seen in tcpdump
Tags: timeout;spring-webflux;reactor-netty;graceful-shutdown
Question: With reactor-netty-http:1.0.20 (with spring-webflux), on setting HttpServer.idleTimeout(idleTimeoutInMs), no GOWAY packet is seen in tcpdump.with protocol H2C, HTTP11, but directly a FIN packet at TCP level.
HttpServer.idleTimeout(idleTimeoutInMs) definition says,
.idleTimeout => Specifies an idle timeout on the connection when it is waiting for an HTTP request (resolution: ms). Once the timeout is reached the connection will be closed.
This definition doesn't say anything about the level at which it sets the idletimeout, is it directly at TCP level or HTTP level.
As per the observation from tcpdump, the idle connection termination is not graceful. The connection gets terminated on reaching the idle timeout, as seen by FIN packet at TCP level. But no GOAWAY packet is observed.
Need to configure idle timeout at HTTP level so that it is accompanied with a GOAWAY packet to terminate connection gracefully.
```@Configuration
public class NettyServerFactoryConfig implements WebServerFactoryCustomizer<NettyReactiveWebServerFactory> {
@Value("${server.http.port}")
private Integer httpPort;
@Value("${server.idleTimeout}")
private Integer idleTimeout;
@Value("${server.settingsMaxConcurrentStreams}")
private Integer settingsMaxConcurrentStreams;
@Override
public void customize(NettyReactiveWebServerFactory factory) {
LoopResources resource = LoopResources.create("my-resource");
ReactorResourceFactory reactorResourceFactory = new ReactorResourceFactory();
reactorResourceFactory.setLoopResources(resource);
reactorResourceFactory.setUseGlobalResources(false);
factory.setResourceFactory(reactorResourceFactory);
Http2 h2 = new Http2();
h2.setEnabled(true);
factory.setPort(httpPort);
factory.setHttp2(h2);
Consumer<Builder> h2Settings = s -> s.maxConcurrentStreams(settingsMaxConcurrentStreams);
factory.addServerCustomizers(httpServer -> httpServer.http2Settings(h2Settings));
factory.addServerCustomizers(httpServer -> httpServer.idleTimeout(Duration.ofMillis(idleTimeout)));
factory.addServerCustomizers(builder -> builder.protocol(HttpProtocol.H2C, HttpProtocol.HTTP11));
factory.setShutdown(Shutdown.GRACEFUL);
}
}
```
Comment: Please create an issue here https://github.com/reactor/reactor-netty/issues and provide a reproducible example.
Comment: The issue was reported https://github.com/reactor/reactor-netty/issues/2412
|
Title: Graphviz executables not found. Python 3
Tags: python-3.x;graphviz
Question: I`m trying to get this code to run:
Getting started with Graphviz and Python
http://matthiaseisen.com/articles/graphviz/
```import graphviz as gv
g1 = gv.Graph(format='svg')
g1.node('A')
g1.node('B')
g1.edge('A', 'B')
print(g1.source)
```
this part works fine, but...
```filename = g1.render(filename='img/g1')
print (filename)
```
-> make sure the Graphviz executables are on your systems' PATH
I found similar questions/answers, but I don```t know much about the Windows registry, so I don```t dare to experiment a lot there. I downloaded Graphviz as zip-file, and I did conda install graphviz at some point. Python 3.6 is installed per default. C:\Users\Oliver\Appdata\Local\Programs\Python36.
I go to Control Panel - System - Advanced System - Environment Variables, but what exactly do I have to change there?
Here is another answer: I could finally solve this:
The graphviz zip I had direcly extracted directly in my Downloads-folder (or wherever you want to have it).
Control Panel - System - Advanced System - Environment Variables
Then in the lower half, System Variables (not User variables), double-klick Path: klick ```New``` and browse to the graphviz bin-folder.
|
Title: How to translate lookup placeholder text?
Tags: translation;translation-workbench
Question: I cant find the way to translate the colored text, can you help me?
Here is the accepted answer: Looks like you are trying to translate standard object labels.
Go to ```'Customize' > 'Tab Names and Labels' > 'Rename Tabs and Labels'``` , then select the language you want to translate the custom / standard object label and then click on ```Edit``` besides the object and change the text according to language. In below screenshot, I translated for object ```Test Object```:
OUTPUT:
BEFORE:
AFTER:
|
Title: Failed to install "expo-cli" using "npm install -g expo-cli"
Tags: javascript;react-native;npm;expo
Question: I am failed to install expo-cli using ```npm install -g expo-cli``` for android application creation.
NPM version: ```7.19.1```
Node version: ```v15.14.0```
After using ```npm install -g expo-cli``` it's failed to install and the error is given below,
```npm ERR! code EACCES
npm ERR! syscall rename
npm ERR! path /usr/local/lib/node_modules/expo-cli
npm ERR! dest /usr/local/lib/node_modules/.expo-cli-dKBr48UN
npm ERR! errno -13
npm ERR! Error: EACCES: permission denied, rename '/usr/local/lib/node_modules/expo-cli' -> '/usr/local/lib/node_modules/.expo-cli-dKBr48UN'
npm ERR! [Error: EACCES: permission denied, rename '/usr/local/lib/node_modules/expo-cli' -> '/usr/local/lib/node_modules/.expo-cli-dKBr48UN'] {
npm ERR! errno: -13,
npm ERR! code: 'EACCES',
npm ERR! syscall: 'rename',
npm ERR! path: '/usr/local/lib/node_modules/expo-cli',
npm ERR! dest: '/usr/local/lib/node_modules/.expo-cli-dKBr48UN'
npm ERR! }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as the current user
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator.
npm ERR! A complete log of this run can be found in:
npm ERR! /home/imdadul/.npm/_logs/2021-07-27T05_54_14_633Z-debug.log
```
I have tried to solve this issue and use the below command's: ```npm cache clean --force``` but it was not solved and that's why I have used ```sudo npm cache clean --force``` command because of using Ubuntu 20.04 operating system and again run ```npm install -g expo-cli``` command.
Note: I am failed every time and I need help to install ```expo-cli```. Advanced thanks and please concern the attached file.
Here is the accepted answer: You have to try two methods:
First is to use the command with sudo npm install expo-cli (if you have not used sudo)
the Second is to delete node_modules and install run again npm install
Maybe it will work
Comment for this answer: which option help you ?
Comment for this answer: Delete the previous "node_modules" and then use the `sudo npm install -g expo-cli ` command to install
|
Title: Is there a way to retrieve data from a second Elasticsearch instance in Kibana?
Tags: elasticsearch;kibana
Question: I have an already an ELK stack. I wonder if it is possible to retrieve data from a second Elasticsearch instace in Kibana?
Comment: This is whole different elasticsearch database, different than the existing ELK stack.
Comment: What do you exactly mean with *a second Elasticsearch **instance***? Another node or whole cluster?
Here is the accepted answer: When you say "second Elasticsearch instance", I assume you mean a second cluster. For this you can use Cross Cluster Search (CCS), which you will first need to configure in Elasticsearch:
```PUT _cluster/settings
{
"persistent": {
"cluster": {
"remote": {
"your_remote_cluster": {
"seeds": [
"<dns-name>:9300"
]
}
}
}
}
}
```
Then you need to add the Elasticsearch cluster in Kibana on which you configured the remote cluster (where you ran the ```PUT _cluster/settings```). And finally add the right index pattern in Kibana](https://www.elastic.co/guide/en/kibana/current/management-cross-cluster-search.html) with ```your_remote_cluster:<pattern>``` (```your_remote_cluster``` is the name you have configured in the PUT).
PS: If you are after a HA setup where one Kibana instance can talk to multiple Elasticsearch nodes in the same cluster, use the ```elasticsearch.hosts``` setting added in 6.6.
Here is another answer: Link to kibana configuration bellow. Kibana is only able to target one cluster, so you can target different url but with very important restriction.
https://www.elastic.co/guide/en/kibana/current/settings.html
elasticsearch.hosts:
Default: "http://localhost:9200" The URLs of the Elasticsearch instances to use for all your queries. All nodes listed here must be on the same cluster.
|
Title: Use a vector from an R markdown code chunk in a LaTeX environment (pmatrix)?
Tags: r;latex;r-markdown
Question: I want to create a column vector in R markdown from a variable in a code chunk. Namely, I want to use the ```\begin{pmatrix}``` environment. But in LaTeX, each element of the vector is separated by a newline ```\\```. The code in LaTeX would be as follows:
```\begin{pmatrix} x_1 \\ x_2 \\ x_3 \end{pmatrix}```.
I want it to produce the following:
column vector with parentheses
where x_1, x_2, and x_3 are the elements of a numeric vector in an R code chunk.
Is this possible?
Here is the accepted answer: You can have R create the LaTeX code, and put it in a chunk with ```results = 'asis'```, or you can use inline R code:
```---
title: "Untitled"
author: "Gregor"
date: "December 5, 2018"
output: pdf_document
---
```{r echo = FALSE, results = 'asis'}
x = 1:3
cat("$$ \\begin{pmatrix}", paste(x, collapse = " \\\\ "), "\\end{pmatrix} $$", sep = " ")
```
Or inline code:
$$
\begin{pmatrix}
`r x[1]` \\ `r x[2]` \\ `r x[3]`
\end{pmatrix}
$$
Alternately
$$
\begin{pmatrix}
`r paste(x, collapse = " \\\\ ")`
\end{pmatrix}
$$
```
Yielding:
If you're doing this a lot, you could easily make a little convenience function, possibly even a hook, depending how you want to use it.
Comment for this answer: Your third example is exactly what I was looking for—a method that easily generalizes to any size without additional code.
|
Title: Send text messages between two computers through internet with delphi?
Tags: delphi;p2p
Question: I want to write a app which will run on different computers and need all of then to communicate with each other like "utorrent" (peer to peer). This app only will send text messages.
How can I do this? I mean sending one message to remote computer on the internet?
I have a website and every app at start can send some information to it and find information of other apps on other computers (with PHP) but I do not know how address one computer through internet and send the data directly to that. I can find the ip address with PHP but it is the ip address of router (ISP).
How a message reaches a computer? I'm wondering about addressing every computer?
My brain really stuck here, I really appreciate any help. Thanks.
Here is the accepted answer: In a peer-to-peer network there's no centralized server for transmitting the data from one client to another, in this case the clients must be able to act as both the server and client. This means that either you'll have to be using UPnP like most modern torrent clients, which handles port forwarding in the router, or you'll have to manually forward a port to the computer in the router.
A centralized server (like a torrent tracker) is usually used to make the clients aware of each other's existence and tell them where to connect. This is where your PHP script comes in, though PHP might not offer the most effective way of doing this, assuming you're using it in combination with a webserver to serve the data though the http protocol.
As for actual text communication, you could use the Indy socket library for that. I found this example, basically which shows how to do it: http://www.ciuly.com/delphi/indy/indy-10-client-server-basic-demo/
Comment for this answer: as I said, either you have to manually forward the port or you have to use UPnP to have the router to it for you. This appears to be an Indy compatible library to do that: http://www.whitebear.ch/upnp.htm
Comment for this answer: I know these things. My question was that how forward a port in the router to the computer where my app is? We have not acsses the router. think about utorrent. It easly forwards data through every router in the internet to the peer. I do not understant that what is the exact address of a computer in the internet witch I have to enter it on Indy to comunicate.
Comment for this answer: How router will know that it have to forwards data of a port (for example 5689) to a computer witch my app is?
Comment for this answer: Those examples did not help much
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.