qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
list
response
stringlengths
0
115k
31,532,828
``` import java.util.Date; import java.util.Timer; import java.util.TimerTask; import android.app.Service; import android.content.Context; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import android.widget.Toast; public class LocationService extends Service { private LocationDatabaseHelper mLocationDatabaseHelper; private LocationModel mLocationModel; private Date mDate; private Handler mHandler = new Handler(); private Timer mTimer = null; private int mCount = 0; public static final long NOTIFY_INTERVAL = 30 * 1000; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { // cancel if already existed if (mTimer != null) { mTimer.cancel(); } else { // recreate new mTimer = new Timer(); } mLocationModel = LocationModel.getInstance(); // schedule task mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL); } @Override public void onDestroy() { mTimer.cancel(); } private class TimeDisplayTimerTask extends TimerTask implements LocationListener { @Override public void run() { mHandler.post(new Runnable() { @Override public void run() { //I send message to draw map here sendMessage(); LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, TimeDisplayTimerTask.this); } }); } @Override public void onLocationChanged(Location location) { // I get location and do work here } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } } private void sendMessage() { Intent intent = new Intent("my-event"); intent.putExtra("message", "data"); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } } ``` What I want is to get user location after every 30 seconds but this code does not work as I expected. It gets location very fast (I think every second). I tried to get location this way because it can get my current location immediately after I start my app.I have tried getLastKnowLocation before, but it give me the last known location which is very far from where I am. Please show me how fix this.Thank you!
2015/07/21
[ "https://Stackoverflow.com/questions/31532828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4209039/" ]
in requestLocationUpdates method second parameter is minimum time interval between location updates, in milliseconds, So you just need to do this: ``` LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30 * 1000, 0, TimeDisplayTimerTask.this); ```
41,614
> > * What does her parents do? > * What do her parents do? > > > Which one is correct? Can you have *does* and *do* in the same sentence like the first one? Would it be incorrect because parents is plural so *do* must be used throughout?
2014/12/10
[ "https://ell.stackexchange.com/questions/41614", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/-1/" ]
> > What do her parents do? > > > Here the subject of the sentence is *her parents*. Because *her parents* is plural the auxiliary verb *DO* must agree with the plural noun phrase, so we need *do* and not *does*. The auxiliary verb *DO* is the first verb in the sentence. This is the verb that moves in front of the subject. It has no meaning, it just helps to make the sentence a question. The verb after auxiliary *Do* is ***ALWAYS*** an infinitive. It can never be "Xing", "Xs", "Xed" or "to X".: * Does he ~~eats~~? * Did they ~~went~~? * We don't ~~liking~~... * They didn't ~~to come~~. It should be: * Does he eat? * Did they go? * We don't like ... * They didn't come. We can only have one auxiliary verb *DO* in a sentence. However, the second *DO* in the Original Poster's example is the main verb. It's the lexical verb *DO*. It isn't an auxiliary. Because it comes after the auxiliary *DO*, it must be in the infinitive. The verb after *auxiliary* *DO* is ***ALWAYS*** an infinitive. Therefore the sentence must be like this: * What do her parents do? Hope this is helpful!
65,811,090
My code worked fine but I changed some things and now it doesn't... When I type `!ping` in the any channel it doesn't work. * the bot is on the server and an admin. * I changed the token down there * here's the code: Does anyone see something?? ```js const Discord = require(`discord.js`), client = new Discord.Client(), prefix = `!`, NO = `801418578069815297` YES = `801418578300764180` client.login(`bruh`) client.once(`ready`, () => { console.log(`online.`) client.user.setPresence({ status: `online`, game: { name: `You`, type: `WATCHING` } }) }) client.on(`message`, message =>{ if(!message.content.startsWith(prefix) || message.author.client) return const args = message.content.slice(prefix.length).trim().split(` `) const arg = args.toString().split(sep) const command = args.shift().toLowerCase() if(command === `ping`){ message.channel.send(`pong!`) } } ) ``` EDIT: I put some log outputs in: ```js const Discord = require("discord.js"); let client = new Discord.Client(); let prefix = "!"; console.log("discord, client, prefix defined.") client.login("bruh"); console.log("logged in.") client.once("ready", () => { console.log("online."); client.user.setPresence({ status: "online", game: { name: "You", type: "WATCHING" } }); }); client.on("message", message =>{ console.log("message recieved") if(!message.content.startsWith(prefix) || message.author.client) return; console.log("it's a command.") const args = message.content.slice(prefix.length).trim().split(" "); console.log("splitted.") const arg = args.toString().split(sep); console.log("args defined.") const command = args.shift().toLowerCase(); console.log("command defined.") if(command === "ping") { console.log("command identified:"+command) message.channel.send("pong!"); console.log("message sent.") } }); ``` The output is: ``` logged in. online. message recieved ``` I looked at that closely but still didn't find anything...
2021/01/20
[ "https://Stackoverflow.com/questions/65811090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14081166/" ]
The problem is, you're using commas where you should be using semicolons, so JS will be interepreting this strangely which will give you undefined behaviour. You should also preferably prefix your variables with `let`, `var` or `const` otherwise this could also lead to undefined behaviour. It is recommended to use `let` over `var`. Try the code below to fix your problem: ```js const Discord = require(`discord.js`); let client = new Discord.Client(); let prefix = '!'; let NO = "801418578069815297"; let YES = "801418578300764180"; client.login(`bruh`); client.once(`ready`, () => { console.log(`online.`); client.user.setPresence({ status: `online`, game: { name: `You`, type: `WATCHING` } }); }); client.on(`message`, message =>{ if(!message.content.startsWith(prefix) || message.author.client) return; const args = message.content.slice(prefix.length).trim().split(' '); const command = args.shift().toLowerCase(); if(command === `ping`) { message.channel.send(`pong!`); } }); ```
45,749,458
I am trying to identify lines in a file that have either 4 integer or 2 double values. My regular expression is as below: ``` var match = new Regex(@"^(?<Values>(((\d+\s*){4})|(\d+\.\d+\s*){2}))$"); ``` Sample of lines in the file getting parsed: ``` element 1 2 8 24 2 1 1 0 1 129 2 2 0 0 30.200001 1000.0000 208 0 0 0 0 0 0 0 ..... ..... ``` Here, my regular expression matches correctly for above lines no 4 & 5. That's ok. But, it's also matching line no 3 (0 1 129). That's the problem for me. **Kindly suggest:** 1. Why my regular expression is matching line no 3. 2. Correct regular expression that matches exactly either 4 no. of integers or 2 no. of double values in a line.
2017/08/18
[ "https://Stackoverflow.com/questions/45749458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1762551/" ]
you directly store result into array. so your code should be like ``` $reader= \Excel::load(Input::file('import_file'))->toArray(); return redirect()->back()->with('reader', $reader); ```
5,706,194
I have inherited a .NET 4 VS2010 solution consisting of a WinForms app and a web service. I don't have access to a server that's running a copy of the web service but I have to run, debug, upgrade and test the project that accesses the web service as well as the web service code. Later, I also want to quickly switch between a deployed web service and the code in my local project What's the best strategy for changing the projects so I can make changes to both projects, test locally, deploy the web service then test against that? If I find issues, I want to switch back to "local" mode to debug. Thanks team!
2011/04/18
[ "https://Stackoverflow.com/questions/5706194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/686433/" ]
The easiest is to host the service locally in visual studio and change the service url to switch between the production service and the local one. You can automatically switch between the services by checking for Debug and Release modes using `#if` and `#else` directives. You can also use the interface to provide a stub of the service. This will also make unit testing easier.
54,003,335
I want to implement javascript function to delete confirmation. After clicking `ok` button of confirmation alert table `tr` should be removed from front end. I have used `$("#confirm-btn-alert").click(function()` for confirmation alert which is in `sweet-alert-script.js` and `function SomeDeleteRowFunction(o)` which is in `newfile.html` for remove `tr` sweet-alert-script.js ``` $(document).ready(function(){ $("#confirm-btn-alert").click(function(){ swal({ title: "Are you sure?", text: "Once deleted, you will not be able to recover this imaginary file!", icon: "warning", buttons: true, dangerMode: true, }) .then((willDelete) => { if (willDelete) { swal("Poof! Your imaginary file has been deleted!", { icon: "success", }); } else { swal("Your imaginary file is safe!"); } }); }); }); ``` newfile.html ``` <script> function SomeDeleteRowFunction(o) { var p=o.parentNode.parentNode; p.parentNode.removeChild(p); } </script> ```
2019/01/02
[ "https://Stackoverflow.com/questions/54003335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10856425/" ]
Use shared preferences to save the data, then on start up use an if statement to determine whether the user needs to fill it out.
62,653,757
I integrated React Froala Editor to my website. It's a simple project and I want to show paragraph select drop down. But it doesn't work. Is it related to version? ``` this.state = { model: ``, tags: [], config: { theme: 'foobar', heightMax: 800, height: 800, toolbarButtons: ['bold', 'italic', 'underline', 'strikeThrough', 'fontFamily', 'fontSize', '|', 'paragraphStyle', 'paragraphFormat', 'align', 'undo', 'redo', 'html'] } } <FroalaEditorComponent model={this.state.model} onModelChange={this.onChange} config={this.state.config} /> ``` [![enter image description here](https://i.stack.imgur.com/rvJ1H.png)](https://i.stack.imgur.com/rvJ1H.png)
2020/06/30
[ "https://Stackoverflow.com/questions/62653757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12067813/" ]
It seems that plugins are missing. Try to import plugins in your component: ``` import 'froala-editor/js/plugins.pkgd.min.js'; ```
3,197,523
I have a question about camera calibration. I've followed approach shown in a book Learning OpenCV for camera calibration process. But the calibrated(undistorted) image is worse than the original one. Is it possible that my camera don't need calibration anymore?(means that the calibration is done by some driver or something like that)? In fact it seems that the original image is not distorted at all. I know that it's not only about distortion, but what would you recommend me to do? Thanks for every reply
2010/07/07
[ "https://Stackoverflow.com/questions/3197523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/385826/" ]
The calibration cannot be done by the driver. If you're planning 3D reconstruction, then you cannot do without a calibration matrix.
3,198,494
I am try in to get the ClientID of one of my server controls to appear in a Javascript in my aspx page. Obviously I am going about it the wrong way, but my intent should be made clear in the following: ``` doSomethingFirst(); var hid = "<% Response.Write(HidingField.ClientID) %>"; doSomethingElse(hid); ``` Any advice? Thanks.
2010/07/07
[ "https://Stackoverflow.com/questions/3198494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/316862/" ]
I'm doing a bit of guessing about your intent, so forgive me if I've guessed wrong, but I think this is what you're looking for: ``` doSomethingFirst(); var hid = document.getElementById('<%= HidingField.ClientID %>'); doSomethingElse(hid); ``` I assuming your intent is to get a reference to the DOM element represented by the client id so that you can then do some sort of javascript operation on that element.
28,592,077
> > HTTP/1.1 has served the Web well for more than fifteen years, but its > age is starting to show. > > > Can anybody explain what is the **main difference** between HTTP 1.1 and 2.0? Is there any change in the transport protocol?
2015/02/18
[ "https://Stackoverflow.com/questions/28592077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
HTTP/2 supports queries multiplexing, headers compression, priority and more intelligent packet streaming management. This results in reduced latency and accelerates content download on modern web pages. [More details here.](https://daniel.haxx.se/http2/)
33,910,676
Problem ======= On one Form I have a Multilist where each item has a "name" and an "ID number". I'd like my app to do the following: After I select an item, it will go to the "profile" screen and then it will display all the information about that person, based on the "ID number" that I will get from the Storage. Question ======== How can I get the information from the Multilist item I just clicked? And then, how can I save that info so I can use it in the "before show (Profile screen)" so I can retrieve the info from Storage. Thnaks
2015/11/25
[ "https://Stackoverflow.com/questions/33910676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5602982/" ]
I will suggest you use a MultiButton instead of Multilist, then you can add actionEvent to individual element. You can save individual element into static variables in the actionEvent and use it in the before show of your profile form. For example: Declare this globally: ``` private static String UserName = ""; ``` And initialize it as follows: ``` Container content = new Container(new BoxLayout(BoxLayout.Y_AXIS)); content.setScrollableY(true); for (int i = 0; i < YourItemsLength; i++) { final MultiButton mb = new MultiButton("Blablabla"); mb.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { UserName = mb.getTextLine1(); // or anything you want it to be //show the profile form here } }); content.addComponent(mb); } content.revalidate(); ``` In the beforeShow() of profile, call UserName and you should be able to use the value. Do the same for all the values you need.
50,314
I wanna set 4 different wallpapers in my 4 workspaces by setting in CCMS (wallpaper plugin). It just only work if show\_desktop (gconf-editor->apps/nautilus/preference) is unchecked. But after that I can not right-click on my desktop anymore. Is it possible to make wallpaper-plugin work without "disable" my desktop?
2011/06/24
[ "https://askubuntu.com/questions/50314", "https://askubuntu.com", "https://askubuntu.com/users/20503/" ]
No. And to make it possible to save my answer ("no" is a bit short) this a possible workaround that changes your actions to open a file on the desktop from 1 move with the mouse and 1 click on an icon to 2 clicks on icons and 1 mouse move: You need to use places>desktop to get to your desktop icons. So you can add in an option to show desktop from the launcher. Rightclick desktop (w/o compiz wallpaper active ;) ) and choose 'add launcher'. See image... ![enter image description here](https://i.stack.imgur.com/vJtVH.png) (command `nautilus "/home/your_username/Desktop"`) Add in an icon, move this launcher from desktop to `~/.local/share/applications` and pin this to the launcher. ![enter image description here](https://i.stack.imgur.com/acdKn.jpg)
6,375,516
Ignore the .bat extensions, just a habit from the old dos batch file days. I have 2 simple shell scripts. I want to pass a filename with spaces (some file with spaces.ext) from little.bat to big.bat, as you can see below. It won't let me put the filename in single or double quotes. First one called little.bat: ``` ./big.bat some file with spaces.ext ``` Second one called big.bat: > > cat template.iss | sed > "s/replace123/$1/g" | sed > "s/replace456/$1/g" > $1.iss > > >
2011/06/16
[ "https://Stackoverflow.com/questions/6375516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/710624/" ]
Escape spaces with another sed command. you can fine details about the idea here: [Escape a string for a sed replace pattern](https://stackoverflow.com/questions/407523/bash-escape-a-string-for-sed-search-pattern)
75,925
I implemented an application run on Raspberry Pi 3 using Android Things. This application will be able to play `rtsp` video and output to screen via HDMI port. But the audio is not working with jack 3.5mm. Below is my code: ``` public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); VideoView videoView = findViewById(R.id.video_view); videoView.setVideoPath("rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov"); videoView.start(); } } ``` **How can I fix it?**
2017/12/01
[ "https://raspberrypi.stackexchange.com/questions/75925", "https://raspberrypi.stackexchange.com", "https://raspberrypi.stackexchange.com/users/77116/" ]
The problem is that if you connect the hdmi first, it will use the hdmi as the audio output. Try connecting the audio jack first. This solved it for me.
60,336,447
I have custom hash function for unordered\_set of vectors< int >: ``` struct VectorHash { int operator()(const vector<int> &V) const { int hsh=V[0] + V[1]; return hash<int>()(hsh); }}; ``` And for two such vectors I have the same hash equal 3: ``` vector<int> v1{2,1}; vector<int> v2{1,2}; ``` But when I try to insert first vector v1 in unordered\_set, and then check if I have the same vector by hash as v2 in my unordered\_set I get false: ``` std::unordered_set<std::vector<int>, VectorHash> mySet; mySet.insert(v1); if(mySet.find(v2) == mySet.end()) cout << "didn't find" << endl; Output: "didn't find" ``` I assume that if two elements in unordered\_set have the same hash then if I have v1 in my unordered\_set, `find` method should return true, when I try to find v2. But it is not the case. Could anyone explain me what is wrong in my reasoning?
2020/02/21
[ "https://Stackoverflow.com/questions/60336447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12937832/" ]
Hash isn't everything, what you're seeing here, is a collision. Both `std::vector<int>` have the same hash value here, but after hash is calculated, `std::unordered_map` will actually actually check for equality of elements using `operator==` to check for equality of elements, which fails in this case, and fails to find the element. Collisions are a normal thing in HashMaps, not much you can do here without providing custom `operator==`.
38,990,345
I hava a javaagent Jar `simpleAgent.jar`. I used it to redifine classes in it and I cached some classes to avoid redifine ``` public class Premain { private static Instrumentation instrumentation; private static final Map<String, Class> allLoadClassesMap = new ConcurrentHashMap<>(); public static void premain(String agentArgs, Instrumentation inst) { instrumentation = inst; cacheAllLoadedClasses("com.example"); } public static void cacheAllLoadedClasses(String prfixName) { try { Class[] allLoadClasses = instrumentation.getAllLoadedClasses(); for (Class loadedClass : allLoadClasses) { if (loadedClass.getName().startsWith(prfixName)) { allLoadClassesMap.put(loadedClass.getName(), loadedClass); } } logger.warn("Loaded Class Count " + allLoadClassesMap.size()); } catch (Exception e) { logger.error("", e); } } } ``` I have three different application `app1.jar`, `app2.jar`, `app3.jar`, so when I start the three application can I use the same agent jar? Eg.: ``` java -javaagent:simpleAgent.jar -jar app1.jar java -javaagent:simpleAgent.jar -jar app2.jar java -javaagent:simpleAgent.jar -jar app3.jar ``` I don't know the javaagent's implementation, so I was scared that using the same javaagent can trigger in app1 or app2 or app3 crash.
2016/08/17
[ "https://Stackoverflow.com/questions/38990345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6704318/" ]
Each JVM instance is separate and does not "know" about other JVMs unless you do something in application level. So, generally the answer is "yes, you can use the same jar either javaagent or not for as many JVM instances as you want."
71,906,448
I need to hide or to make some field completely hidden in some field in the item class. i have tried using jquery, javascript and html but the result is not too good. ``` <div class="item"> <label for="id_mobile_number">Mobile number:</label>: <input type="text" name="mobile_number" maxlength="12" required id="id_mobile_number"> </div> <div class="item"> <label for="id_ported_number">Ported number:</label>: <input type="text" name="ported_number" value="true" maxlength="100" id="id_ported_number"> </div> <div class="item"> <label for="id_idplan">Idplan:</label>: <select name="idplan" required id="id_idplan"> <option value="" selected>---------</option> <option value="1">500 at 150 for 1month</option> </select> </div> <div class="item"> <label for="id_user">User:</label>: <select name="user" id="id_user"> <option value="">---------</option> <option value="2">[email protected]</option> <option value="3">[email protected]</option> </select> </div> Am trying to make some fields invisible or completely hidden with html but the result only hide only the input field or text property while the name of the html element still shows on the form. I want those field or element mark hidden to be completely hidden or completely invisible. users should not be able to know that there was supposed to be an item there. ``` check my code ``` i tried using javascript and only the input field is hidden while the form name and size and other still display <script type="text/javascript"> var net = document.getElementById('id_idnetwork'); net.style.display = 'hidden'; </script> ``` I tried using html but only the input is hidden while the name and other property shows am using html id to get this field. ``` #id_user { position: absolute; display: none } #id_idplan { position: absolute; display: none } ```
2022/04/18
[ "https://Stackoverflow.com/questions/71906448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18375924/" ]
You can hide siblings: ```css [for="id_user"], [for="id_user"] ~ * /* hide siblings */ { position: absolute; display: none } [for="id_idplan"], [for="id_idplan"] ~ * /* hide siblings */ { position: absolute; display: none } ``` ```html <div class="item"> <label for="id_mobile_number">Mobile number:</label>: <input type="text" name="mobile_number" maxlength="12" required id="id_mobile_number"> </div> <div class="item"> <label for="id_ported_number">Ported number:</label> <input type="text" name="ported_number" value="true" maxlength="100" id="id_ported_number"> </div> <div class="item"> <label for="id_idplan">Idplan:</label> <select name="idplan" required id="id_idplan"> <option value="" selected>---------</option> <option value="1">500 at 150 for 1month</option> </select> </div> <div class="item"> <label for="id_user">User:</label> <select name="user" id="id_user"> <option value="">---------</option> <option value="2">[email protected]</option> <option value="3">[email protected]</option> </select> </div> ``` Or much better way is to add additional classes to the `.item` elements, so you can control it instead: ```css .item4 { position: absolute; display: none; } .item3 { position: absolute; display: none; } ``` ```html <div class="item item1"> <label for="id_mobile_number">Mobile number:</label>: <input type="text" name="mobile_number" maxlength="12" required id="id_mobile_number"> </div> <div class="item item2"> <label for="id_ported_number">Ported number:</label>: <input type="text" name="ported_number" value="true" maxlength="100" id="id_ported_number"> </div> <div class="item item3"> <label for="id_idplan">Idplan:</label>: <select name="idplan" required id="id_idplan"> <option value="" selected>---------</option> <option value="1">500 at 150 for 1month</option> </select> </div> <div class="item item4"> <label for="id_user">User:</label>: <select name="user" id="id_user"> <option value="">---------</option> <option value="2">[email protected]</option> <option value="3">[email protected]</option> </select> </div> ```
31,451,935
While writing interface in java 8 i noticed behavior that i was able to define method in interface without any compile time error. ``` public interface AdvanceMediaPlayer { public static void playVlc(String fileName) { System.out.println("play VLC"); } public abstract void playMp4(String fileName); } ``` Please explain why is this happening. As far as I am aware we cant implement methods inside interfaces.
2015/07/16
[ "https://Stackoverflow.com/questions/31451935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2828006/" ]
Java8 provides the ability to create default method implementations: <https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html>
308,829
I have often heard developers mention that Java can't "*do [Real Time](https://en.wikipedia.org/wiki/Real-time_computing)*", meaning a Java app running on Linux cannot meet the requirements of a deterministic real-time system, such as something running on RIOT-OS, etc. I am trying to understand *why*. My [SWAG](https://en.wikipedia.org/wiki/Scientific_Wild-Ass_Guess) tells me that this is probably largely due to Java's Garbage Collector, which can run at any time and totally pause the system. And although there are so-called "pauseless GCs" out there, I don't necessarily believe their advertising, and also don't have $80K-per-JVM-instance to fork over for a hobby project! I was also reading [this article about running drone software on Linux](http://owenson.me/build-your-own-quadcopter-autopilot/). In that article, the author describes a scenario where Linux almost caused his drone to crash into his car: > > I learnt a hard lesson after choosing to do the low level control loop (PIDs) on the Pi - trying to be clever I decided to put a log write in the middle of the loop for debugging - the quad initially flied fine but then Linux decided to take 2seconds to write one log entry and the quad almost crashed into my car! > > > Now although that author wrote his drone software in C++, I would imagine a Java app running on Linux could very well suffer the same fate. According to Wikipedia: > > A system is said to be real-time if the total correctness of an operation depends not only upon its logical correctness, but also upon the time in which it is performed. > > > So to me, this means "*You don't have real-time if total correctness requires logical correctness and timeliness.*" Let's pretend I've written a Java app to be super performant, and that I've "squeezed the lemon" so to speak, and it couldn't reasonably be written (in Java) to be any faster. All in all, my question is: I'm looking for someone to explain to me all/most of the reasons for why a Java app running n Linux would fail to be a "real time app". **Meaning, what are all the categories of things on a Java/Linux stack that prevent it from "being timely", and therefore, from being "*totally correct*"?** As mentioned, it looks like GC and Linux log-flushing can pause execution, but I'm sure there are more things outside the Java app itself that would cause bad timing/performance, and cause it to meet hard deadline constraints. **What are they?**
2016/01/30
[ "https://softwareengineering.stackexchange.com/questions/308829", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/154753/" ]
A software is real time not when it is as fast as possible, but when it is guaranteed that a process completes within some determined time slot. In a soft real time system, it is good but not absolutely necessary that this is guaranteed. E.g. in a game, the calculations necessary for a frame should complete within the period of a frame, or the framerate will drop. This degrades the quality of the gameplay, but does not make it incorrect. E.g. Minecraft is enjoyable even though the game occasionally stutters. In a hard real time system, we don't have such liberties. A flight control software must react within some deadline, or the vehicle could crash. And the hardware, OS, and software must work together to support real time. For example, the OS has a scheduler to decide when which thread is run. For a real-time program, the scheduler has to guarantee big enough, frequent enough time slots. Any other process that wants to execute in such a slot must be interrupted in favour of the real-time process. This requires a scheduler with explicit real-time support. Also, a user-space program will do system calls into the kernel. In a real-time OS, these too must be real-time. E.g. writing to a file handle would have to be guaranteed to take no more that *x* time units, which would solve the log problem. This impacts how such a system call can be implemented, e.g. how buffers can be used. It also means that a call must fail if it can't complete within the required time, and that the user-space program must be prepared to deal with these cases. In the case of Java, the JVM and the standard library are also kernel-like and would need explicit real-time support. For anything that is real-time, your programming style will change. If you don't have endless time, you have to restrict yourself to small problems. All your loops must be bounded by some constant. All memory can be allocated statically, since you have an upper bound on size. Unrestricted recursion is forbidden. This goes against a lot of best practices, but they don't apply for real-time systems. E.g. a logging system might use a statically allocated ring buffer to store log messages when they are written. Once the start is reached, old logs would be discarded, or this condition might be an error.
25,937,168
I use a `entity` form type to provide a list of `Position` entities in a form. I use it often enough (each with the same "setup" code to customize it) that I've decided to make a custom form type from it for better re-use. Here's the current form type: ``` class PositionType extends AbstractType { private $om; public function __construct(ObjectManager $om, $mode) { $this->om = $om; } public function buildForm(FormBuilderInterface $builder, array $options) { } public function setDefaultOptions(OptionsResolverInterface $resolver) { // I need to pass "mode" as an option when building the form. $mode = ??? $query_builder = function (EntityRepository $em) use ($mode) { // Limit the positions returned based on the editing mode return $em ->createQueryBuilder('Position') ->orderBy('Position.name') ->leftJoin('Position.type', 'Type') ->andWhere('Type.id IN (:ids)') ->setParameter('ids', Type::typesForMode($mode)) ; }; $resolver ->setRequired(array('mode')) ->setDefaults(array( 'label' => 'Position', 'class' => 'AcmeBundle:Position', 'property' => 'name', 'query_builder' => $query_builder, 'empty_value' => '', 'empty_data' => null, 'constraints' => array( new NotBlank(), ), )) ; } public function getParent() { return 'entity'; } public function getName() { return 'position'; } } ``` Don't worry about the specifics in the query builder, that doesn't matter. The part that does matter is I'm trying to use a form type option in the query builder. How can I do this? The problem is I can't use `$mode` (the option I want to pass to alter the query builder) in `setDefaultOptions`. I was beginning to look for a way to set the query builder from inside `buildForm` but I'm not sure I can do that.
2014/09/19
[ "https://Stackoverflow.com/questions/25937168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/899199/" ]
This is fairly easy to achieve. You can build an option that depends on another option. [OptionResolver Component - Default Values that Depend on another Option](http://symfony.com/doc/current/components/options_resolver.html#default-values-that-depend-on-another-option) Basically you will do: ``` $resolver ->setRequired(array('mode', 'em')) // "em" for EntityManager as well ->setDefaults(array( 'label' => 'Position', 'class' => 'AcmeBundle:Position', 'property' => 'name', ##################################################### 'query_builder' => function(Options $options){ // Obviously you will need to pass the EntityManager $em = $options['em']; // Limit the positions returned based on the editing mode return $em ->createQueryBuilder('Position') ->orderBy('Position.name') ->leftJoin('Position.type', 'Type') ->andWhere('Type.id IN (:ids)') ->setParameter('ids', Type::typesForMode($options['mode'])) // ; }, #################################### 'empty_value' => '', 'empty_data' => null, 'constraints' => array( new NotBlank(), ), )) ; ``` This is just a rough representation of what `OptionsResolver` can do. Hope it helps :)
29,456,031
I am running a simple client-server program written in python, on my android phone using QPython and QPython3. I need to pass some commandline parameters. How do I do that?
2015/04/05
[ "https://Stackoverflow.com/questions/29456031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3211321/" ]
I found a couple of way of running a script that I imported from my Linux laptop. If I put `frets.py` in the `script3` directory, and create this script in the same directory: ``` import sys, os dir = '/storage/emulated/0/com.hipipal.qpyplus/scripts3/' os.chdir(dir) def callfrets(val): os.system(sys.executable+" frets.py " + val) while True: val = input('$:') if val: callfrets(val) else: break ``` I can run the program with the same commandline inputs that I used in Linux, getting output on the console. Just invoke this script from the editor or the `programs` menu. I also found (after getting some `argparse` errors) that I can get to a usable Linux shell by quiting the Python console with `sys.exit(1)`: ``` import sys sys.exit(1) ``` drops me into the shell with the `/` directory. Changing directory ``` cd /storage/emulated/0/Download # or to the scripts3 directory ``` lets me run that original script directly ``` python frets.py -a ... ``` This shell has the necessary permisions and `$PATH` (`/data/data/com.hipipal.qpy3/files/bin`). (I had problems getting this working on my phone, but updating Qpython3 took care of that.)
627,158
$$\nabla \times A = B$$ $A$ is vector magnetic potential, $\mathrm{Wb/m}$ $B$ is magnetic field intensity, $\mathrm{Wb/m^2}$ **Where does one more m come from for $B$?** *Is that from the gradient operator so it is in meter or something?*
2021/04/05
[ "https://physics.stackexchange.com/questions/627158", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/271720/" ]
It's kind of a funny misconception that the sun is yellow. I mean, astronomically speaking it is indeed a *yellow star*, more precisely [G-type main sequence / yellow dwarf](https://en.wikipedia.org/wiki/G-type_main-sequence_star)... but don't be fooled by the terminology: astronomically speaking, you'll also find that the Earth consists completely of [metal](https://en.wikipedia.org/wiki/Metallicity)! Actually you should consider **the sun as white**. The main reason, strangely enough, why we think the sun is yellow is that **we never look at it**. That is, directly enough to judge its colour. When the sun is high in a cloudless sky, it's just too bright to see its colour (and evolution has trained us to not even try, because it would damage the eyes). Only near sunrise or sunset do we actually get to look at the sun, but then it's not so much the colour of the sun but the colour of the *atmosphere* we're noticing – and the atmosphere is, again counter to perception, yellow-orange-red in colour. Well, not quite – the point is that the atmosphere lets red / yellow light through in a straight line whereas bluer frequencies are more [Rayleigh scattered](https://en.wikipedia.org/wiki/Rayleigh_scattering). That's the reason why *the sky* is blue, and also adds to the perception of the sun being yellow: it's yellow-ish in comparison with the surrounding sky colour. When you see the sun through clouds, you get to see its actual colour more faithfully than usual, both because (as [Mark Bell wrote](https://physics.stackexchange.com/a/627151/3540)) Mie scattering doesn't have the colour-separating effect that Rayleigh scattering does, and because you then see it against a grey / white backdrop instead of against the blue sky.
19,249,756
I have the regular wordpress code to display category description: ``` <?php echo category_description( $category_id ); ?> ``` But how can i display Woocommerce category description? @@ After one of the comment suggestion i added: ``` <?php if ( have_posts() ) { while ( have_posts() ) { the_post(); global $post, $product; $categ = $product->get_categories(); $term = get_term_by ( 'name' , strip_tags($categ), 'product_cat' ); echo $term->description; } // end while } // end if ?> ``` Still, not work.
2013/10/08
[ "https://Stackoverflow.com/questions/19249756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/713576/" ]
``` $args = array( 'taxonomy' => 'product_cat' ); $terms = get_terms('product_cat', $args); $count = count($terms); if ($count > 0) { foreach ($terms as $term) { echo $term->description; } } ``` Edit for Last answer: ``` <?php global $post; $args = array( 'taxonomy' => 'product_cat' ); $terms = wp_get_post_terms($post->ID, 'product_cat', $args); $count = count($terms); if ($count > 0) { foreach ($terms as $term) { echo '<div style="direction:rtl;">'; echo $term->description; echo '</div>'; } } ```
73,573,550
The react docs boldly state that hooks shall only be called inside **"React functions"**: <https://reactjs.org/docs/hooks-rules.html#only-call-hooks-from-react-functions> "Don’t call Hooks from **regular JavaScript** functions." That raises the question what *precisely* distinguishes a React function from a regular js function. Is it the return of a JSX Element? How about those functions: ``` function F1() { return <div>hello</div> } // certainly can use hooks function F2() { return F1() } // can use hooks? is a react function? is a regular js function? function F2() { return <F1 /> } // makes no difference, right? function F3(s) { return <div>{s}</div> } // is a react function because uses jsx? function F4() { return F3("bugs bunny") } function F5({s}) { return <div>{s}</div> } ``` They all return a JSX Element. But I am not sure that f2 or f4 really are React functions and participate in the hook attachment. The way we pass arguments should only not matter. So the question: What exactly makes the difference? (I know how JSX, hyperscript work, no need to explain those basics. I just did not look into the internals of the hook system.)
2022/09/01
[ "https://Stackoverflow.com/questions/73573550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/857848/" ]
Whether the function is a component or not comes down to how you will use the function. Do you plan to render it as a JSX element, eg: `<f1 />`? If so, it's a react component and it can use hooks (though you will need to rename it to uppercase, as in `<F1 />`). During the render process, react will call your function, but only after it has set up the appropriate internal state so that the hooks can work correctly. On the other hand, if you plan to call it directly (eg, `f1()`), you can't set up react's internal state for it, and react won't know you're calling the function so it can't do the setup for you. Thus, the only way you can get away with calling hooks in this kind of function is if you exclusively call this function while another component is rendering. This is called a "custom hook". They're a very useful tool for reusing code, but you should use the naming convention of starting with `use`, so that the programmer and the lint tools know to enforce the rules of hooks.
42,789,183
I have and angular service that I want to test. In one of his methods I am using $http of angular service. I am simply want to mock that function (to be more specific mock $http.post function) that would return whatever I want and inject this mock to my service test. I am tried to find solution and I found $httpBackend but I am not sure that this could help me. MyService looks like that: ``` angular.module('app').service('MyService' , function (dependencies) { let service = this; service.methodToTest = function () { $http.post('url').then(function () { // Do something }); } } ``` * I am want to test methodToTest and inject the mock of $http.post() P.S please remember that $http.post() returns promise so I think that I need to consider in that.
2017/03/14
[ "https://Stackoverflow.com/questions/42789183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6848513/" ]
From the docs > > **pluginManagement**: is an element that is seen along side plugins. > Plugin Management contains plugin elements in much the same way, > except that rather than configuring plugin information for this > particular project build, it is intended to configure project builds > that inherit from this one. However, this only configures plugins that > are actually referenced within the plugins element in the children. > The children have every right to override pluginManagement > definitions. > > > Considering your Inherited POM, the `maven-checkstyle-plugin` used would be the one you've declared first(outside the pluginManagement). Instead of this, for the **inherited `pom.xml`**, to override the configuration, you must specify the same under the `plugins` and not `pluginManagement`. Try simplifying the pom's build tag as -- ``` <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <!--Note - the version would be inherited--> <configuration> <configLocation>${project.parent.basedir}/${checkstyle.configLocation}</configLocation> <suppressionsFile>${project.parent.basedir}/${checkstyle.suppressionsLocation}</suppressionsFile> </configuration> </plugin> </plugins> </build> ``` *Edit* : - From the comment, it was visible that the OP was not using the Simple [Inheritance structure](http://maven.apache.org/guides/introduction/introduction-to-the-pom.html#Example_1) hence using a *relative path* would solve the problem in such cases.
48,275,998
How C++ handles cout of negative value of signed char? Is the behavour defined in C++11 standard? I am using MinGW C++ 11 compiler. It looks the signed value is converted to unsigned type by adding 256 and then prints extended ASCII characters. ``` signed char a=-35; std::cout<<a; ```
2018/01/16
[ "https://Stackoverflow.com/questions/48275998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6446479/" ]
According to [this](http://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt2), the following overload is selected: ``` template< class Traits > basic_ostream<char,Traits>& operator<<( basic_ostream<char,Traits>& os, signed char ch ); ``` And since `signed char` is not `char`, `a` is first converted to a `char` using [`widen`](http://en.cppreference.com/w/cpp/io/basic_ios/widen): ``` char_type widen( char c ) const; ``` So your code is equivalent to: ``` std::cout << std::cout.widen(c); // or: std::cout << std::use_facet< std::ctype<char> >(getloc()).widen(c) ``` As you can see, `widen` takes a `char`, so you'll have a conversion from `signed char` to `char` prior to the actual "widening". Even if you are widening from a `char` to a `char`, the behavior is implementation-defined — The standard makes no guarantee regarding this.
22,599,917
I am using jQuery File Upload plugin (<http://blueimp.github.io/jQuery-File-Upload/>) for image upload for my website. I am trying to disable `UploadHandler.php` from generating thumbnail image on the server. After some searching, I found this: <https://github.com/blueimp/jQuery-File-Upload/issues/2223> My Code: ``` error_reporting(E_ALL | E_STRICT); require('UploadHandler.php'); $options = array ( 'upload_dir' => dirname(__FILE__) . '/uploaddir/', 'image_versions' => array() ); $upload_handler = new UploadHandler($options); ``` When I try to upload file, it is not generating thumbnail in to the thumbnail folder. But it generate another smaller image on the `uploaddir` folder with the resolution 800 x 800. So, how to properly disable thumbnail generation in UploadHandler.php? Thank you.
2014/03/24
[ "https://Stackoverflow.com/questions/22599917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1995781/" ]
The default `index.php` file should look like following. `error_reporting(E_ALL | E_STRICT); require('UploadHandler.php'); $upload_handler = new UploadHandler();` --- In your **`index.php`** file **before** the following function call `$upload_handler = new UploadHandler();` add the following code... ``` $options = array( // This option will disable creating thumbnail images and will not create that extra folder. // However, due to this, the images preview will not be displayed after upload 'image_versions' => array() ); ``` and then **CHANGE** the `UploadHandler()` function call to the pass the option as follows `$upload_handler = new UploadHandler($options);` --- **Short Explanation** In `UploadHandler.php` file there are default options. One of which is `'image_versions'`. This option sets all relevant options to create server side thumbnail image. With the above explained changes we are overwriting the `'image_versions'` option to be an empty array (which is same as not having this option). This disables the server side thumbnail creation.
72,097,711
I searched a lot and there are several questions like this however most of them do not have any answer or are not relevant to me. I'm using TypeORM(v0.2.45) with Postgres driver and my entities/schemas are working fine with `synchronize` mode enabled. My goal is to reverse generate migrations from the existing entities however it fails somehow. This is what I get when trying to generate migrations ```sh ❯ npm run migration:generate Coffee > [email protected] migration:generate > npm run build && npm run typeorm migration:generate -- -n "Coffee" > [email protected] prebuild > rimraf dist > [email protected] build > cross-env NODE_ENV=production nest build > [email protected] typeorm > cross-env NODE_ENV=production ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config dist/src/common/setup/config/orm.config.js "migration:generate" "-n" "Coffee" No changes in database schema were found - cannot generate a migration. To create a new empty migration use "typeorm migration:create" command ``` Here are my npm scripts for TypeORM ```json { "typeorm": "cross-env NODE_ENV=production ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config dist/src/common/setup/config/orm.config.js", "migration:generate": "npm run build && npm run typeorm migration:generate -- -n", "migration:run": "npm run typeorm migration:run" } ``` orm.config.ts ```js import { Env } from '../../env'; import { join } from 'path'; import { SnakeNamingStrategy } from 'typeorm-naming-strategies'; export default { database: Env.isTest ? ':memory:' : process.env.DB_DATABASE || 'dri', type: Env.isTest ? 'sqlite' : 'postgres', port: Number(process.env.DB_PORT || 5432), username: process.env.DB_USERNAME || 'dri-user', password: process.env.DB_PASSWORD || 'dri-secret', host: process.env.DB_HOST || '127.0.0.1', ...(!Env.isProd && { synchronize: true, synchronizeOptions: { force: true, }, }), autoLoadEntities: true, entities: [Env.isTest ? 'src/**/*.entity{.ts,.js}' : join(__dirname, './**/*.entity{.ts,.js}')], keepConnectionAlive: true, namingStrategy: new SnakeNamingStrategy(), logging: Env.isDev ? 'all' : 'error', migrations: [join(__dirname, './**/*.entity{.ts,.js}')], cli: { migrationsDir: 'migrations', }, }; ``` When I try to create a migration - it works but I want to generate it from the existing schema which is failing at the moment. p.s. I tried it with all the tables removed and also having em all in place but the result is the same - did not generate anything.
2022/05/03
[ "https://Stackoverflow.com/questions/72097711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8108312/" ]
Late to the party but maybe it will help someone else. TypeOrm compares your entities schema to the database schema for any changes. If not changes between the two are found, it will not create a new migration. Because you are using `sync: true`, you DB is already up to date with your orm code so no migration is generated. To generate migrations for each table, you will need to delete one table at a time, run the generate command and after run the migration. Repeat for all the tables.
433,009
I can't seem to be able to type in a password so that I may acquire access to #apt-get. I'm looking to update my system via terminal, but typing out my password does no good to get me into su, as the spaces stay blank, and what I know is the password won't go through. Has anyone else had this issue?
2014/03/12
[ "https://askubuntu.com/questions/433009", "https://askubuntu.com", "https://askubuntu.com/users/257348/" ]
This answer has screenshots for Gnome-Shell (Ubuntu Gnome 13.10). I suppose it will be similar for standard Unity, but if not, please chime in. First of all (and this is the most common problem), **to have AltGr working you need a keyboard layout which uses it**. For example, this is my keyboard layout (Settings -> Region and Language): [![Screenshot: Region & Language settings](https://i.stack.imgur.com/zE3UR.png)](https://i.stack.imgur.com/zE3UR.png) * English (US, international with dead keys) has AltGr. * English (US) has NO AltGr. * English (international AltGr dead keys) has AltGr. (My preferred layout is the third one, really). If the layout does not map AltGr+Key to anything, like for example the default "English (US)", AltGr **will not work** even if it's activated in the Keyboard -> Shortcuts panel. This is normally sufficient. To change the position of the AltGr you go to Settings -> Keyboard and set the "Alternative Characters Key": [![Screenshot: Keyboard settings](https://i.stack.imgur.com/QNOB1.png)](https://i.stack.imgur.com/QNOB1.png) For example, my keyboard has no physical AltGr key, so I mapped it to the Right Alt key. Now with the third layout, pressing `AltGr` and `n` **together** gives ñ. [Compose](https://help.ubuntu.com/community/ComposeKey) (the option before) is a very different beast. If you enable it, then you will have a set of characters available with three (or more) keystrokes. For example, pressing `Compose`, `o`, `e` gives œ. That's three sequential keystrokes, not together. Take into account that there is a [bug related to the layout switching](https://bugs.launchpad.net/ubuntu/+source/gnome-settings-daemon/+bug/1218322) in 13.10 which is being worked on, so check it if you have problems changing layout.
33,610,111
I caņ't seem to get around this error message: ExecuteNonQuery: Connection property has not been initialized It refers to a `cmd.ExecuteNonQuery();` I'm not really sure what is going on, maybe the insert is not correct, but here is my code: ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace md2 { public partial class Form2 : Form { SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=MD2;Integrated Security=True;Pooling=False"); SqlCommand cmd = new SqlCommand(); SqlDataReader dr; public Form2() { InitializeComponent(); } private void label2_Click(object sender, EventArgs e) { cmd.Connection = cn; } private void button2_Click(object sender, EventArgs e) { if (izd_adr.Text != "" && izd_nos.Text != "") { cn.Open(); cmd.CommandText = "insert into Publisher (pu_id, pub_name, adress) values ("+null+"'Elina', 'Kalnina')"; cmd.ExecuteNonQuery(); cmd.Clone(); MessageBox.Show("Ir pievienots"); cn.Close(); new Form1().Show(); } } } } ``` I followed a tutorial in how to do this, but I'm getting this error. That Database looks like this: [![enter image description here](https://i.stack.imgur.com/pqLFv.png)](https://i.stack.imgur.com/pqLFv.png) This seems like a easy mistake somewhere, but is really frustrating...
2015/11/09
[ "https://Stackoverflow.com/questions/33610111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3816142/" ]
Using a service can be a good option if you want the downloads to continue even if the user exits. Images that are stored in directories created using `getExternalStorageDirectory()` are automatically deleted when your app is uninstalled. Moreover you can check if the internal memory is large enough to store images. If you use this methods these images will be deleted upon the uninstallion of the app.
36,252,233
I made One Class for executing hibernate select operations my code is working fine but i just need some help I am passing hibernate select query from some other class to get the result if my select query contains more than one column than I call the method getListbylimit(String query,int limit) its returns List but when my select query column contains only one than it gives exception java.lang.String cannot be cast to `[Ljava.lang.Object;` for that I made second method List getListForSingleColumn(String query) to get the result for single column is there any way to write method for this so that I can call only one method. Rather my select query contain one column or more than one columns. can I get return type `List<Object[]>` if I select only one column instead of `List<String>` so that I can use only one method for select operation Here is my code ``` public class ContentDomain { Session session; public List<Object[]> getListbylimit(String query,int limit){ session = HibernateUtil.getSessionFactory().getCurrentSession(); /* session = HibernateUtil.getSessionFactory().openSession(); */ List<Object[]> ls_ob = new ArrayList<Object[]>(); Transaction tx = null; try { tx = session.beginTransaction(); Query q = session.createQuery(query); q.setMaxResults(limit); ls_ob = (List<Object[]>)q.list(); }catch (HibernateException ex) { if (tx != null) { System.out.println("Exception in getList method " + ex); tx.rollback(); ex.printStackTrace(); } System.out.println("Exception getList tx open" + ex); } finally { session.close(); } return ls_ob; } public List<String> getListForSingleColumn(String query){ session = HibernateUtil.getSessionFactory().getCurrentSession(); /* session = HibernateUtil.getSessionFactory().openSession();*/ List<String> ls_ob = new ArrayList<String>(); Transaction tx = null; try { tx = session.beginTransaction(); Query q = session.createQuery(query); ls_ob = q.list(); }catch (HibernateException ex) { if (tx != null) { System.out.println("Exception in getList method " + ex); tx.rollback(); ex.printStackTrace(); } System.out.println("Exception getList tx open" + ex); } finally { session.close(); } return ls_ob; } } ```
2016/03/27
[ "https://Stackoverflow.com/questions/36252233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5194837/" ]
Here is a general implementation using a helper class for finding the lowest X integers. With three columns, three instances of the helper class is created, and the data is then iterated to collect the 3 lowest values for each column. The advantages of this code are: * Only retains the lowest X values * Does not need to box the integers * Uses binary search for improved performance of higher values of X This means it should be fast and have a low memory footprint, supporting unlimited amounts of data (if streamed). See [IDEONE](https://ideone.com/v0CCri) for demo. ``` import java.util.Arrays; class Ideone { private static final int MIN_COUNT = 3; public static void main(String[] args) { int[][] data = { { 74, 85, 123 }, { 73, 84, 122 }, { 72, 83, 121 }, { 70, 81, 119 }, { 69, 80, 118 }, { 76, 87, 125 }, { 77, 88, 126 }, { 78, 89, 127 } }; // Initialize min collectors Min[] min = new Min[data[0].length]; for (int col = 0; col < min.length; col++) min[col] = new Min(MIN_COUNT); // Collect data for (int row = 0; row < data.length; row++) for (int col = 0; col < min.length; col++) min[col].add(data[row][col]); // Print result for (int i = 0; i < MIN_COUNT; i++) { for (int col = 0; col < min.length; col++) System.out.printf("min%d = %-5d ", i + 1, min[col].get(i)); System.out.println(); } } } class Min { private int[] min; public Min(int count) { this.min = new int[count]; Arrays.fill(this.min, Integer.MAX_VALUE); } public void add(int value) { int idx = Arrays.binarySearch(this.min, value); if (idx != -this.min.length - 1) { // not insert at end if (idx < 0) idx = -idx - 1; System.arraycopy(this.min, idx, this.min, idx + 1, this.min.length - idx - 1); this.min[idx] = value; } } public int get(int index) { return this.min[index]; } } ```
44,426,498
When i setup static resources like js,css,templates on my web server, i forget to set cache period for them. by default web server set it "cache forever" (this is tomcat server and spring mvc) ``` <mvc:resources mapping="/resources/**" location="/resources/" /> ``` if dont specify `cache-period` then server will send headers like "cache it forever". now i try different ways to solve this: 1. try to change static resource url ``` mvc:resources mapping="/static/**" location="/resources/" cache-period="10800" ``` but this does not help(i think that browser cache the whole html page, but it does not) 2. i try to force reloading page using JS: location.reload(true) but this does not help much to how can i force browser to reload cached files? P.S. i dont send any cache headers to cache my html pages
2017/06/08
[ "https://Stackoverflow.com/questions/44426498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4760059/" ]
You can append a version number to the URL ``` http://mydomin.com/resources/file.css?version=1 ``` For example; ``` <html> <head> <link href="resources/file.css?version=1" type="text/css" rel="stylesheet"/> <head> <body></body> </html> ```
35,631,454
I have set up new relic in azure (Web Sites > My App > Configuration > Monitoring Tools > Custom) and I have also installed the NuGet package: **NewRelic.Azure.Websites**. Then I changed my web config app settings to this: ``` <add key="NewRelic.AppName" value="My Website" /> ``` and in the new relic config file, I changed this: ``` <application /> ``` to this: ``` <application> <name>My Website</name> </application> ``` I have disabled **Always On** and still I do not get any data. Does anyone know why?
2016/02/25
[ "https://Stackoverflow.com/questions/35631454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1303170/" ]
Did you add the Application Settings according to the [NewRelic documentation](https://docs.newrelic.com/docs/agents/net-agent/azure-installation/azure-web-apps)? [![enter image description here](https://i.stack.imgur.com/IECCD.png)](https://i.stack.imgur.com/IECCD.png) Remember that if you are using **ASPNet 5 /Core 1.0**, NewRelic is [not yet supported](https://discuss.newrelic.com/t/asp-net-5-vnext/12589).
27,450,369
I have the following homework assignment: > > Add a new method `retrieveAt` for the class `IntSLList` that takes an integer index position as a parameter. > > > The method returns the info inside the node at the index position. The index of the first node is 0. If the list is empty or the index is invalid, then display an error message. > > > I have implemented a solution using the following code: ```java public int retrieveAt(int pos){ IntSLLNode tmp; int count = 0; int c; for(tmp = head; tmp != null; tmp = tmp.next){ count++; } if(isEmpty()|| count<pos){ return 0; } else { IntSLLNode tmp1 = head; for(int i = 1; i < pos; i++){ if(tmp1.next == null) return 0; tmp1 = tmp1.next; } return tmp1.info; } } ``` It appears to traverse the list properly, but it does not retrieve the correct element. An example case where this does not appear to give the correct output: ```java IntSLList myn = new IntSLList(); myn.addToHead(10); myn.addToHead(20); myn.addToHead(30); myn.addToHead(40); myn.addToTail(60); myn.printAll(); int x = myn.retrieveAt(4); if(x == 0) System.out.println("NOT VALID "); else System.out.println("elm : " + x); ``` The output is: ``` 40 30 20 10 60 elm : 10 ```
2014/12/12
[ "https://Stackoverflow.com/questions/27450369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4238558/" ]
`Received:` headers are timestamped: ``` Received: from lb-ex1.int.icgroup.com (localhost [127.0.0.1]) by lb-ex1.localdomain (Postfix) with ESMTP id D6BDB1E26393 for <[email protected]>; Fri, 12 Dec 2014 12:09:24 -0500 (EST) ``` So, do `messageInstance.get_all()` and [sort](https://wiki.python.org/moin/HowTo/Sorting) the resulting list however you see fit, an example of how to do this: ``` import email.utils import operator def sort_key(received_header): received_date = email.utils.parsedate_tz(received_header) return received_date received_header_list.sort(key=sort_key) ``` If it doesn't work, do leave a comment and I'll be happy to look into it further.
30,251,819
I am developing a project using primefaces. **Code:** ``` <p:panel id="accountPolicyRichPanel"> <h:panelGrid id="outputPanelGrid"> <h:outputText value=""...../> <p:inputText id="InputTextId"/> <p:selectOneMenu id="suspendTypeId" value="..."> <f:selectItems value="#{AccountPolicy.suspendTypeItemList}"/> <p:ajax listener="#AccountPolicy.suspendTypeComboboxAction}"event="change" update="outputPanelGrid"/> </p:selectOneMenu> </panelGrid> <p:commandButton id="saveButtonId" value="..." action="..." update="accountPolicyRichPanel" /> </p:panel> ``` My issue is when i select the `<p:selectOneMenu>` I upadte the `<h:panelGrid id="outputPanelGrid">` at the time my previous entered value in `<p:inputText id="InputTextId"/>` is removed. How to update the `<h:panelGrid id="outputPanelGrid">` or `<p:panel>` without remove the previous entered value in `p:inputText`.
2015/05/15
[ "https://Stackoverflow.com/questions/30251819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4513434/" ]
You have a problem and you want to use multi-threading to solve it. Now you have two problems. :) First of all you have to look at a way to decompose your problem into something that can be done in parallel. The way you have decomposed your problem right now is inherently sequential. There is no advantage to multi-threading when you decompose it this way because the through put will be limited by the slowest step in the process. A better way to decompose your problem would be to break up the job into tasks that are repeatedly executed. The slowest, but also most easily parallel part is reading and uploading the files. You can do this for each file in parallel. This allows you to leverage Javas [High Level Concurrency Objects](http://docs.oracle.com/javase/tutorial/essential/concurrency/highlevel.html) which will safe you a world of pain. Thread 1: Watch input folder for files. When a new file appears, create a task. This task is submitted to a [Task Executor](http://www.javaworld.com/article/2078809/java-concurrency/java-101-the-next-generation-java-concurrency-without-the-pain-part-1.html). The executor will then execute the task on its own thread using one of the available threads. Task: For a given file a task reads, parses and validate the data in the file. When the data is valid write it to the database and delete/move the original file. Thread 2: Watch the task executor for completed tasks. When a task is complete, read its information and write a report or log an error if something went wrong. Thread 3: Since you have tasks going on in parallel you need something to monitor user requests to stop the service gracefully. You don't want to stop the service halfway through writing a report. Logging: Logging is a separate concern but has nothing (much) to do with threading. You should use a logging framework for this. Most frameworks can handle logging from multiple threads. Finally note that your problem doesn't sound like a problem that would benefit much form parallel processing. Reading files, and uploading them to a database are both IO operations and IO operations are glacially slow compared to other computations. They're also the bottle neck for all parallel processes. You can't read files faster then your disk can provide them and you can't upload faster then your connection can handle. So you have to ask yourself if the marginally improved speed is worth the added complexity.
43,836,829
This sounded simple, but I haven't been able to figure it out. Context: a VC tells a view to animate itself and the VC waits the animation to be completed before. I thought about doing something like this: In ViewController: ``` loadingView.animate() ``` In LoadingView (UIView subclass): ``` animate() -> Bool { UIView.animate(withDuration: 1.0, animations: { self.imageViewCenterYConstraint.constant -= 20 self.layoutIfNeeded() }, completion { return true // This line obviously doesn't work. }) } ``` I do not want to include the rest of the code inside the completion block. The rest of the code is in the VC. I suspect that all this should rather be done with an additional completion handler to add to the animate func. PS: Just in case you know of a better solution/best practices, here is more context: I display a loading animation and remove it once I have retrieved data from the network. I always want to wait for the animation to complete before removing, even if the network data was already downloaded. Don't want to stop the animation at half of it.
2017/05/07
[ "https://Stackoverflow.com/questions/43836829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7698127/" ]
My experience with Selenium is limited to some niche cases where I wanted some automation (for scraping I can normally get by with requests and BeautifulSoup) but I believe the reason you are getting **None** is because `execute_script` doesn't return a value to begin with (your script is basically just being injected into the webpage and executed within the browser). Iirc, you should be able to parse your jquery out to (verbosely): ``` div = driver.find_element_by_class_name("targetclass") targeta = div.find_element_by_link_text("[email protected]") tr = targeta.parent.parent retrieve = tr.find_element_by_tag_name("a") aurlval = retrieve.getattribute("href") ``` I can't recall of the top of my head if Selenium has separate methods for list vs first-element, so you may have to take the zero index on those lines.
32,488,101
I want to do an animation that zooms in from a calendar, specifically with the origin and frame size being that of the button that represent's today's date. Here is the code for determining the todayButton inside CalendarMonthView.m: ``` NSDate *date = (weekdayOffset > 0) ? [_monthStartDate dateByAddingTimeInterval:-1 * weekdayOffset * D_DAY] : _monthStartDate; BOOL bEnabled = (weekdayOffset == 0); CGRect buttonFrame = CGRectMake (0, 0, 81, 61); int idx = -1 * weekdayOffset; for (int y = 0; y < 6; y++) { buttonFrame.origin.x = 0; for (int x = 0; x < 7; x++) { UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; button.tag = idx++; [button setFrame:buttonFrame]; [button setBackgroundImage:[UIImage imageNamed:@"calendarFlyout_dayContainer_today.png"] forState:UIControlStateSelected]; [button setBackgroundImage:[UIImage imageNamed:@"calendarFlyout_selected.png"] forState:UIControlStateHighlighted]; button.titleLabel.font = [UIFont fontWithName:@"TitilliumWeb-Regular" size:18.0]; button.titleLabel.textAlignment = NSTextAlignmentCenter; // TODO: optimize performance int dayOfMonth = (int)[_calendar component:NSCalendarUnitDay fromDate:date]; if (dayOfMonth < prevDayOfMonth) { bEnabled = !bEnabled; } prevDayOfMonth = dayOfMonth; [button setTitle:[NSString stringWithFormat:@"%d", dayOfMonth] forState:UIControlStateNormal]; [button setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal]; [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled]; [button setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted]; [button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected]; [button setBackgroundImage:[UIImage imageNamed:((bEnabled) ? @"calendarFlyout_dayContainer_insideMonth.png" : @"calendarFlyout_dayContainer_outsideMonth.png")] forState:UIControlStateNormal]; // button.enabled = bEnabled; button.selected = [date isToday]; if (button.selected == NO) { button.highlighted = (_currentDayDate) ? [date isEqualToDateIgnoringTime:_currentDayDate] : NO; } else { // Set buttonHolder to today } [button addTarget:self action:@selector (dayButtonTapped:) forControlEvents:UIControlEventTouchUpInside]; [_dayButtonsHolderView addSubview:button]; buttonFrame.origin.x += buttonFrame.size.width; date = [date dateByAddingTimeInterval:D_DAY]; } buttonFrame.origin.y += buttonFrame.size.height; } - (IBAction)dayButtonTapped:(id)sender { if (_delegate) { UIButton *button = (UIButton *)sender; NSDate *selectedDate = [_monthStartDate dateByAddingDays:button.tag]; [_delegate performSelector:@selector (calendarMonthView:dateSelected:) withObject:self withObject:selectedDate]; } } ``` I want to get the frame of `button` and use it in this animation used in CalendarFlyoutView.m. I'm new to iOS programming and I read up on some delegate information and passing information through segues, but it doesn't seem to help me here. Any help would be greatly appreciated.
2015/09/09
[ "https://Stackoverflow.com/questions/32488101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5125365/" ]
Use the `transform` feature. // animate in year calendar \_yearCalendarView.hidden = NO; self.curMonthView.monthLabel.hidden = YES; ``` CalendarMonthView *monthView = [CalendarMonthView new]; monthView.delegate = self; CGRect buttonFrame = _currentDayButtonFrame; _yearCalendarView.frame = CGRectMake(buttonFrame.origin.x, buttonFrame.origin.y + buttonFrame.size.height, buttonFrame.size.width, buttonFrame.size.height); NSLog(@"_yearCalendarView frame: %@", NSStringFromCGRect(_yearCalendarView.frame)); _yearCalendarView.transform = CGAffineTransformMakeScale(0.01, 0.01); [UIView animateWithDuration:kAnimation_ExpandCalendarDuration delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{ _yearCalendarView.transform = CGAffineTransformIdentity; _yearCalendarView.frame = CGRectMake(_monthSwiperScrollView.frame.origin.x, _monthBarImageView.frame.size.height + 20, _monthSwiperScrollView.frame.size.width + 2, _yearFlyoutHeight); } completion:^(BOOL finished) { [UIView setAnimationDelegate:self]; [UIView setAnimationDidStopSelector:@selector (yearCalendarAnimationDidStop:finished:context:)]; }]; ```
1,474,968
What is the coefficient of $x^9$ in the expansion of $(1+x)(1+x^2)(1+x^3)\cdots (1+x^{100})?$ --- I manually expanded $(1+x)(1+x^2)(1+x^3)...(1+x^{10})$ and calculated the coefficient of $x^9$ as $8$ but i dont know how to solve it without expanding.Please help me.
2015/10/11
[ "https://math.stackexchange.com/questions/1474968", "https://math.stackexchange.com", "https://math.stackexchange.com/users/262197/" ]
The coefficient of $x^9$ is the number of [partitions](https://en.wikipedia.org/wiki/Partition_%28number_theory%29) of $9$ into distinct parts, i.e., the number of ways of writing $9$ as the sum of distinct positive integers when the order of the summands doesn’t matter. The sequence of these numbers is [OEIS A000009](https://oeis.org/A000009), and as you can see there, there is no nice formula. However, for small $n$ it’s not hard to write out the partitions by hand: $9$, $8+1$, $7+2$, $6+3$, $5+4$, $6+2+1$, $5+3+1$, and $4+3+2$.
7,623
Helo Guys, I want to know your experience about carbon material and grease Can I use normal grease with carbon ? I want to put grease onto fork and stem.... Or WD-40 or silicone penetrant would be ok ? Thank you.... Can I use this one ? ![http://i129.photobucket.com/albums/p231/picture_77/13012012170.jpg](https://i.stack.imgur.com/QhpnC.jpg)
2012/01/11
[ "https://bicycles.stackexchange.com/questions/7623", "https://bicycles.stackexchange.com", "https://bicycles.stackexchange.com/users/3189/" ]
From [Sheldon Brown](http://sheldonbrown.com/gloss_g.html): > > Grease lubrication is commonly used on all ball bearings. Good mechanics also use grease (or oil) on the threads of most threaded fittings and fasteners, and also inside the steerer (to keep the stem from becoming stuck) and the seat tube (to keep the seatpost from becoming stuck.) > > > There are a great many different greases on the market with different special features, mainly for automotive applications. For bicycle use, almost any grease is adequate, since the loads and temperatures are generally low. > > > Seems to me like the answer is *yes*, although to be safe why don't you invest in some [Finish Line Teflon Grease](http://www.finishlineusa.com/products/fortified-grease.htm) - one tube will last you for years. From the Finish Line [website](http://www.finishlineusa.com/frequentquestions/index.htm): > > **Q. Are Finish Line products safe for use on Carbon Fiber Frames and Parts?** > > > **A. Yes.** All of our products are safe to use on carbon fiber bike parts; our three degreasers, four lubes, our polish, grease, etc are all safe to use on and around carbon fiber bike parts. The exception is our DOT Brake Fluid – you don’t want to get DOT fluid on any painted or finished surface because it’ll attack the paint / finish. > > >
245,522
I have a field name where all the values are capitalized so I used title('string') to get my desired results: ``` 'OLONGAPO CITY' ``` will result to ``` 'Olongapo City'. ``` However, there are strings such as: ``` CITY OF MAKATI ``` I want it to appear as ``` 'City of Makati' ``` instead of ``` 'City Of Makati' ```
2017/06/27
[ "https://gis.stackexchange.com/questions/245522", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/35246/" ]
You could try using something like the following expression: ``` replace(title("fieldName"), 'Of', 'of') ```
60,862,825
I find the method `public ValueStateDescriptor(String name,TypeInformation<T> typeInfo,T defaultValue)`is now deprecated and the documentation says to manage the default value by checking whether the contents of the state is null. I wonder what does this suggestion for?
2020/03/26
[ "https://Stackoverflow.com/questions/60862825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13110035/" ]
We have discovered that our own proxy were writing Access-Control-Allow-Origin header as well. That's why together with keycloak we got it twice. Our devops team has fixed the code of our proxy and it works now.
16,877,762
**This is a spoiler to task #3 of Project Euler! Don't continue to read, if you want to solve it by yourself.** I am trying to learn Haskell by writing programs for Project Euler. At the moment I'm trying to solve task #3 which asks for the largest prime factor of the number 600851475143. To do this, I create a list `liste` which contains all numbers, which are divisors of this number (up to its squareroot). My strategy is now, to count the divisors of these numbers, to decide, if they are prime. ``` number = 600851475143 -- sn = sqrt number sn = 775146 liste = [x | x <- [1..sn], (mod number x == 0)] -- liste = [1,71,839,1471,6857,59569,104441,486847] primelist :: Int -> [Int] primelist z = [y | y <- [1..z], mod z y == 0] main = print [primelist x | x <- liste] ``` The result, which should appear here, should be a list containing 8 lists with the divisors of the elements of `liste`. Instead, the list ``` [[1],[1,3],[1,29],[1,3,29,87]] ``` is printed. How is this behaviour to be explained?
2013/06/01
[ "https://Stackoverflow.com/questions/16877762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2068635/" ]
The Problem is the type declaration `primelist :: Int -> [Int]`. It forces Haskell to use native integers, i.e. 32-Bit integers on a 32-Bit platform. However, if you leave it out, Haskell will infer the function type to be `Integer -> [Integer]`. Integers allow computations with arbitrary precision, but are a little bit slower than native types. To quote from "[What's the difference between Integer and Int"](http://www.haskell.org/haskellwiki/FAQ#What.27s_the_difference_between_Integer_and_Int.3F) in the Haskell FAQ: > > Operations on Int can be much faster than operations on Integer, but > overflow and underflow **can cause weird bugs**. > > > Now isn't that the truth.
148,291
I need to implement an audit trail for Add/Edit/Delete on my objects,I'm using an ORM (XPO) for defining my objects etc. I implemented an audit trail object that is triggered on 1. OnSaving 2. OnDeleting Of the base object, and I store the changes in Audit-AuditTrail (Mast-Det) table, for field changes. etc. using some method services called. How do you implement audit trail in you OOP code? Please share your insights? Any patterns etc? Best practices etc? Another thing is that how to disable audit when running unit test,since I don't need to audit them but since base object has the code. Changes to object (edit/add/del) and what field changes need to be audited
2008/09/29
[ "https://Stackoverflow.com/questions/148291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Database triggers are the preferred way to go here, if you can. However, recently I had to do this in client-side code and I ended up writing a class that created a deep (value) copy of the object when it was opened for editing, compared the two objects at save time (using ToString() only) and wrote any changes to an audit table. Edit: I had an [Audit] attribute on each property I wanted to consider auditable and used reflection to find them, making the method non-specific to the objects being audited.
5,526,625
I am trying to start from scratch a website that has similar functionality to grubhub.com. Fundamentally, a website where restaurant owners can come on to the website, post their menu and most importantly customers will be able to order instant delivery online which sends an email or something to the restaurant. The problem is I have no idea where to start. I have been trying to figure out for a long time. I am familiar with HTML, CSS and somewhat familiar with PHP and MYSQL. So my question is how should I go about starting this project, how do I use the languages and where. Also, should I create a CMS from scratch or just use premade ones. If so, are there any recommendations?
2011/04/02
[ "https://Stackoverflow.com/questions/5526625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/689355/" ]
I would use a premade CMS, unless i had a very solid reason not to (they did not have the functionality that i wanted). This would save you LOTS of time. If you are familiar with PHP, MySQL, CSS and the likes, starting should not be such a problem. You first design how you want your program to work, think of the database tables and how functionality applies to each. Then, you would create the appropriate classes that handle database models and maybe even use a template system that handles the views. Since everything starts with an index page, you may want to start there and include more and more pages as you develop more and more things. Now, just start :)
3,232,098
I am trying to understand a step in the following proof of completeness of $L^p$ in [Stein-Shakarchi's Functional Analysis](http://assets.press.princeton.edu/chapters/s9627.pdf). (See the proof on page 5 of the link or at the end of this post.) At the beginning of the proof, it is said that > > Let $\{f\_n\}\_{n=1}^\infty$ be a Cauchy sequence in $L^p$, and consider a subsequence $\{f\_{n\_k}\}\_{k=1}^\infty$ of $\{f\_n\}\_{n=1}^\infty$ with the following property $\|f\_{n\_{k+1}}-f\_{n\_k}\|\le 2^{-k}$ for all $k\geq 1$. > > > **Question:** Why can the sequence be considered as it is? On a [YouTube video](https://youtu.be/BWnV8fBlDQQ?t=870), it explains about a similar subsequence. I still don't understand why for $n,m>n\_k$ $\Vert f\_{n}-f\_{m}\Vert\_p\implies \Vert f\_{n\_k}-f\_{n\_{k+1}}\Vert\_p$, thus an increasing subsequence. Why is it justified to make $n$ to depend on $k$, $n\_k$? --- [![enter image description here](https://i.stack.imgur.com/D3NG2.png)](https://i.stack.imgur.com/D3NG2.png) [![enter image description here](https://i.stack.imgur.com/t17lP.png)](https://i.stack.imgur.com/t17lP.png) [![enter image description here](https://i.stack.imgur.com/etwMx.png)](https://i.stack.imgur.com/etwMx.png)
2019/05/19
[ "https://math.stackexchange.com/questions/3232098", "https://math.stackexchange.com", "https://math.stackexchange.com/users/459663/" ]
The authors mention at the beginning of the proof that > > The argument is essentially the same as for $L^1$ (or $L^2$); see Section 2, Chapter 2 and Section 1, Chapter 4 in [Book III](https://press.princeton.edu/titles/8008.html). > > > It is said clearly there (see also a snapshot at the end) that > > The existence of such subsequence is guaranteed by the fact that $\|f\_{n}-f\_{m}\|\leq \epsilon$ whenever $n,m\geq N(\epsilon)$, so that it suffices to take $n\_k=N(2^{-k})$. > > > [Added for elaboration.] There exists an integer $N(2^{-1})>0$ such that **for all** $n,m\geq N(2^{-1})$, $$ \|f\_{n}-f\_{m}\|\leq 2^{-1}\tag{1}. $$ There exists an integer $N(2^{-2})>N(2^{-1})$ such that **for all** $n,m\geq N(2^{-2})$, $$ \|f\_{n}-f\_{m}\|\leq 2^{-2}\tag{2}. $$ There exists an integer $N(2^{-3})>N(2^{-2})$ such that **for all** $n,m\geq N(2^{-3})$, $$ \|f\_{n}-f\_{m}\|\leq 2^{-3}\tag{2}. $$ ... so on and so forth. Now, let $n\_1=N(2^{-1})$, $n\_2=N(2^{-2})$, $n\_3=N(2^{-3})$, $\cdots$. Since $n\_1,n\_2\geq N(2^{-1})$, we have by (1) $$ \|f\_{n\_2}-f\_{n\_1}\|\leq 2^{-1}. $$ Since $n\_2,n\_3\geq N(2^{-2})$, we have by (2) $$ \|f\_{n\_3}-f\_{n\_2}\|\leq 2^{-2}. $$ Since $n\_3,n\_4\geq N(2^{-3})$, we have by (3) $$ \|f\_{n\_4}-f\_{n\_3}\|\leq 2^{-3}. $$ ... so on and so forth. --- The following is a snapshot of the beginning of the proof for completeness of $L^1$ in Stein-Shakarchi's Book III (page 70 Theorem 2.2). > > [![enter image description here](https://i.stack.imgur.com/cgCtg.png)](https://i.stack.imgur.com/cgCtg.png) > > >
10,564,722
I'm new to PHP, I started about 3 weeks ago. I have a string, which is used with $\_POST to pass it to another page, the second page uses $\_GET to get these url and split it as desired. My problem is that, in my first page I use a String, and I want to encrypt it, so that I can pass it as a plan text. In the second page I must decrypt it and get it as an array. So is there any encryption method or function I can use which is compatible with $\_POST ( so I can send it to another page ) and decrypt it as an array ? I need this method, because the second page is actually connecting to website and is a payment method. So i don't want users to manually edit the url and lower the amount of $ for the product they get. tnx for your help.
2012/05/12
[ "https://Stackoverflow.com/questions/10564722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1391170/" ]
You're thinking about this wrong. You NEVER trust information coming from the user's side. For example, if your user sends a form that says what item they want, DO NOT include the price in the form. Instead, get the price from the server (database), where it can be trusted.
12,456,578
Hi I have a table with name **test**. it got 7 columns **id , a , b , c , d , e , f.** All this columns contains either 1 or 0. Now i want make a query where i can choose only those columns whose value is 1. Something like this: ``` select (condition) from test where id = 5; ``` because i have a hotel table with 50 columns out of which 11 columns contains either 1 or 0 representing the facilities of the hotel. I want to make a query which just tells what are the facilities of the hotel. Any help would be great.
2012/09/17
[ "https://Stackoverflow.com/questions/12456578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1529342/" ]
Something like this perhaps? You may want to customize the behavior of the dropdown, but this shows the basic logic of handling the click events and preventing default behaviour (i.e. following links) if the menu isn't open: ``` $(function() { $('#main-menu a').click(function(e) { var listItem = $(this).closest('li'); if (!listItem.is('.open')) { // Opening drop-down logic here. e.g. adding 'open' class to <li> e.preventDefault(); listItem.addClass('open'); } // Otherwise the default behaviour of the event (clicking the link) will be unaffected }); }); ```
34,019,675
As in earlier version of symfony we user to generate a CRUD with the following command ``` $ php app/console generate:doctrine:crud ``` But in symfony 3.0.0 i could not find the app/console, even I tried checking the documentation for the same but was not able to find anything. Link to document <http://symfony.com/doc/current/bundles/SensioGeneratorBundle/commands/generate_doctrine_crud.html>
2015/12/01
[ "https://Stackoverflow.com/questions/34019675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1278758/" ]
Use bin/console instead of app/console. However, Symfony 3.0 was just released yesterday. <http://symfony.com/blog/symfony-3-0-0-released>. Most of the core concepts between S2 and S3 are the same but the implementations have changed significantly. For example, the form components work differently. Most of the current documentation is S2 specific and will not work under S3. Furthermore, many 3rd party bundles such as FOSUserBundle will not currently work under S3. So, if want to use bleeding edge software then roll up your sleeves and start reading the upgrade files as well as the blog. If you just want to make applications then start over with S2.8. Something else that will be really fun. The 'current' documents now point to S3. So most of the S2 links will now point to incorrect information.
28,430,749
I have a C++ classe in a .h file like this: ``` #ifndef __GLWidget_h__ #define __GLWidget_h__ class PivotShape { // This is allowed void do_something() { std::cout << "Doing something\n"; } // This is not allowed void do_something_else(); } // This is not allowed void PivotShape::do_something_else() { std::cout << "Doing something else\n"; } #endif ``` If I add methods inside the class declaration everything seems fine. But if I add methods outside of the class declaration, I get errors like this: ``` /usr/share/qt4/bin/moc GLWidget.h > GLWidget_moc.cpp /programs/gcc-4.6.3/installation/bin/g++ -W -Wall -g -c -I./ -I/usr/include/qt4 GLWidget_moc.cpp /programs/gcc-4.6.3/installation/bin/g++ main.o GLState.o GLWidget.o MainWindow_moc.o GLWidget_moc.o -L/usr/lib/x86_64-linux-gnu -lQtGui -lQtOpenGL -lQtCore -lGLU -lGL -lm -ldl -o main GLWidget.o: In function `std::iterator_traits<float const*>::iterator_category std::__iterator_category<float const*>(float const* const&)': /home/<user>/<dir>/<dir>/<dir>/<dir>/<dir>/GLWidget.h:141: multiple definition of `PivotShape::do_someting_else()' main.o:/home/<user>/<dir>/<dir>/<dir>/<dir>/<dir>/GLWidget.h:141: first defined here ``` I think the duplication is being caused by this snippet in the Make file. I think the .h files are being converted to \_moc.cpp files and this is allowing the multiple inclusions: ``` # Define linker LINKER = /programs/gcc-4.6.3/installation/bin/g++ MOCSRCS = $(QTHEADERS:.h=_moc.cpp) # Define all object files to be the same as CPPSRCS but with all the .cpp # suffixes replaced with .o OBJ = $(CPPSRCS:.cpp=.o) $(MOCSRCS:.cpp=.o) ``` Is this the problem? If so, how can I fix it? If not, what's going on? I thought it was illegal in C++ to include class methods inside the body of the class declaration. If this is legal, then it seems like an easy way to solve the problem. Is this legal? Edit: I forgot to mention that I had already discovered that declaring the methods as `inline` works, but I was wondering how to avoid the duplication.
2015/02/10
[ "https://Stackoverflow.com/questions/28430749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1993403/" ]
You're breaking the One Definition Rule; defining the function in the header means there's a definition in every translation unit that includes the header, and you're usually only allowed a single definition in the program. Options: * Move the function definition into a source file, so there's just one definition; or * Add `inline` to the function definition, to relax the rule and allow multiple definitions; or * Define the function inside the class, which makes it implicitly inline. (To answer your final question, yes that is legal.) Also, don't use [reserved names](https://stackoverflow.com/questions/228783) like `__GLWidget_h__`.
5,939,578
I would like to use shared memory between several processes, and would like to be able to keep using raw pointers (and stl containers). For this purpose, I am using shared memory mapped at a *fixed address*: ``` segment = new boost::interprocess::managed_shared_memory( boost::interprocess::open_or_create, "MySegmentName", 1048576, // alloc size (void *)0x400000000LL // fixed address ); ``` What is a good strategy for choosing this fixed address? For example, should I just use a pretty high number to reduce the chance that I run out of heap space?
2011/05/09
[ "https://Stackoverflow.com/questions/5939578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/680410/" ]
This is a hard problem. If you are forking a single program to create children, and only the parent and the children will use the memory segment, just be sure to map it before you fork. The children will automatically inherit the mapping from their parent and there's no need to use a fixed address. If you aren't, then the first thing to consider is whether you really need to use raw STL containers instead of the boost interprocess containers. That you're already using boost interprocess to allocate the shared memory segment suggests you don't have any problem using boost, so the only advantage I can think of to using STL containers would be so you don't have to port existing code. Keep in mind that for it to work with fixed addresses, the containers *and what they contain pointers to* (assuming you're working with containers of pointers) will need to be kept in the shared memory space. If you're certain that it's what you want, you'll have to figure out some method for them to negotiate an address. Keep in mind that the **OS is allowed to reject your desired fixed memory address**. It will reject an address if the page at that address has already been mapped into memory or allocated. Because different programs will have allocated different amounts of memory at different times, which pages are available and which are unavailable will vary across your programs. So you need for the programs to gain consensus on a memory address. This means that several addresses might have to be tried and rejected. If it's possible that sometime after startup a new program will become interested, **the search for consensus will have to start over again**. The algorithm would look something like this: 1. Program A proposes memory address X to all other programs. 2. The other programs respond with true or false to indicate whether the memory mapping at address X succeeded. 3. If program A receives any false responses, goto #1. 4. Program A sends a message to the other programs letting them know the address has been validated and maybe used. 5. If a new app becomes interested in the data, it must notify program A it would like an address. 6. Program A then has to tell all the other programs to stop using the data and goto #1. To come up with what addresses A should propose, you could have A map a non-fixed memory segment, see what address it's mapped at, and propose that address. If it's unsatisfactory, map another segment and propose it instead. You will need to unmap the segments at some point, but you can't unmap them right away because if you unmap then remap a segment of the same size chances are the OS will give you the same address back over and over. **Keep in mind that you may never reach consensus**; there's no guarantee that there's a large enough segment at a common location across all the processes. This could happen if your programs all independently use almost all memory, say if they are backed up by a ton of swap (though if you care enough about performance to use shared memory hopefully you are avoiding swap). All of the above assumes you're in a relatively constrained address space. **If you're on 64-bit, this could work**. Most computers' RAM + swap will be far less than what's allowed by 64-bits, so you could put map the memory at a very far out fixed address that all processes are unlikely to have mapped already. I suggest at least 2^48, since current 64-bit x86 processors don't each beyond that range (despite pointers being 64-bits, you can only plug in as much RAM as allowed by 48-bits, still a ton at the time of this writing). Although there's no reason a smart heap allocator couldn't take advantage of the vastness of the address space to reduce its bookkeeping work, so to be truly robust you would still need to build consensus. Keep in mind that you will at least want the address to be configurable -- even if we don't have that much memory anytime soon, between now and then someone else might have the same idea and pick your address. To do the bidirectional communication you could use any of sockets, pipes, or another shared memory segment. Your OS may provide other forms of IPC. But strongly consider that you are probably now introducing more complexity than you would have to deal with if you just used the boost interprocess containers ;)
49,007,767
I'm trying to exchange messages using multiple covert channels. So, basically, first i need to select the channel that i want to use for communication and then select the "destination\_ip" of the user that i want to chat with and after that the > > processMessage() > > > is called. Now, to move from one channel to another I have to close the existing connection and then open a new connection with the new channel that i want to use. My code below is modified to keep using the same channel after closing the connection and contain only the things that you need. ``` #include <channelmanager.hpp> #include <thread> #include <iostream> #include <boost/test/unit_test.hpp> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <stdio.h> #include <string.h> #include <fstream> #include <openssl/hmac.h> struct CommunicationFixture { CommunicationFixture() { channelmanager.setErrorStream(&cout); channelmanager.setOutputStream(&cout); destination_ip = ""; channel_id = channelmanager.getChannelIDs()[0]; } library::ChannelManager channelmanager; vector<string> last_adapters; string destination_ip; string channel_id = ""; int processMessage(string message) { if (message.compare("exit") == 0) { channelmanager.closeConnection(destination_ip); return 1; } vector<string> arguments; boost::split(arguments, message, boost::is_any_of(" "), boost::token_compress_on); if (arguments[0].compare("argument") == 0) { if (arguments.size() < 2) { cout << "Not enough arguments" << endl; return 0; } string argument_list = arguments[1]; for (unsigned int i = 2; i < arguments.size(); i++) { argument_list += " " + arguments[i]; } channelmanager.setChannelArguments(destination_ip, argument_list); cout << "Set channel argument to '" << argument_list << "'." << endl; return 0; } if (message.compare("help") == 0) { cout << "Help not available in chat mode. Close chat first with 'exit'" << endl; return 0; } channelmanager.openConnection(destination_ip, channel_id); channelmanager.sendMessage(destination_ip, message); return 0; } int close(string destination){ cout << "closing.." << endl; channelmanager.closeConnection(destination); //I believe i have the error because of this! return 0; } }; BOOST_FIXTURE_TEST_SUITE(communication, CommunicationFixture) BOOST_AUTO_TEST_CASE(basic_communication) { selectAdapterId(0); cout << "Test" << endl << endl; printCommands(); cout << "Enter your command:" << endl; string command; int code = 0; while (code != 2) { std::getline(cin, command); code = processCommand(command); if (code == 1) { // chat cout << "chat started.." << endl; int chatCode = 0; while (chatCode != 1) { std::getline(cin, message); close(destination_ip); chatCode = processMessage(message); channelmanager.setErrorStream(&cout); } cout << "chat ended." << endl; } } } BOOST_AUTO_TEST_SUITE_END() ``` Note that, i think that the error happens due to the > > function close() > > > because without it i don't get any errors. and the error doesn't happen immediately but after exchanging some messages. Here's the error: > > unknown location(0): fatal error: in > "communication/basic\_communication": memory access violation at > address: 0x00000024: no mapping at fault address > communicationTest.cpp(325): last checkpoint: "basic\_communication" > test entry > > >
2018/02/27
[ "https://Stackoverflow.com/questions/49007767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5467365/" ]
Memory access violation happen when you are trying to access to an unitialized variable, in this case the `channelmanager`. I can only see that you initialize `channelmanager` in the `processMessage()` method and you are closing the connection before initializing the `channelmanager` as it happen in: ``` close(destination_ip); chatCode = processMessage(message); ``` Either you change the initialization or do not close it before the `processMessage()` method.
38,262,422
I was learning about constructors, and I came across the `new` keyword. `var obj = new myContructor();` I learnt that it created a new object, set its prototype as `constructor.prototype`, set its properties as according with the `this` keyword, and finally returns that object. Now, I am confused as to where exactly does it create the new object, as inside memory or somewhere where it is volatile. And what do we mean when saying it RETURNS that object, that it creates a copy of the new object at the location of the var obj, or does it reference obj to wherever it created the new object ?
2016/07/08
[ "https://Stackoverflow.com/questions/38262422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6324230/" ]
> > inside memory or somewhere where it is volatile > > > Yes, of course. Just like any other piece of data in the program. > > do we mean when saying it RETURNS that object > > > You are making a function call. Function calls have return values. The object is the return value of that function call. > > it creates a copy of the new object at the location of the var obj > > > It creates it in the function, then it returns a reference to it (just like any other object), and that reference is stored in the variable because you used an assignment.
7,209,731
I am writing a program that does some batch processing. The batch elements can be processed independently of each other and we want to minimize overall processing time. So, instead of looping through each element in the batch one at a time, I am using an ExecutorService and submitting Callable objects to it: ``` public void process(Batch batch) { ExecutorService execService = Executors.newCachedThreadPool(); CopyOnWriteArrayList<Future<BatchElementStatus>> futures = new CopyOnWriteArrayList<Future<BatchElementStatus>>(); for (BatchElement element : batch.getElement()) { Future<MtaMigrationStatus> future = execService.submit(new ElementProcessor(batch.getID(), element)); futures.add(future); } boolean done = false; while (!done) { for (Future<BatchElementStatus> future : futures) { try { if (future.isDone()) { futures.remove(future); } } catch (Exception e) { System.out.println(e.getMessage()); } if (futures.size() == 0) { done = true; } } } } ``` We want to be able to allow the batch processing to be cancelled. Because I'm not using a loop, I can't just check at the top each loop if a cancel flag has been set. We are using a JMS topic to which both the BatchProcessor and ElementProcessor will be listening to inform them the batch has been cancelled. There are a number of steps in the ElementProcess call() after which some of them the processing can be safely stopped but there's a point of no return. The class has this basic design: ``` public class ElementProcessor implements Callable, MessageListener { private cancelled = false; public void onMessage(Message msg) { // get message object cancelled = true; } public BatchElementStatus call() { String status = SUCCESS; if (!cancelled) { doSomehingOne(); } else { doRollback(); status = CANCELLED; } if (!cancelled) { doSomehingTwo(); } else { doRollback(); status = CANCELLED; } if (!cancelled) { doSomehingThree(); } else { doRollback(); status = CANCELLED; } if (!cancelled) { doSomehingFour(); } else { doRollback(); status = CANCELLED; } // After this point, we cannot cancel or pause the processing doSomehingFive(); doSomehingSix(); return new BatchElementStatus("SUCCESS"); } } ``` I'm wondering if there's a better way to check if the batch/element has been cancelled other than wrapping method calls/blocks of code in the call method in the `if(!cancelled)` statements. Any suggestions?
2011/08/26
[ "https://Stackoverflow.com/questions/7209731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/332893/" ]
I don't think you can do much better than what you are currently doing, but here is an alternative: ``` public BatchElementStatus call() { return callMethod(1); } private callMethod(int methodCounter) { if (cancelled) { doRollback(); return new BatchElementStatus("FAIL"); } switch (methodCounter) { case 1 : doSomethingOne(); break; case 2 : doSomethingTwo(); break; ... case 5 : doSomethingFive(); doSomethingSix(); return new BatchElementStatus("SUCCESS"); } return callMethod(methodCounter + 1); } ``` Also, you want to make `cancelled` volatile, since `onMessage` will be called from another thread. But you probably don't want to use `onMessage` and `cancelled` anyway (see below). Other minor points: 1) `CopyOnWriteArrayList<Future<BatchElementStatus>> futures` should just be an `ArrayList`. Using a concurrent collection mislead us into thinking that `futures` is on many thread. 2) `while (!done)` should be replaced by `while (!futures.isEmpty())` and `done` removed. 3) You probably should just call `future.cancel(true)` instead of "messaging" cancellation. You would then have to check `if (Thread.interrupted())` instead of `if (cancelled)`. If you want to kill all futures then just call `execService.shutdownNow()`; your tasks have to handle interrupts for this to work. **EDIT**: instead of your `while(!done) { for (... futures) { ... }}`, you should use an [ExecutorCompletionService](http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorCompletionService.html). It does what you are trying to do and it probably does it a lot better. There is a complete example in the API.
31,111,914
When we use GET method we use ambersand(`&`) sign to send the data to a particular script. I'm sending data to a php script called `myscript.php` by the GET method from a javascript like the following : ``` http.open('GET', 'Myscript.php'+ '?d=' + value1 + '&c=' + value2 + '&f=' + value3); ``` But if the value1 or value2 or value3 contains an `&` sign in their actual value (for example if somebody enter for the value1 `garth&ggg&kkk` then the `Myscript.php` can't handle the value1 properly because it contains an `&` sign in the actual data. It takes the value `garth` for value1. My php code is as follows: ``` if (isset($_GET['d'])) { $a = $_GET['d'];} ```
2015/06/29
[ "https://Stackoverflow.com/questions/31111914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2884663/" ]
You need to encode it properly before putting it into url to turn ampersand to `%26`: * in PHP: `urlencode()` * in javascript: `encodeURIComponent()` You don't need to decode it in PHP, it will decode it for you to `&` character.
69,544,118
I'm working on a solution where I have a SQS queue with Lambda trigger. My understanding is Lambda will receive messages in batches to be processed, and once Lambda function is successful, the messages in the SQS queue is automatically deleted. However, how do I only allow some of those messages to be deleted? Let's assume this use case: Lambda function receives a batch with 10 messages, and only 7 messages are valid and can be processed, and the other 3 messages needs to be reprocessed at later point. My initial thought was I could update the visibility timeout via `boto3.sqs.change_visibility_timeout` for each of the 3 messages to have it reprocessed after the timeout, however, since overall lambda function execution is successful, all 10 messages are deleted from SQS queue. Any suggestions?
2021/10/12
[ "https://Stackoverflow.com/questions/69544118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5186759/" ]
Yes, by default, the Lambda function deletes all the messages upon success. You would need to handle this in your code, but not by changing the visibility timeout of the messages. Add DLQ (dead-letter queue) that will actually handle the failed messages (messages go to DLQ after a certain number of failed attempts to be processed, depending on how you set it up) You have few options here: 1. You can handle each item yourself, and delete messages that are processed successfully. In case of a message that's not successful, you can throw an error and it won't be deleted automatically by the lambda function 2. If you use JavaScript you can try with [Middy](https://www.npmjs.com/package/@middy/core) 3. If you use Python, you can use [Lambda Powertools Python](https://awslabs.github.io/aws-lambda-powertools-python/1.12.0/utilities/batch/)
1,542
I have a problem similar in formulation to this post, with a few notable differences: [What simple methods are there for adaptively sampling a 2D function?](https://scicomp.stackexchange.com/questions/923/what-simple-methods-are-there-for-adaptively-sampling-a-2d-function) Like in that post: * I have a $f(x,y)$ and evaluation of this function is somewhat expensive to compute Unlike in that post: * **I am interested not in the value of the function accurately everywhere, but only in finding a single isocontour of the function.** * I can make significant assertions about the autocorrelation of the function, and consequently the scale of smoothness. Is there an intelligent way to step along/sample this function and find this contour? More Information ---------------- The function is the computation of [Haralick Features](http://murphylab.web.cmu.edu/publications/boland/boland_node26.html) over $N$ pixles surrounding the point, and soft classification by some sort of classifier/regressor. The output of this is a floating point number which indicates which texture/material the point belongs to. The scaling of this number can be estimated class probablities (SoftSVM or statistical methods etc) or something really simple like the output of a linear/logistic regression. Classification/regression is accurate and cheap compared to time taken for feature extraction from the image. Statistics surrounding $N$ means that the window is typically sampling overlapping regions, and as such there is *significant* correlation between nearby samples. (Something I can even approach numerically/symbolically) Consequently, this can be thought of as a more complex function of $f(x, y, N)$ where larger $N$ will give an estimate more related to the neighborhood (highly correlated), and a smaller $N$ will give a more variable, but more local estimate. Things I Have Tried: -------------------- * Brute Computation - Works well. 95% correct segmentation with constant $N$. The results look fantastic when contoured using any standard method after that. This takes *forever*. I can simplify the features calculated on a per-sample basis, but ideally I want to avoid this to keep this code general to images with textures who's differences show up in different parts of the feature space. * Dumb Stepping - Take a single pixel "step" in each direction and pick the direction to move based on closeness to iso-line value. Still pretty slow, and it will ignore bifurcation of an isoline. Also, in areas with a flat gradient it will "wander" or double back on itself. I am thinking I want to do something like the subdivison proposed in the first link, but pruned for boxes which bound the isoline of interest. I feel like I should be able to leverage $N$ also, but I am not sure how to approach that.
2012/03/06
[ "https://scicomp.stackexchange.com/questions/1542", "https://scicomp.stackexchange.com", "https://scicomp.stackexchange.com/users/53/" ]
There is a paper in computer graphics called [Provably Good Sampling and Meshing of Surfaces](http://geometrica.saclay.inria.fr/team/Steve.Oudot/papers/bo-pgsms-05/bo-pgsms-05.pdf), which relies on you providing an oracle that determines all the intersections of an isoline with a given line segment. With that, it samples all the contours assuming you can provide a local feature scale (something like the maximum local curvature), and an initial set of line segments that intersects all the contours. It is not the simplest thing to implement, since it relies on computing Delaunay triangulations, but it is implemented in 3D in [CGAL](http://www.cgal.org). It is substantially simpler in 2D, since good triangulation software like [Triangle](http://www.cs.cmu.edu/~quake/triangle.html) exists. In some sense, this is pretty close to the best you can possibly do.
66,659,701
I am trying to create a function compare(lst1,lst2) which compares the each element in a list and returns every common element in a new list and shows percentage of how common it is. All the elements in the list are going to be strings. For example the function should return: ``` lst1 = AAAAABBBBBCCCCCDDDD lst2 = ABCABCABCABCABCABCA common strand = AxxAxxxBxxxCxxCxxxx similarity = 25% ``` The parts of the list which are not similar will simply be returned as x. I am having trouble in completing this function without the python **set** and **zip** method. I am not allowed to use them for this task and I have to achieve this using while and for loops. Kindly guide me as to how I can achieve this.
2021/03/16
[ "https://Stackoverflow.com/questions/66659701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15292030/" ]
Your undefined label is because of the `...filtersApplied` ``` if (me.prop('checked') === true) { filtersApplied.push([ //this ...filtersApplied { id: me.attr('id'), data: me.attr('data-filter-label') } ]); ``` Note that filtersApplied is an array and you're making a `push()`, this method inserts a value in the end of the array, so your `...filtersApplied` makes no sense. Just remove it and you'll be fine. You can se more here <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push>
17,416,488
What I want to implement is something like: ``` switch(flag) { case 1: var query=from w in db.someTable select w; break; case 2: query=from w in db.someTable where w.id==someID select w; break; case default: break; } ``` But it cannot compile correctly. If I add a `var` before the second `query`, it prompts that query has been declared. Do I have to change the variable name? Such like: `query1 in case1, query2 in case2`, etc. --- EDITED 1 Thanks for your help. In fact my code is a little bit more complicated than what I posted above. Here is the complete code: ``` List<object> results=new List<object>(); switch (flag) { case 1: var query = from w in db.RADIATION where w.DATEDT.CompareTo(dateStr) == 0 && w.LATITUDE.CompareTo(latitude) == 0 && w.LONGITUDE.CompareTo(longitude) == 0 orderby w.TIMETM select new { w.RADIATION, w.TIMETM }; break; case 2: var query = from w in db.TEMPRETURE where w.DATEDT.CompareTo(dateStr) == 0 && w.LATITUDE.CompareTo(latitude) == 0 && w.LONGITUDE.CompareTo(longitude) == 0 orderby w.TIMETM select new { w.TEMPRETURE, w.TIMETM }; foreach (var item in query) { var resultItem = new { TEMPRETURE = item.TEMPRETURE, TIME = item.TIMETM }; results.Add(resultItem); } break; case default: break; } ``` The two queries are for two different tables. So I don't know how to determine the Type T in IQueryable. Also, what I `select` is an anonymous object using `new { PropertyName = propertyValue }`. Is there anyway if I insist using the same name `query`?
2013/07/02
[ "https://Stackoverflow.com/questions/17416488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1526662/" ]
Declaring with `var` lets you shorten the code, but the variable that you declare remains statically typed, and the scope of that variable does not change. If you need to use a variable outside `switch`, declare it before the `switch` statement, like this: ``` IQueryable<SomeType> query = null; switch (...) { case 1: query = ...; break; ... default: ... } ``` Now you can use `query` outside the `switch`. Note: There are cases where you must use `var` because the type that you assign to it has no name, but in your first case the type has a name, so you do not need to use `var`. **EDIT :** Your second case, however, does require a `var`, because you are selecting an anonymous type. In situations like that there are several ways around this problem: * You can declare a named type for the "superset" of columns that you select (i.e. `TIMETM`, `TEMPERATURE`, and `RADIATION`), or * In .NET 4.0 you can use `IQueryable<dynamic>`. This shifts some of compile-time checking into runtime, but if you have to go this route, it is very convenient.
22,544
With the equipment development timelines we know about, what is the soonest date a manned lunar landing could take place?
2017/08/05
[ "https://space.stackexchange.com/questions/22544", "https://space.stackexchange.com", "https://space.stackexchange.com/users/19834/" ]
Elon Musk has stated that it is highly unlikely that the Falcon Heavy will actually make it to orbit on the maiden flight. This is due to the fact that it will be the first time that they can test out how the fuel pumps between the boosters work and also the separation and stage strengthening. Due to this, it is highly likely that the first Falcon Heavy launch will be with a fairing containing some form of test payload. A Dragon capsule would likely not be used due to pricing given that they would basically be throwing it away. One situation I can think of however where they would use a Dragon would be if it is an early Dragon 2 as it would allow them to practice launch escape with the capsule if something was to go wrong. In terms of what they will actually launch, it will likely be something like a test payload. Musk did say it would be something silly so you never know, his mind works in mysterious ways.
12,332
Почему в первом случае "к" будет приставкой,а во втором - "-юч" будет суффиксом? **Ключ воды и ключ дверной**
2012/11/15
[ "https://rus.stackexchange.com/questions/12332", "https://rus.stackexchange.com", "https://rus.stackexchange.com/users/1038/" ]
Это по каким же эврикам? Ключ - корень в обоих случаях. Фасмер даже допускает общность происхождения. I род. п. -а́ I., сюда же заключи́ть, укр. ключ, ст.-слав. ключь, болг. клю́чът, сербохорв. кљу̑ч, род. п. кљу́ча " крюк, ключ", словен. kljúč, чеш. klíč, слвц. kl᾽úč, польск. klucz, в.-луж. kluč, н.-луж. kluc. Родственно балт. словам, приведенным на клюка́, а также греч. κληΐς, дор. κλΒ̄ίς, κλάξ "ключ", κλείω "запираю", лат. clāvus " гвоздь", clāvis "ключ", claudō "запираю", ирл. cló, мн. clói " гвоздь"; см. Бернекер 1, 528 и сл.; Траутман ВSW 137 и сл.; Вальде–Гофм. 1, 229 и сл. Сюда же с и.-е. skl- относятся д.-в.-н. slioʒan "запирать", sluʒʒil "ключ", др.-сакс. slutil – то же. II род. п. -а́ II. "источник, родник", болг. ключ (водата ври с ключ) "о шуме воды", сербохорв. кљу̑ч, род. п. кљу́ча "клокотание, бурление воды", кљу̀чати " кипеть, бурлить, клохтать". Обычно сближается с клю́кать " шуметь" (см.); см. Бернекер 1, 529; Брюкнер 236, но имеет смысл поставить вопрос об одинаковом происхождении с ключ I. Ср. нем. выражение eine Quelle erschließen " открыть источник".
20,279
Suppose that a Tor client wants to access a certain hidden service. According to the protocol, instead of submitting a request directly to the server IP (which is hidden[1][2]), this client submit a request via a series of relays. However, at some point, there will be a final relay in charge of delivering the client's message specifically to the server running the hidden service. In order to do so, this final relay must know the IP of this hidden server, otherwise the current internet infrastructure cannot deliver the message. If the aforementioned steps are indeed correct, this means that in order to host a website using TOR Hidden Service you must reveal the IP address to a final relay. Therefore, Tor network does not hide the IP address of hidden services. How to reconcile that? Am I missing something? --- [1]: "TOR Hidden Service allows you to host a website, without revealing where the website is, and hence protects the identity of the publisher/webmaster.", [WikiBooks](https://en.wikibooks.org/wiki/How_to_Protect_your_Internet_Anonymity_and_Privacy/TOR_Hidden_Service_for_Anonymous_Websites) [2]: "The Tor network hides the IP address of hidden services, instead using onion addresses and public keys to keep the real location hidden.", [Privay.net](https://privacy.net/make-site-visible-dark-web-tor-hidden-services/)
2019/09/12
[ "https://tor.stackexchange.com/questions/20279", "https://tor.stackexchange.com", "https://tor.stackexchange.com/users/27707/" ]
Tor uses TCP tunnels, so - regardless of the previous answer - no need to use it. The hidden service is reached from the Tor node that is hosting it, usually through a localhost. The scenario you've described about IP revealing - yes, it *can* be a privacy problem. The design doc states clear - the system is anonymizing mostly the client, not the server - it's only rudimentary in a *standard* setup. To conceal your server IP use bridges-only for your hosting server(s) - that will elevate the privacy, but if you want both client and server to be equally anonymized - use I2P, not Tor - it's designed for exactly that purpose
16,417,449
I create my own class and I want to use it in my new component but I am getting an error... The code is the following: ``` type TMyClass = class Name: string; Number: double; end; TMyComponent = class(TCustomPanel) private FMyClass: TMyClass; public procedure SetMyClass(aName: string; aNumber: double); published property MyClass: TMyClass write SetMyClass; end; procedure SetMyClass(aName: string; aNumber: double); begin FMyClass.Name:= aName; FMyClass.Number:= aNumber; end; ``` it appears that the property has incompatible types, I don't know why. Does anybody has a clue about that and how can I solve this problem. Having a FName and FNumber as fields in TMyComponent is not an option, my code is more complex and this is a simple example to explain my goal. thanks
2013/05/07
[ "https://Stackoverflow.com/questions/16417449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2338944/" ]
The things that I can see wrong with your code at present are: 1. The property setter must receive a single parameter of the same type as the property, namely `TMyClass`. 2. The property setter must be a member of the class, but you've implemented it as a standalone procedure. 3. A published property needs to have a getter. So the code would become: ``` type TMyClass = class Name: string; Number: double; end; TMyComponent = class(TCustomPanel) private FMyClass: TMyClass; procedure SetMyClass(Value: TMyClass); published property MyClass: TMyClass read FMyClass write SetMyClass; end; procedure TMyComponent.SetMyClass(Value: TMyClass); begin FMyClass.Name:= Value.Name; FMyClass.Number:= Value.Number; end; ``` This code does not instantiate `FMyClass`. I'm guessing that the code that does instantiate `FMyClass` is part of the larger component code that has been excised for the sake of this question. But obviously you do need to instantiate `FMyClass`. An alternative to instantiating `FMyClass` is to turn `TMyClass` into a record. Whether or not that would suit your needs I cannot tell. --- It looks like you are having some problems instantiating this object. Do it like this: ``` type TMyClass = class Name: string; Number: double; end; TMyComponent = class(TCustomPanel) private FMyClass: TMyClass; procedure SetMyClass(Value: TMyClass); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property MyClass: TMyClass read FMyClass write SetMyClass; end; constructor TMyComponent.Create(AOwner: TComponent); begin inherited; FMyClass:= TMyClass.Create; end; destructor TMyComponent.Destroy; begin FMyClass.Free; inherited; end; procedure TMyComponent.SetMyClass(Value: TMyClass); begin FMyClass.Name:= Value.Name; FMyClass.Number:= Value.Number; end; ``` One final comment. Using `MyClass` for an object is a bad name. Use class for the type, and object for the instance. So, your property should be `MyObject` and the member field should be `FMyObject` etc.
43,016
I use VMware Fusion created a VM(Linux) in my Mac, but I don't know how to delivery the data from my Mac to the VM. If the VM is on the Windows I can use the WinSCP to load data to it, but how can I load data to VM from Mac? Some friend can recommend me a software to load data to Linux?
2017/06/16
[ "https://softwarerecs.stackexchange.com/questions/43016", "https://softwarerecs.stackexchange.com", "https://softwarerecs.stackexchange.com/users/28348/" ]
I have been using something called [Alpha VNC Lite](https://play.google.com/store/apps/details?id=de.abr.android.avnc). Alpha VNC lite doesn't seem to work on the home screen but most other apps seem to work fine. The device doesn't need to be rooted but you do not to enable a special keyboard and accessibility options. It requires Android 5.0 and up. You can use it for free. VNC software never really works perfectly but it is still cool. [![enter image description here](https://i.stack.imgur.com/X5BgR.png)](https://i.stack.imgur.com/X5BgR.png)
339,902
Suppose you are implementing a publication database and creating migrations to represent different publications. Each publication has a "year" associated with it. `t.column :year, ???` Would this year be best represented as an integer, date, or datetime?
2008/12/04
[ "https://Stackoverflow.com/questions/339902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39584/" ]
I would recommend just going with Rails conventions and doing a `Date` data type. This way, if you ever *do* need the month and day, you can retrieve it. Plus, it's simple to do: ``` YourModel.date.year # => "1999" ```
11,441,468
New to Eclipse and Solr, I imported apache-solr-3.6.0.war into Eclipse and run Solr with tomcat plugin. Now i want to debug some existing code, however how do i import the Solr source code?
2012/07/11
[ "https://Stackoverflow.com/questions/11441468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/962382/" ]
Without knowing how you imported it exactly: sounds like you are looking for [Source attachment](https://stackoverflow.com/questions/122160/is-there-an-easy-way-to-attach-source-in-eclipse). It might be better if you use the [Solr source code](http://apache.mirror.clusters.cc/lucene/solr/3.6.0/) directly. Check the README file included in the release, there is an ant task to init eclipse: > > To setup your ide run [...] 'ant eclipse'. > > > Then all dependencies are loaded using [ivy](http://ant.apache.org/ivy/) and you can run it from within the IDE.
10,323,548
I am not using a coding language. This has to be straight regex. I need to add a variable length of whitespace between two strings. The string I am passing to the regex has the number of whitespaces in the string itself and will need to be replaced: ``` string1 *27* string2 ``` so I need to insert 27 whitespaces into this string between string1 and string 2 ``` \*(\d+)\* ``` This is my capture and it appear to be working, but I was trying to setup my replace with this: ``` \s{$1} ``` or this: ``` $&\s{$1} ``` So how would you do it? I am using expresso for my validation, but not all the regex patterns are supported by the text engine I am using.
2012/04/25
[ "https://Stackoverflow.com/questions/10323548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/183408/" ]
This is not possible with straight regex. Regex would need some sort of parsing capabilities to use the captured variable and translate it into repeating spaces. The way you want replace to work is not possible, also. As the replace portion of a regex is a straight text replace, and not another regex evaluator....it would be kind of cool to have some sort of recursive regex though :)
239,405
As stated from the questions title: **What does 'beta' state of a SE site actually imply?** Could someone elaborate, which restrictions or drawbacks we should expect from a *'beta'* SE site? I could have well been missing something, that's already been answered, or is an easy to find policies concept.
2014/09/15
[ "https://meta.stackexchange.com/questions/239405", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/186472/" ]
Beta sites aren't full sites. They're sites in a "trial" period, to see if they have the potential to become successful sites, or if interest in them wanes and the community dies out. From time to time, the site's community will be asked to [evaluate their site to ensure it is fulfilling its goal](https://meta.stackexchange.com/questions/161033/which-questions-need-community-evaluaton). However, terms of functionality, beta sites behave like full sites, though with [reduced reputation requirements](https://meta.stackexchange.com/questions/58587/reputation-requirements-compared) for most of the tools, to make it easier for a brand new community to self-moderate. The main difference between beta and full sites is the presentation. Beta sites all use the same generic theme and don't have a prominent link in the site footer (they're buried under "more").
47,374,425
On my app, I'm trying to make it so that if a user has a certain condition, he will ALWAYS be redirected to a certain page, no matter which route he tries to access. In this case, it's if he doesn't have a username (long story). **ComposerServiceProvider.php** : ``` public function boot() { View::composer('templates.default', function ($view) { if(Auth::user()) { if (Auth::user()->username == null || Auth::user()->username == "") { return redirect()->route('auth.chooseUsername'); } ``` So I figured the place to do this would be `ComposerServiceProvider.php`. However, I'm noticing that my redirect don't work in `ComposerServiceProvider.php`. And `laravel.log` doesn't give me an error or reason why. The if condition is being met. If I replace `return redirect()->route('auth.chooseUsername');` with `dd('test');`, sure enough all my pages return 'test'. Why is this happening?
2017/11/19
[ "https://Stackoverflow.com/questions/47374425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2280332/" ]
Try this steps: You can use middleware for this scenario like below: 1. Create middleware `php artisan make:middleware CheckPoint` Inside `App\Http\Middleware\CheckPoint.php` File ``` use Closure; class CheckPoint { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if($request->user()) { if ($request->user()->username == null || $request->user()->username == "") { return redirect()->route('auth.chooseUsername'); } } return $next($request); } } ``` 2. Add the middleware inside the `app\Http\kernel.php` ``` protected $routeMiddleware = [ 'checkPoint' => \App\Http\Middleware\CheckPoint::class, ]; ``` 3. Then you can use it inside your route file and controller like below `Route::get(...)->middleware('checkPoint');` `Route::middleware('checkPoint')->group(function() { //Group of routes ..... });` [More About Middleware](https://laravel.com/docs/5.5/middleware) [controller middleware](https://laravel.com/docs/5.5/controllers#controller-middleware)
44,027,873
Here is my problem: I have a task running a Docker image on Amazon ECS but I would like to make a new Docker image from the running instance of the container. I see the id of the instance on Amazon ECS; I have made an AMI but I would like to make a new docker image that I can pull from Amazon. Any ideas? Regards and thanks.
2017/05/17
[ "https://Stackoverflow.com/questions/44027873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/462794/" ]
To create a image from container execute the command below: > > `docker commit container_id imagename` > > >
12,550,086
I came across some threads on StackOverflow but none of them quite cleared my doubts. So the problem is simple. I need to iteratively insert elements into a binary tree. And this is my code. ``` BST newNode(int x) { BSTNodePtr node = (BSTNodePtr) malloc(sizeof(struct TreeNode)); node->Element = x; node->Left = NULL; node->Right = NULL; return node; } BST Insert(int x, BST T) { BST temp_node = T; while( T != NULL) { if (x < T->Element) T = T->Left; else if (x >= T->Element) T = T->Right; } T = newNode(x); return temp_node; } ``` However, when I'm finding the height of this tree I am always getting 0. The height code is ``` int Height(BST T) { if (T == NULL) return 0; return 1+(max(Height(T->Left), Height(T->Right))); } ``` and this works perfectly fine when I do insertion recursively (using a function with the exact same signature) What am I missing?
2012/09/23
[ "https://Stackoverflow.com/questions/12550086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1123924/" ]
Couldn't solve the problem that way. This code, however, seems to work. ``` BST Insert(int x, BST T) { BST temp=T; BST node=(BST)malloc(sizeof(struct TreeNode)); node->Element=x; node->Left=NULL; node->Right=NULL; if (T==NULL) { T=node; return(T); //printf("%d\n",T->Element); } else { while(1) { if (temp->Element>=node->Element && temp->Left==NULL) { temp->Left=node; break; } else if (temp->Element>=node->Element && temp->Left!=NULL) { temp=temp->Left; } else if (temp->Element<node->Element && temp->Right==NULL) { temp->Right=node; break; } else { temp=temp->Right; } } return(T); } } ```
2,289,518
> > How to calculate $5^{2003}$ mod $13$ > > > using fermats little theorem 5^13-1 1 mod 13 (5^12)^166+11 mod 13 a+b modn=(a modn + b modn) modn (1+11mod13)mod13 12 mod 13 = 12 why answer is 8 ? how do we calculate this thanks
2017/05/20
[ "https://math.stackexchange.com/questions/2289518", "https://math.stackexchange.com", "https://math.stackexchange.com/users/437586/" ]
All modulo 13, $$5^{2003} \equiv (5^{2})^{1001} (5)$$ $$\equiv (-1)^{1001}(5)$$ $$\equiv -5$$ $$\equiv 8$$
54,736,145
-How can I scale the Y- and X- axis to 0,30 and 0,50 respectively and plot the data point according to the scale? -How do I change the color of groups 1, 2 and 3 to purple, orange and yellow? ``` library(ggplot2) library(plotly) ID <- c("Group 1", "Group 1", "Group 1", "Group 2", "Group 2", "Group 2", "Group 3", "Group 3", "Group 3", "Group 4", "Group 4", "Group 4") area <- c("Area 1", "Area 1", "Area 1","Area 2", "Area 2", "Area 2", "Area 3", "Area 3", "Area 3", "Area 4", "Area 4", "Area 4") x <- c(1.0, 10.25, 50.0, 2.0, 5.0, 30.0, 5.0, 9.0, 10.0, 11.0, 23.0, 40.0) y <- c(1.0, 3.0, 5.0, 20.0, 10.0, 23.0, 25.0, 19.1, 5.0, 15.0, 8.0, 4.0) df <- cbind(ID, area, x, y) df <- as.data.frame(df) df p <- ggplot(df, aes(x=x, y=y)) + geom_polygon(aes(fill=factor(ID), group=area)) p <- ggplotly(p) p ``` [![enter image description here](https://i.stack.imgur.com/qY4eh.png)](https://i.stack.imgur.com/qY4eh.png) I have tried to play around with scale\_x\_continuous, scale\_fill\_manual, and scale\_fill\_identity but it doesn`t seem to do anything.
2019/02/17
[ "https://Stackoverflow.com/questions/54736145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9710121/" ]
First, convert the x and y columns to number (they are factors in the data). Then, set the scale limits using scale\_x\_continuous and scale\_y\_continuous. Finally, use scale\_fill\_manual to change the colors (since you have a fourth group, I gave it another color). ``` library(tidyverse) df <- df %>% mutate(x = parse_number(x), y = parse_number(y)) p <- ggplot(df, aes(x=x, y=y)) + geom_polygon(aes(fill=factor(ID), group=area)) + scale_x_continuous(limits = c(0,50)) + scale_y_continuous(limits = c(0,30)) + scale_fill_manual(values = c("purple", "orange", "yellow", "gray40")) ggplotly(p) ```
29,226,198
I'm looking for function that **Open window explorer in C language**. I have found this [answer]**([How can I open Windows Explorer to a certain directory from within a WPF app?](https://stackoverflow.com/questions/1746079/how-can-i-open-windows-explorer-to-a-certain-directory-from-within-a-wpf-app))**, but this is C# language. **C can't have these features**? I use VS 2010. I'm a beginner of C. So my question may seem ridiculously easy. But if you give me the answer I really appreciate it. Thanks :)
2015/03/24
[ "https://Stackoverflow.com/questions/29226198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4427613/" ]
The simplest way to open a certain directory in an explorer (here c:\program files) may be: ``` system("start \"\" \"c:\\program files\""); ```
155,822
I'm having some problems getting my table and caption formatting to look right. Below is a sample of the code from my thesis. I've included all the packages that I'm using in my thesis, so that you can get an idea of what else might be affecting the look of the table. I've also attached a picture of my output. The main issues that I have with the table are: 1. The caption text sits too close to the top of the table. Is there a way to get this to sit a little higher (0.5-1 line spaces) above the table? 2. The rows are too closely spaced, making it a little hard to read the nuclide and atomic mass numbers for the elements. Does line spacing not affect tables? How can I can increase the spacing between rows? 3. The text underneath the table needs to sit directly beneath the table and be no wider than the width of the table. How do I go about this? Thanks for the help! ![enter image description here](https://i.stack.imgur.com/i85i6.png). ``` \documentclass[12pt,a4paper]{report} \usepackage{setspace} \usepackage{amsmath} \usepackage{graphicx} \usepackage{layout} \usepackage{lscape} \usepackage[round]{natbib} \usepackage{array} \usepackage{booktabs} \usepackage{siunitx} \usepackage{tensor} \begin{document} \doublespacing \begin{table} \centering \caption{Naturally occurring long-lived radionuclides and their stable radiogenic daughters frequently used in geochronology.}\label{tab:001} \addtolength{\tabcolsep}{-2pt} % slight reduction of intercolumn space \begin{tabular}{*{4}{c} >{\raggedright\arraybackslash}p{3.5cm}} \toprule Parent & Decay Modes$^a$ & Half-life (years) & Daughters \\ \midrule $^{40}_{19}$K & $\varepsilon$: $10.72\%$, $\beta^{+}$: $1.0\times 10^{-3}\%$ & $1.248 \times 10^{9}$ & $^{40}_{18}$Ar \\ $^{40}_{19}$K & $\beta^{-}$: $89.28\%$ & $1.248 \times 10^{9}$ & $^{40}_{20}$Ca \\ $^{87}_{37}$Rb & $\beta^{-}$: $100\%$ & $4.81\times 10^{10}$ & $^{87}_{38}$Sr \\ $^{147}_{62}$Sm & $\alpha$: $100\%$ & $1.06\times 10^{11}$ & $^{143}_{60}$Nd \\ $^{176}_{71}$Lu & $\beta^{-}$: $100\%$ & $3.76\times 10^{10}$ & $^{176}_{72}$Hf \\ $^{187}_{75}$Re & $\alpha$: $1.0\times 10^{-4}\%$, $\beta^{-}: 100\%$ & $4.33\times 10^{10}$ & $^{187}_{76}$Os \\ $^{232}_{90}$Th & $\alpha$: $100\%$, SF: $1.1\times 10^{-9}\%$ & $1.40\times 10^{10}$ & $^{208}_{82}$Pb \\ $^{235}_{92}$U & $\alpha$: $100\%$, SF: $7.0\times 10^{-9}\%$ & $7.04\times 10^{8}$ & $^{207}_{82}$Pb \\ $^{238}_{92}$U & $\alpha$: $100\%$, SF: $5.5\times 10^{-5}\%$ & $4.468\times 10^{9}$ & $^{206}_{82}$Pb \\ \bottomrule \end{tabular} \end{table} $^{a}$ $\varepsilon$ = electron capture decay; $\beta^{+}$ = positron decay; $\beta^{-}$ = negatron decay; $\alpha$ = alpha decay. \end{document} ```
2014/01/24
[ "https://tex.stackexchange.com/questions/155822", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/44564/" ]
1. It's enough to load the [`caption`](http://www.ctan.org/pkg/caption) package (you could even set a bigger `skip`, if needed). 2. Redefine `\arraystretch` locally. 3. Build your table and its footnote using the [`ctable`](http://www.ctan.org/pkg/ctable) package. The code: ``` \documentclass[12pt,a4paper]{report} \usepackage{booktabs} \usepackage{siunitx} \usepackage{chemmacros} \usepackage{caption} \usepackage{ctable} \begin{document} { \renewcommand\arraystretch{1.3} \addtolength{\tabcolsep}{-2pt} % slight reduction of intercolumn space \ctable[ caption = {Naturally occurring long-lived radionuclides and their stable radiogenic daughters frequently used in geochronology.}, label= {tab:001}, mincapwidth = \textwidth, footerwidth ] {ccS[table-figures-exponent=2,table-figures-integer=2,table-figures-decimal=3,table-number-alignment=center]c } {% \tnote{$\varepsilon$ = electron capture decay; $\beta^{+}$ = positron decay; $\beta^{-}$ = negatron decay; \\ $\alpha$ = alpha decay.}% } {% \toprule Parent & Decay Modes & {Half-life (years)} & Daughters \\ \midrule \ch{^{40}_{19}K} & $\varepsilon$: \SI{10.72}{\percent}, $\beta^{+}$: \SI{1.0e-3}{\percent} & 1.248e9 & \ch{^{40}_{18}Ar} \\ \ch{^{40}_{19}K} & $\beta^{-}$: \SI{89.28}{\percent} & 1.248e9 & \ch{^{40}_{20}Ca} \\ \ch{^{87}_{37}Rb} & $\beta^{-}$: $100\%$ & 4.81e10 & \ch{^{87}_{38}Sr} \\ \ch{^{147}_{62}Sm} & $\alpha$: \SI{100}{\percent} & 1.06e11 & \ch{^{143}_{60}Nd} \\ \ch{^{176}_{71}Lu} & $\beta^{-}$: \SI{100}{\percent} & 3.76e10 & \ch{^{176}_{72}Hf} \\ \ch{^{187}_{75}Re} & $\alpha$: \SI{1.0e-4}{\percent}, $\beta^{-}$: \SI{100}{\percent} & 4.33e10 & \ch{^{187}_{76}Os} \\ \ch{^{232}_{90}Th} & $\alpha$: \SI{100}{\percent}, SF: \SI{1.1e-9}{\percent} & 1.40e10 & \ch{^{208}_{82}Pb} \\ \ch{^{235}_{92}U} & $\alpha$: \SI{100}{\percent}, SF: \SI{7.0e-9}{\percent} & 7.04e8 & \ch{^{207}_{82}Pb} \\ \ch{^{238}_{92}U} & $\alpha$: \SI{100}{\percent}, SF: \SI{5.5e-5}{\percent} & 4.468e9 & \ch{^{206}_{82}Pb} \\ \bottomrule } } \end{document} ``` ![enter image description here](https://i.stack.imgur.com/Tn8Fk.png) ### Additional improvements: 1. The `siunitx` package was used to format the entries in the third column. 2. The `chemmacros` package was used to properly format the sub/superscripts in the first and third columns.
801,940
I have a parameterized hibernate dao that performs basic crud operations, and when parameterized is used as a delegate to fulfil basic crud operations for a given dao. ``` public class HibernateDao <T, ID extends Serializable> implements GenericDao<T, ID> ``` I want to be able to derive Class from T at runtime to create criteria queries in Hibernate, such that: ``` public T findByPrimaryKey(ID id) { return (T) HibernateUtil.getSession().load(T.getClass(), id); } ``` I know: ``` T.getClass() ``` does not exist, but is there any way to derive the correct Class object from T at runtime? I have looked at generics and reflection but have not come up with a suitable solution, perhaps I am missing something. Thanks.
2009/04/29
[ "https://Stackoverflow.com/questions/801940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49854/" ]
You could have the Class passed as a constructor argument. ``` public class HibernateDao <T, ID extends Serializable> implements GenericDao<T, ID> { private final Class<? extends T> type; public HibernateDao(Class<? extends T> type) { this.type = type; } // .... } ```
58,576,631
I want to learn to create a wrapper around a program in linux. How does one do this? A tutorial reference web-page/link or example will do. To clarify what I want to learn, I will explain with an example. I use **vim** for editing text files. And use **rcs** as my simple revision control system. **rcs** allows you to check-in and checkout-files. I would like to create a warpper program named **vir** which when I type in the shell as: ``` $ vir temp.txt ``` will load the file temp.txt into rcs with `ci -u temp.txt` and then allows me to edit the file using vim. When I get out and go back in, It will need to check out the file first, using `ci -u temp.txt` and allow me to edit the file as one normally does with vim, and then when I save and exit, it should check-in the file using `co -u temp.txt` and as part of that I should be able to add a version control comment. Basically, all I want to be doing on the command line is: ``` $ vir temp.txt ``` as one would with vim. And the wrapper should take care of the version control for me.
2019/10/27
[ "https://Stackoverflow.com/questions/58576631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4567351/" ]
There are a few missing dependencies in your `create-react-app` project. This probably happened because you tried to export the project from codesandbox (I'm not sure though) You have to fix those first. **Dependency 1** (`react-scripts`): ``` npm install react-scripts --save-dev ``` **Dependency 2** (`node-sass` because you are using `scss` in your project) ``` npm install node-sass --save ``` **Dependency 3** (`gh-pages`) ``` npm install gh-pages --save-dev ``` After the above steps are completed, verify your package.json to match below structure ``` { "name": "and-air", "version": "1.0.0", "description": "", "keywords": [], "main": "src/index.js", "homepage": "https://develijahlee.github.io/andair/", "dependencies": { "@fortawesome/fontawesome-svg-core": "1.2.25", "@fortawesome/free-regular-svg-icons": "5.11.2", "@fortawesome/react-fontawesome": "0.1.5", "node-sass": "^4.13.0", "react": "16.9.0", "react-dom": "16.8.6" }, "devDependencies": { "gh-pages": "^2.1.1", "react-scripts": "^3.2.0", "typescript": "3.3.3" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject", "predeploy": "npm run build", "deploy": "gh-pages -d build" }, "browserslist": [ ">0.2%", "not dead", "not ie <= 11", "not op_mini all" ] } ``` Now you can run the **deploy** script ``` npm run deploy ``` After this step, verify that a new branch created with name `gh-pages` [![enter image description here](https://i.stack.imgur.com/zDaAL.png)](https://i.stack.imgur.com/zDaAL.png) Click on the **settings** tab in github [![enter image description here](https://i.stack.imgur.com/URU21.png)](https://i.stack.imgur.com/URU21.png) Scroll down to the **GitHub Pages** section and switch your branch to `gh-pages` branch. [![enter image description here](https://i.stack.imgur.com/07Mj4.png)](https://i.stack.imgur.com/07Mj4.png) You should get a success message when the page is live. [![enter image description here](https://i.stack.imgur.com/PQ4Ls.png)](https://i.stack.imgur.com/PQ4Ls.png)
63,452,974
I am trying to install Pylucene on my WSL Ubuntu 20.04 clean installation. I tried to follow tutorial on [the official page but it looks outdated](https://lucene.apache.org/pylucene/install.html). So I was wondering if anyone here managed to make it work on Ubuntu 20.04 and python 3.8.2 The commands I run: ``` sudo apt-get upgrade sudo apt-get install -y default-jdk ant build-essential python3-dev mkdir pylucene cd pylucene curl https://downloads.apache.org/lucene/pylucene/pylucene-8.3.0-src.tar.gz | tar -xz --strip-components=1 cd jcc export JCC_JDK=/usr/lib/jvm/default-java python3 setup.py build ``` ^^^^^ Fails here on: ``` ... building 'jcc3' extension x86_64-linux-gnu-gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -D_jcc_lib -DJCC_VER="3.7" -I/usr/lib/jvm/default-java/include -I/usr/lib/jvm/default-java/include/linux -I_jcc3 -Ijcc3/sources -I/usr/include/python3.8 -c jcc3/sources/jcc.cpp -o build/temp.linux-x86_64-3.8/jcc3/sources/jcc.o -DPYTHON -fno-strict-aliasing -Wno-write-strings x86_64-linux-gnu-gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -D_jcc_lib -DJCC_VER="3.7" -I/usr/lib/jvm/default-java/include -I/usr/lib/jvm/default-java/include/linux -I_jcc3 -Ijcc3/sources -I/usr/include/python3.8 -c jcc3/sources/JCCEnv.cpp -o build/temp.linux-x86_64-3.8/jcc3/sources/JCCEnv.o -DPYTHON -fno-strict-aliasing -Wno-write-strings x86_64-linux-gnu-g++ -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fwrapv -O2 -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 build/temp.linux-x86_64-3.8/jcc3/sources/jcc.o build/temp.linux-x86_64-3.8/jcc3/sources/JCCEnv.o -o build/lib.linux-x86_64-3.8/libjcc3.so -L/usr/lib/jvm/default-java/jre/lib/amd64 -ljava -L/usr/lib/jvm/default-java/jre/lib/amd64/server -ljvm -Wl,-rpath=/usr/lib/jvm/default-java/jre/lib/amd64:/usr/lib/jvm/default-java/jre/lib/amd64/server -Wl,-S /usr/bin/ld: cannot find -ljava /usr/bin/ld: cannot find -ljvm collect2: error: ld returned 1 exit status error: command 'x86_64-linux-gnu-g++' failed with exit status 1 ``` Commands I plan to run afterwards: ``` sudo python3 --preserve-env=JCC_JDK setup.py install cd .. make make test sudo make install ```
2020/08/17
[ "https://Stackoverflow.com/questions/63452974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5594539/" ]
Here are the steps that lead to the successful installation of pylucene on Ubuntu 18.04 - this may work for you: 1. Install openjdk-8: `apt install openjdk-8-jre openjdk-8-jdk openjdk-8-doc` Ensure that you have ant installed, if you don't run `apt install ant`. Note that if you had a different version of openjdk installed you need to either remove it or run `update-alternatives` so that version 1.8.0 is used. 2. Check that Java version is 1.8.0\* with `java -version` 3. After installing openjdk-8 create a symlink (you'll need it later): ``` cd /usr/lib/jvm ln -s java-8-openjdk-amd64 java-8-oracle ``` 4. Install python-dev: `sudo apt install python-dev` In my case Python 3 didn't work so I ended up using Python 2. But this might not have been the actual reason of the problem, so you're welcome to try Python 3. If you go with Python 3, use `python3` instead of `python` in the commands below. 5. Install JCC (in jcc subfolder of your pylucene folder): ``` python setup.py build python setup.py install ``` The symlink you created on step 3 will help here because this path is hardcoded into setup.py - you can check that. 6. Install pylucene (from the root of your pylucene folder). Edit Makefile, uncomment/edit the variables according to your setup. In my case it was ``` PREFIX_PYTHON=/usr ANT=ant PYTHON=$(PREFIX_PYTHON)/bin/python JCC=$(PYTHON) -m jcc --shared NUM_FILES=10 ``` Then run ``` make make test sudo make install ``` 7. If you see an error related to the shared mode of JCC remove `--shared` from Makefile.
61,559,348
I am integrating JWT authorization from Cognito into my Nestjs application and I am running into a sort of a chicken vs egg situation. If a generate clientSecret for my Cognito client, I will get the following error: > > "Unable to verify secret hash for client {Client\_Id}" > > > If I uncheck clientScret generation when creating a new client in Cognito, I will get the following error when the application compiles: > > [ExceptionHandler] JwtStrategy requires a secret or key +0ms > > > I have been following this guide to implement it: <https://brightinventions.pl/blog/using-cognito-with-nest-js/>, but it does not really address any of these issues. Could someone provide some guidance here?
2020/05/02
[ "https://Stackoverflow.com/questions/61559348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10603880/" ]
The tutorial you shared let the back-end side handle the user register, sign in, and sign out. I want to delegate the access token getting to AWS Cognito. For a user to request protected resources, the backend side validates the access token passed as a bearer token in two ways: * Use middleware: <https://github.com/katesroad/Cognito-as-Authentication-Provider-for-NestJs/blob/main/backend/src/common/middlewares/auth.middleware.ts> Also, this link worth reading <https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-verifying-a-jwt.html>. How to validate the jwt token generated by an AWS Cognito pool. If you don't want to access other user information, having the user being validate is enough by validating the user's access token. If you want to get the user's other information (such as email and custom attributes), you can use the version shared by you or getting user information by the user's sub id stored in the JWT token. Thanks, happy coding. Hope this could help you.
24,491,420
Is there any difference between these 2 quesries? This is from test and one asnwer is right and accordingly another wrong. For me, both are valid and similar. ``` B. SELECT Cust_No, Cust_Name, Emp_Name, Emp_Loc FROM Customers, Employees WHERE Customers.Sales_Rep_No = Employees.Sales_Rep_No; C. SELECT Cust_No, Cust_Name, Emp_Name, Emp_Loc FROM Customers, Employees WHERE Employees.Sales_Rep_No = Customers.Sales_Rep_No; ```
2014/06/30
[ "https://Stackoverflow.com/questions/24491420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2705336/" ]
Yes, they differ in their `WHERE`-clauses, but everything else (the Tables joined, the columns retrieved, is the same, and they also should really produce the same result): `WHERE Customers.Sales_Rep_No = Employees.Sales_Rep_No;` `WHERE Employees.Sales_Rep_No = Customers.Sales_Rep_No;`
18,753
My attendant and I met a year ago and had intercourse back then, we recently picked back up where we left off, but want to go about it the right way and get married. Is there a time frame that we have to be apart from each other sexually and not sexual before marriage? What is needed to be done for our marriage to be halal?
2014/11/25
[ "https://islam.stackexchange.com/questions/18753", "https://islam.stackexchange.com", "https://islam.stackexchange.com/users/9208/" ]
There's no time frame, but both of you must repent to Allah(SWT) and never commit that sin again. You and your potential cannot be alone together privately anywhere and at anytime. You must restrain your looks at each other. You must have a **Wali** involved to go about your business with him. You must be covered properly i.e. hijab, and he must have himself covered properly also. There can't be any intimate conversations between the two of you. Until you're married, you can't really have much physical contact.
102,339
I want to buy the full version of Minecraft, but I'm one of those creative types. What are some of the differences in Creative mode in the full version of Minecraft?
2013/01/22
[ "https://gaming.stackexchange.com/questions/102339", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/41294/" ]
From [the wiki](http://www.minecraftwiki.net/wiki/Classic#Advantages_of_purchasing) about the classic version: > > Advantages of purchasing > > > Although this mode is free to the public, there are several advantages > made available to those who have purchased the game. Some of them are > the ability to: > > - Use custom skins in both singleplayer and multiplayer. > > - Use mods that require placement of files in the original minecraft.jar folder. > > - **Build with more blocks and items.** > > - Use crafting and create items. > > - Combat mobs. > > > From a purely creative point of view, you will get more space, and more blocks to choose from, in the full version. Keep in mind also that Minecraft classic is a prototype which has not been updated since 2009. From a technical point of view, the new version (full) will perform better, and look better (new lighting system).
9,119,233
How can I initialize a val that is to be used in another scope? In the example below, I am forced to make `myOptimizedList` as a var, since it is initialized in the `if (iteration == 5){}` scope and used in the `if (iteration > 5){}` scope. ``` val myList:A = List(...) var myOptimizedList:A = null for (iteration <- 1 to 100) { if (iteration < 5) { process(myList) } else if (iteration == 5) myOptimizedList = optimize(myList) } if (iteration > 5) { process(myOptimizedList) } } ``` This may have been asked [before](https://stackoverflow.com/questions/7425854/scala-create-val-for-outer-scope), but I wonder if there is an elegant solution that uses Option[A].
2012/02/02
[ "https://Stackoverflow.com/questions/9119233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/750995/" ]
Seems that you have taken this code example out of the context, so this solution can be not very suitable for your real context, but you can use `foldLeft` in order to simplify it: ``` val myOptimizedList = (1 to 100).foldLeft (myList) { case (list, 5) => optimize(list) case (list, _) => process(list); list } ```
1,320,991
My textbook says: Suppose that $E$ is a convex region in the plane bounded by a curve $C$. [Where a convex region is defined as for all $x, y \in E, sx + ty \in E$ where $0 \le s, t \le 1$ and $s + t = 1$.] Show that $C$ has a tangent line except at a countable number of points. So my thinking is roughly that points without tangent lines look like sharp corners with some angle $\theta < 180^\circ$ and so if $\theta\_m$ is the largest $\theta$ in $C$ then the most corners you can pack into $C$ is the regular $n$-gon with $n=\frac{2}{180-\theta\_m}$. Except that seems to suggest that $C$ must have a tangent line except at finitely many points whereas the question clearly asks about countably many. So what's the pathological convex curve with infinitely many discontinuities that thwarts my proof?
2015/06/11
[ "https://math.stackexchange.com/questions/1320991", "https://math.stackexchange.com", "https://math.stackexchange.com/users/204420/" ]
Line segments from $(n,n^2)$ to $((n+1),(n+1)^2)$ for each integer $n$ you should draw. A nice and simple convex region you will get.
70,811,590
Let's say we have the following table: ``` city gender abc m abc f def m ``` Required output: --- ``` city f_count m_count abc 1 1 def 0 1 ``` Please help me in writing a query either in Hive or MySQL or SQL Server syntax. Hive syntax is needed for me. Thank You:)
2022/01/22
[ "https://Stackoverflow.com/questions/70811590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13345717/" ]
Try: ``` select city,sum(gender='f') as f_count,sum(gender='m') as m_count from my_table group by city; ``` > > Result: > > > > ``` > city f_count m_count > abc 1 1 > def 0 1 > > ``` > > [Demo](https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=e9e64e17c116766877f1ba802492fac3)
57,887,300
My Github repo won't update after `git push -u origin master` command! It says: ``` Branch 'master' set up to track remote branch 'master' from 'origin'. Everything up-to-date ``` The result for `git remote show origin` is: ``` * remote origin Fetch URL: [email protected]:MyGithubID/RepoName.git Push URL: [email protected]:MyGithubID/RepoName.git HEAD branch: master Remote branch: master tracked Local branch configured for 'git pull': master merges with remote master Local ref configured for 'git push': master pushes to master (up to date) ``` and for `git status`: ``` On branch master Your branch is up to date with 'origin/master'. Changes to be committed: (use "git reset HEAD <file>..." to unstage) new file: myFile.m ``` I have no idea what is going on! I tried `git push --all origin` and it says: `Everything up-to-date` but it's not! I'm new with git; I checked 'config' file in my .git directory and the information is correct. What is wrong with my git?!
2019/09/11
[ "https://Stackoverflow.com/questions/57887300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7522214/" ]
You have only staged the file for commit, but not actually committed the change. You have to commit the change to get a commit-id which is then used during the push/pull phase. ``` git commit ``` With `git`, committing a change is a two step process. The first step is to add your change(s) to a so called staging area. This is local to the repo and will not participate when pushing a changes to the remote. In your case you have added a new file to the staging area and git push will not consider the changes in the staging area. Only changes that are committed are discussed during the push/pull process. The second step is to commit the changes.. This step you don't get to choose what changes you can commit. All the changes that you have added in the staging area gets into the commit and git creates a commit-id which is now version controlled (in your local repo).. Once a commit is done, the staging area is clear. some commands to add files to the staging are. ``` git add <file_name> #Add all changes made to this file. git add <dir> #Add all changed files in that directory. git add -i # This is interactive menu-type command ``` Instead of adding all the changes(called as hunks) made to a file, You can also choose to add selected changes in a file, using the patch option. ``` git add -i #choose patch option. ``` The changes in staging area is the delta from `HEAD`. To remove the changes from the staging area you have to reset the HEAD file as it was in HEAD. Once you reset, all changes are gone from the staging area but not lost, you will see the hunks in the un-staged area. ``` git reset HEAD <file> ```
37,711
Comme l'on lit dans cette **excellente réponse** [Quand peut-on mettre un adjectif avant ou après un nom ? — When do adjectives go before or after a noun?](https://french.stackexchange.com/questions/319/quand-peut-on-mettre-un-adjectif-avant-ou-apr%c3%a8s-un-nom-when-do-adjectives-go/323#323) > > La place de l'épithète par rapport au nom remplit plus d'une dizaine > de pages du Grevisse (de §325 à §332 dans l'édition 2008). > > > Je me demande si des tournures comme **excellente réponse**, **excellente oeuvre** au lieu des plus traditionnelles **réponse excellente** et **oeuvre excellente** choqueraient les locuteurs natifs du français. Par exemple > > Je vous félicite pour votre excellente oeuvre. > > > Ibid. pour l'adjectif **monumental**. Par exemple. > > Le mécanicien et mathématicien Clifford Truesdell est l'auteur des monumentales oeuvres. > > >
2019/08/01
[ "https://french.stackexchange.com/questions/37711", "https://french.stackexchange.com", "https://french.stackexchange.com/users/16020/" ]
Si on trouve ***excellent*** plutôt avant le nom ça tient au sens même de cet adjectif. L'adjectif exprimant un jugement, un réaction subjective, affective se place avant le nom. (Grevisse §398 10e édition, qui renvoie à l'article de Marouzeau « Encore la place de l'adjectif » dans *Le Français Moderne*, oct. 1953, [p. 241-243](https://fr.calameo.com/read/0009039473e627990eacf?authid=FcLgsii5nHaQ)) : > > C'est une excellente initiative. > > > On peut bien sûr trouver *excellent* après le nom. > > La belle matière, la maturité du Chenin a bien été saisie dans ce vin excellent qui a su jouer le jeu de la fraîcheur avec cette finale sapide et minérale. ([In Vino veritas](http://www.in-vino-veritas.fr/les-appellations-meconnues/)) > > > Selon l'analyse de Mazureau à laquelle renvoie Grevisse, ici *excellent* exprime une valeur discriminative qui classe le vin en question dans une catégorie (celle des vins excellents). Comme le dit @petitrien ***monumental*** se place quasi exclusivement après le nom parce que, comme le dit Grevisse (§398 10e édition), les adjectifs exprimant une qualité physique se placent après le nom. Cependant la même analyse faite ci-dessus pour « excellent » peut s'appliquer aussi pour « monumental ». > > Ce monumental ouvrage d’art offre un spectacle incomparable sur les montagnes environnantes. ([Site de l'Office de tourisme de Grenoble-Alpes](https://www.grenoble-tourisme.com/de/katalog/activite/les-forts-de-la-bastille-et-du-saint-eynard-293867/)) > > > Dans cet exemple il me semble que l'adjective placé avant reflète l'affectivité du locuteur qui cherche de surcroît à attirer l'attention des touristes. Autre cas similaire : > > Ce monumental échafaudage érigé il y a huit mois sera démonté à partir du lundi 15 avril.[(*La Provence* 11/04/2019](https://www.laprovence.com/article/edition-vaucluse/5452721/le-mur-a-livre-certains-secrets.html)) > > >
69,299,965
I don't know how to describe them, so here is a screenshot [![enter image description here](https://i.stack.imgur.com/BZKHP.png)](https://i.stack.imgur.com/BZKHP.png)
2021/09/23
[ "https://Stackoverflow.com/questions/69299965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
This is one method using css pseudo elements `:before` and `:after`. I used the Horizontal bar Unicode character ― in the css `content:` declaration. ```css div:before { content: "― "; } div:after { content: " ―"; } ``` ```html <div>TEST</div> ```
69,938,288
I have a Vuetify treeview setup in a NuxtJS app like so: ```html <v-treeview open-all color="white" class="info-pool" :load-children="loadChildren" :search="search" :filter="filter" :items="items"> <template slot="label" slot-scope="{ item }"> <a @click="CHANGE_INFO_TOPIC(item)" style="text-decoration: none; color: inherit;">{{ item.name }}</a> </template> </v-treeview> ``` Whenever a node is opened, it's meant to load its children from NuxtJS's content folder like so: ```js async loadChildren(item) { let topicChildren = await this.$content(`${item.location}/${item.item_key}`).sortBy('id', 'asc').fetch() topicChildren.forEach((child) => { let subChildren = child.children ? [] : null; item.children.push({ id: child.id, name: child.name, location: child.location, item_key: child.item_key, children: subChildren }) }) } ``` This method works as intended, and I can see the desired results in the console log after the load-children method kicks off. The parent node's children key is populated with objects as intended. However, the node in the treeview itself remains empty as if its children was still an empty array. What could be the reason for this? * I tried manually pasting the content objects into the node's children array, and they showed up in the treeview. So I know it isn't the formatting of the objects coming from the content fetch method. It must be that the treeview isn't updating after the push. * The [official docs](https://vuetifyjs.com/en/components/treeview/#load-children) show them using a .json() method on the response, but my response is coming from content in array form so I don't believe I need to do that. * While fetching from content is different than fetching from an API, I'm still populating the children array in the same manner. Very confused as to why this method would successfully change the item's children array, but the treeview won't update to reflect it. **Update** This test method with a return is also not functioning ```js async loadChildren(item) { return await this.$content(`${item.location}/${item.item_key}`).sortBy('id', 'asc').fetch() .then(res => {item.children.push(...res)}) } ``` This hardcoded method is also not working. I've tried it with both pushing an array with one object, as well as just an object. ```js async loadChildren(item) { return item.children.push({ id: 1, name: 'blah' }); }, ``` The documentation states: > > You can dynamically load child data by supplying a Promise callback to > the load-children prop.This callback will be executed the first time a > user tries to expand an item that has a children property that is an > empty array. > > > So perhaps the issue is that the method needs to return a Promise callback that would push the child objects into the array. But nuxt-content's fetch() method DOES return a Promise. And I can inspect the node in the component's computed data and see that it has been populated with children. But the node on the treeview still remains empty.
2021/11/12
[ "https://Stackoverflow.com/questions/69938288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10029354/" ]
try this Navigator.popUntil(context, ModalRoute.withName('/c')); or you can simply pop 3 times like Navigator.of(context)..pop()..pop()..pop();
27,871,573
Im developing a WCF web service with receives always and only XML. So i need to validate that input XML using their XSD. The question is, can i save them inside web service? Locally i can access XSD files via relative path into IIS Express root folder which i created manually. I tried add the XSD files in VS project but i just cant a find them on runtime. I'm using the Shemas like this: [Image1 Link](http://s16.postimg.org/cmnm850lh/image.png) IIS XSD'd Folder Path Workaround: [Image2 Link](http://i.stack.imgur.com/ePozA.png) At the moment, its working fine, the problem will be when i try deploy the service somewhere on internet. Thank you. **tl;dr: Can i send some XSD when deploying the webservice or its just impossible?**
2015/01/10
[ "https://Stackoverflow.com/questions/27871573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3542287/" ]
Files that belong to your solution should be **physically** part of it. Once that is the case you can use for instance [`HostingEnvironment.MapPath`](http://msdn.microsoft.com/en-us/library/system.web.hosting.hostingenvironment.mappath%28v=vs.110%29.aspx); or look at the answers to [this question](https://stackoverflow.com/questions/791468/how-to-get-working-path-of-a-wcf-application). Note that there is [a possible issue](http://blogs.msmvps.com/theproblemsolver/2009/02/08/gotcha-with-hostingenvironment-mappath/) with HostingEnvironment.MapPath when the WCF service is self hosted. A possible solution is this method: ``` public static string MapPath(string path) { if (HttpContext.Current != null) return HttpContext.Current.Server.MapPath(path); return HostingEnvironment.MapPath(path); } ``` The parameter `path` needs to be of the format `"~/XSD/MyFile.xsd"`, with the folder "XSD" being located in the root of your WCF service. NEVER create folders in `c:\program files (x86)\iis express`.
9,709,688
Heya I get this error message. I've been looking everywhere but I dont know how to fix it? Im a beginner so I'm really confued. Thanks in advance Notice: Undefined index: cart in /nas/students/j/j39-green/unix/public\_html/ISD5/inc/functions.inc.php on line 3 You have no items in your shopping cart ``` <?php function writeShoppingCart() { $cart = $_SESSION['cart']; if (!$cart) { return '<p>You have no items in your shopping cart</p>'; } else { // Parse the cart session variable $items = explode(',',$cart); $s = (count($items) > 1) ? 's':''; return '<p>You have <a href="cart.php">'.count($items).' item'.$s.' in your shopping cart</a></p>'; } } ```
2012/03/14
[ "https://Stackoverflow.com/questions/9709688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1269822/" ]
If `$_SESSION['cart']` isn't set, it throws that warning. Try: ``` $cart = isset($_SESSION['cart'])?$_SESSION['cart']:false; ```
200,627
I'm using `standalone` document class and trying to draw a TikZ picture. The picture have border which is the border of the page. I do it [like this](http://papeeria.com/p/c6949888bcd012d5fcc4ca5bd8ba79a9#/without-fontspec.tex): ``` \documentclass{standalone} \usepackage{tikz} \def\W{220} \def\H{250} \begin{document} \begin{tikzpicture}[x=1pt,y=1pt] \draw[ultra thick] (0,0) -- (\W,0) -- (\W,\H) -- (0,\H) -- (0,0); \end{tikzpicture} \end{document} ``` And it looks like this (I've added red background just to make the difference visible, and I've done it using gimp, it's not a part of the question) ![the left border at very left](https://i.stack.imgur.com/yZ64i.jpg) But if I just add `\usepackage{fontspec}` to the preamble then some left margin appears and it looks [like this](http://papeeria.com/p/c6949888bcd012d5fcc4ca5bd8ba79a9#/with-fontspec.tex) ![the left border moves to the right](https://i.stack.imgur.com/zFyqb.jpg) So, where does it come from? How can I get rid of it?
2014/09/11
[ "https://tex.stackexchange.com/questions/200627", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/27682/" ]
I see the effect with TexLive 2013, but not with 2014 and miktex. So you will probably have to update something (fontspec?). The effect disappears if I add `\unskip` after `\begin{document}`. So it looks like an spurious space somewhere.
39,065,933
First and foremost, this is my 1st time writing PHP code, so please forgive my newbie'isms. I have a login form with 3 submit buttons (post method) named login, register and forgot. If I select login button, the login function in the PHP code gets called, however, the same is not true for the register and forgot buttons. Its almost like the only submit button that is working is the login buttons. My best guess at this point is there is id/name that not correct. For the sake of brevity I've removed the CSS portion. Any points in the right direction will be most appreciated. ``` <?php function login(){ //do stuff echo "Login"; } function register(){ // do stuff echo "Register"; } function forgot(){ //do stuff echo "Forgot"; } if($_SERVER["REQUEST_METHOD"] == "POST") { if(isset($_POST['login'])) { login(); } if(isset($_POST['register'])) { register(); } if(isset($_POST['forgot'])) { forgot(); } } ?> <html> <head> <meta charset="utf-8"> <title>Login Page</title> </head> <body> <div id="login"> <h1><strong>Welcome!</strong> Please login.</h1> <form action="" method="post"> <fieldset> <p><input type="text" name="username" required value="Username" onBlur="if(this.value=='')this.value='Username'" onFocus="if(this.value=='Username')this.value=''"></p> <p><input type="password" name="password"></p> <p><input type="submit" name= "login" value="Login"></p> <p><input type="submit" name= "register" value="Register"></p> <p><input type="submit" name= "forgot" value="Forgot Password"></p> </fieldset> </form> </div> <!-- end login --> </body> </html> ```
2016/08/21
[ "https://Stackoverflow.com/questions/39065933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3254596/" ]
HTML forms can not contain more than one input of type "submit" (which means others would not be functioning) **register** and **forgot** are links rather than buttons. Instead you could use: ``` <a href="/register.php">Register</a> ``` Another alternative is to use javascript to make these buttons act as links.
7,873,972
I'm rewriting/converting some VB-Code: ``` Dim dt As New System.Data.DataTable() Dim dr As System.Data.DataRow = dt.NewRow() Dim item = dr.Item("myItem") ``` C#: ``` System.Data.DataTable dt = new System.Data.DataTable(); System.Data.DataRow dr = dt.NewRow(); var item = dr.Item["myItem"]; ``` I can't make it run under C#, the problems I have is the third row `var item = dr.Item["myItem"];`: `System.Data.DataRow' does not contain a definition for 'Item' and no extension method 'Item' accepting a first argument of type 'System.Data.DataRow' could be found (are you missing a using directive or an assembly reference?)` I referenced `System.Data` Version 4 in both projects. What am I missing here? Note: ItemArray exists in both...
2011/10/24
[ "https://Stackoverflow.com/questions/7873972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/598516/" ]
Try like this: ``` var item = dr["myItem"]; ``` In C# you can access the [indexer property](http://msdn.microsoft.com/en-us/library/2549tw02.aspx) directly. And the [DataRow.Item](http://msdn.microsoft.com/en-us/library/system.data.datarow.item.aspx) property is defined as indexer.
29,014
There is an existing light fixture and switch for the light fixture. I want to add a bath fan with its own switch. What is the easiest way?
2013/06/24
[ "https://diy.stackexchange.com/questions/29014", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/13644/" ]
If you're not comfortable working with electricity then hire a professional. Improper wiring and the resulting fire isn't worth saving a few bucks. That said: Your existing fan/light combo is likely connected using a 2-conductor cable (like 14-2)... but for two separately switched circuits you'll need three conductors (14-3) or two separate 14-2 wires. At the gang box, one of the conductors goes to the light, and the other goes to the fan.
10,373,163
There a search service (PHP) which sends search query via POST. I would like to use that search engine in my app. The PHP service does not have a public API. Is there a way to enter search query and to fetch a POST request to see the name of parameters? I would use then later to send a POST requests from my app and to catch POST responses. This is an official search engine with governmental officials who do not reply to my requests to tell me the name of parameters. It's nothing illegal, app is free of charge, it's just that I can no longer wait for them as they will reply to me. PS. I have access to Ubuntu shell and its admin tools. **EDIT** This is how the search form looks like in the source of the web page (seen via browser) ``` <form action="search.php" method="POST"> <input type="text" name="search" size=20><br> SZ<input type="checkbox" checked name="sz"> NZ<input type="checkbox" checked name="nz"> <input type="submit" name="search_term" value="search" > </form> ``` **EDIT 2** Do not edit post as a guy suggested me the proper way to do this via linux command curl.
2012/04/29
[ "https://Stackoverflow.com/questions/10373163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/437039/" ]
Have you tried viewing the source on the search form to get the POST parameters? i.e. the name of the input box **Edit** take for example the php form on tizag site ``` <html><body> <h4>Tizag Art Supply Order Form</h4> <form action="process.php" method="post"> <select name="item"> <option>Paint</option> <option>Brushes</option> <option>Erasers</option> </select> Quantity: <input name="quantity" type="text" /> <input type="submit" /> </form> </body></html> ``` the parameters are the input names i.e. quality and item **Java code** (was using this for appengine) ``` HttpURLConnection connection = null; String line = null; BufferedReader rd = null; String urlParameters = "search=search&submit=Submit"; serverAddress = new URL("http://www.search.com/search.php"); // set up out communications stuff connection = null; connection = (HttpURLConnection) serverAddress.openConnection(); // connection.setRequestMethod("GET"); connection.setRequestMethod("POST"); connection.setRequestProperty("Referer", ""); connection.setRequestProperty("User-Agent", ""); connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); connection.connect(); if (connection.getResponseCode() == 404) { throw new ErrorException(); } ArrayList<String> ud = new ArrayList<String>(); rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = rd.readLine()) != null) { ud.add(line); // add response to arraylist } ```
1,520,525
I tried to answer the following question: Let $G$ be a finite Abelian group and $a,b \in G$. Let $$ \langle a,b \rangle = \{a^i b^j \mid i,j \in \mathbb Z \}$$ What can we say about $|\langle a,b \rangle|$ in terms of $|a|,|b|$? My answer: $|\langle a,b \rangle| = lcm(|a|,|b|)$. But it's not so clear to me how to prove this claim. For example, this subgroup of $G$ is not cyclic. If it was it would be obvious. But maybe my claim about the order is wrong. > > Is my claim wrong? If not, how to prove it rigorously? > > >
2015/11/09
[ "https://math.stackexchange.com/questions/1520525", "https://math.stackexchange.com", "https://math.stackexchange.com/users/180995/" ]
We can say $|\langle a,b\rangle|$ is a divisor of $|a|.|b|$ and divisible by $|a|$ and $|b|$. Consider the group $\mathbb{Z}\_4\times \mathbb{Z}\_2.$ Consider $a=(1,0)$ and $b=(1,1)$. Then $|\langle a,b\rangle|=|G|=8$ and is not the lcm of the orders of $a$ and $b$ (which are $4$ for both). We can say this: since $G$ is abelian, $\langle a,b\rangle=\langle a\rangle . \langle b\rangle$, and there is well known formula for order of such product: $$|\langle a,b\rangle| = |\langle a\rangle.\langle b\rangle|=\frac{|\langle a\rangle|.|\langle b\rangle|}{|\langle a\rangle \cap \langle b\rangle|}$$
377,443
I was adventuring, and reset my spawn by accident, by interacting with a bed in a random village. I never wrote down the coordinates or followed a compass so I’m completely lost. I worked really hard, and since I’m on a Nintendo switch it’s confusing with what everyone’s saying? How do I get back home? Is there any commands I can use? I even by accident changed the world spawn to a village?
2020/11/02
[ "https://gaming.stackexchange.com/questions/377443", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/260711/" ]
There are a few ways you may be able to get back home. The simplest is to craft a compass which will point you to the world spawn. It's unclear from your post whether you used commands to change the spawn point to a village, or used a bed, but assuming you just used a bed then the compass would point you towards 0,0 which may be enough to help you navigate home once you reach the center of the map. If you're willing to use commands then I'd recommend temporarily setting your game mode to creative and fly around until you're able to locate your base. In creative mode you'll be faster and able to fly over obstacles. You'll be able to find and identify landmarks more easily from a great altitude.
42,638,440
I am having a hard time getting javascript to work without reloading a page. I believe the problem has to do with turbo links. I am setting an onsubmit listener to a form like this ``` <%= form_for @cart, url: cart_path, html: {onsubmit: "addCart(event, #{@product.id})"} do |c| %> ``` I am then submitting the form via ajax like this ``` function addCart(event, id){ event.preventDefault(); var quantity = $("#"+id+'_product_quantity').val() $.post('/cart/add', { product_id: id, quantity: quantity }, function(data, status, xhr){ if(xhr.status !== 200){ alert("There was an error. Please try again") }else { $("#"+id+'_product_submit').val("Added"); } }) } ``` Everything works perfectly when I reload the page but when I go to the page via a link the javascript does not get called. The weird thing is that the `event.preventDefault()` is working. When I remove the javascript completely the form will submit like a normal html form. I am a pretty new to jquery and cannot figure out how to get the javascript to load.
2017/03/07
[ "https://Stackoverflow.com/questions/42638440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1599104/" ]
This could be a turbolinks issue. In your javascript file, surround your javascript code with ``` $(document).on('turbolinks:load', function() { // your code }); ```
30,191,851
I am trying to figure out if Python/Numpy is a viable alternative to develop my numerical software which is already available in C++. In order to get performance in Python/Numpy, one need to "vectorize" the code. But it turns out that as soon as I move away from very simple examples, I struggle to vectorize the code (I am not talking about SIMD instructions but "efficient Numpy code" without loops). Here is an algorithm that I want to get efficiently in Python/Numpy. 1. Create an numpy array containing: 1.0, 1.0 + 1/n, 1.0 + 2/n, ..., 2.0 2. For every u in the array, compute the root of x^2 - u, using a Newton method, stopping when |dx| <= 1.0e-7. Store the result in an array result. 3. Sum all the elements of the result array Here is the algorithm in Python I want to speed up ``` import numpy as np n = 1000000 data = np.arange(1.0, 2.0, 1.0 / n) def newton(u): x = 2.0 while True: f = x**2 - u df_dx = 2 * x dx = f / df_dx if (abs(dx) <= 1.0e-7): break x -= dx return x result = map(newton, data) print result[n - 1] ``` Here is a version of the algorithm in C++11 ``` #include <iostream> #include <vector> #include <cmath> int main (int argc, char const *argv[]) { auto n = std::size_t{100000000}; auto v = std::vector<double>(n + 1); for(size_t k = 0; k < v.size(); ++k) { v[k] = 1.0 + static_cast<double>(k) / n; } auto result = std::vector<double>(n + 1); for(size_t k = 0; k < v.size(); ++k) { auto x = double{2.0}; while(true) { auto f = double{x * x - v[k]}; auto df_dx = double{2 * x}; auto dx = double{f / df_dx}; if (std::abs(dx) <= 1.0e-7) { break; } x -= dx; } result[k] = x; } auto somme = double{0.0}; for(size_t k = 0; k < result.size(); ++k) { somme += result[k]; } std::cout << somme << std::endl; return 0; } ``` It takes 2.9 seconds to run on my machine. Is there a way to make a fast Python/Numpy algorithm that does the same thing (I am willing to get something that is less than 5 times slower). Thanks.
2015/05/12
[ "https://Stackoverflow.com/questions/30191851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3763545/" ]
You can do step 1. with numpy efficiently: ``` 1.0 + np.arange(n + 1) / n ``` however I think you would need the np.vectorize() method to feed back x into your calculated values and it's not an efficient function (basically a wrapper for a python loop). If you can use scipy then there are built in methods that might do what you want <http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.optimize.newton.html> EDIT: Having thought a bit more about this I followed up on @ev-br's point and tried some alternatives. The masking uses too much processing but the abs().max() is pretty fast so a compromise might be to "divide the problem into blocks" both in the 1st dimension of the array and in iteration direction. The following doesn't do too badly (< 20s) on my pretty low power laptop - certainly much faster than np.vectorize() or any of the scipy solving systems I could find. (If I set m too big it runs out of something (memory?) and grinds to a complete halt!) ``` n = 100000000 m = 5000000 block = 3 u = 1.0 + np.arange(n + 1) / n x = np.full(u.shape, 2.0) dx = np.ones(u.shape) for i in range(0, n, m): while np.abs(dx[i:i+m]).max() > 1.0e-7: for j in range(block): dx[i:i+m] = (x[i:i+m] ** 2 - u[i:i+m]) / (2 * x[i:i+m]) x[i:i+m] -= dx[i:i+m] ```
40,381,697
Suppose that we perform DFS on this graph by obeying the following rules: • Start from vertex 1. • At every vertex, process its out-neighbors in ascending order of id. • Whenever we need to restart, do it from the white vertex with the smallest id Show the resulting DFS forest. Furthermore, for every vertex, indicate its discovery time and finish time. also #/ = discovered and #/# = finished [![enter image description here](https://i.stack.imgur.com/sXPng.png)](https://i.stack.imgur.com/sXPng.png) dfs tree as follows: ``` 6 | 1--2--7--3--4--5--8 ``` the question ask me to show the resulting forest, yet I'm only producing one tree, what have i done wrong?
2016/11/02
[ "https://Stackoverflow.com/questions/40381697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6821180/" ]
You need an `except` clause to use `else`: > > The `try ... except` statement has an optional `else` clause, which, when > present, must **follow** all `except` clauses > [*Emphasis mine*] > > >