source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0045298587.txt" ]
Q: NSPredicate with regex capture always gets 0 results Hi to all overflowers, I'm scratching my head around putting a regular expression inside an NSPredicate. I would like to move all our thumbnails from Documents directory into Caches directory and catch em'all I've created this regex: _thumb(@[2-3]x)?\.jpg. Here on regex101.com you can see the above regex working with this test data: grwior_thumb.jpg <- match grwior.jpg [email protected] <- match vuoetrjrt.jpg hafiruwhf_thumb.jpg <- match [email protected] <- match [email protected] <- match hafiruwhf.jpg But when I put it in the code it's not matching anything: NSError *error = nil; NSFileManager *fileManager = [NSFileManager defaultManager]; // Find and move thumbs to the caches folder NSArray<NSString *> *mediaFilesArray = [fileManager contentsOfDirectoryAtPath:documentsPath error:&error]; NSString *regex = @"_thumb(@[2-3]x)?\\.jpg"; NSPredicate *thumbPredicate = [NSPredicate predicateWithFormat: @"SELF ENDSWITH %@", regex]; NSArray<NSString *> *thumbFileArray = [mediaFilesArray filteredArrayUsingPredicate:thumbPredicate]; thumbFileArray has always 0 elements... What am I doing wrong? A: Use MATCHES rather than ENDSWITH, as ENDSWITH does not treat the expression as a regular expression, but make sure you match all the chars from the start of the string, too, as MATCHES requires a full string match, so you need to somehow match the chars before the _. Use NSString *regex = @".*_thumb(@[23]x)?\\.jpg"; And then [NSPredicate predicateWithFormat: @"SELF MATCHES %@", regex] The .* will match any 0+ chars other than line break chars, as many as possible. Note that if you just want to match either 2 or 3, you might as well write [23], no need for a - range operator here. You may also replace (@[23]x)? with (?:@[23]x)?, i.e. change the capturing group to a non-capturing, since you do not seem to need the submatch to be accessible later. If you do, keep the optional capturing group.
[ "stackoverflow", "0001733229.txt" ]
Q: Iphone NSTimer Issue Hi I am new to objective c. I am trying to make an app for iphone. I have a button on my view, and the click on which the function playSound is called. This is working properly. It does plays the sound that i want it to. Now the problem is with the timer. I want the timer to start on the click on the same button, and the timer value will be displayed in a label. I am not very clear with the NSTimer itself either yet. I guess i am doing something wrong here. Can anyone help me with this. -(IBAction)playSound { //:(int)reps NSString *path = [[NSBundle mainBundle] pathForResource:@"chicken" ofType:@"wav"]; NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: path]; AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil]; theAudio.delegate = self; [theAudio play]; [self startTimer]; } - (void)startTimer { timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(targetMethod) userInfo:nil repeats:YES]; labelA.text = [NSString stringWithFormat:@"%d", timer]; } Using the code above, when i click on the button, it plays the sound, and then my app closes. Thanks Zeeshan A: This line: labelA.text = [NSString stringWithFormat:@"%d", timer]; makes absolutely no sense. The timer will call the method you specify as the selector in scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: when it fires so you have to implement that method and update your label there. The first line of startTimer is almost correct, but the selector must include a colon (because it denotes a method that takes one parameter): - (void)startTimer { timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES]; } Note that I named the selector timerFired: so we have to implement that method. If you want the timer to increment a counter, you will have to do that in this method, too: - (void)timerFired:(NSTimer *)timer { static int timerCounter = 0; timerCounter++; labelA.text = [NSString stringWithFormat:@"%d", timerCounter]; } Don't forget to invalidate the timer later when you no longer need it.
[ "apple.stackexchange", "0000117500.txt" ]
Q: Can I create a keyboard shortcut to lock a file in Finder? I'm constantly opening Info panes so that I can lock the currently selected files in Finder. Keeping the Info pane open is no longer good enough; it gets cumbersome to manage with multiple desktops and screens. Can I assign a keyboard shortcut to do this? A: Keyboard Maestro can do this with a macro such as this, which will run chflags uchg on every file in the current Finder selection:
[ "stackoverflow", "0021729752.txt" ]
Q: Android BLE BluetoothAdapter.LeScanCallback scanRecord length ambiguity I am using the example project from google (BluetoothLeGatt) to receive data from a BLE device and trying to read a specific byte within it's scanRecord obtained by the onLeScan method. My problem is that there is missmatch between the data I am observing in the network and what I see on logs. This is on Android 4.3 and using a Samsung Galaxy S4 to test it. To verify that the scanRecord logs are correct on Android, I am using TI's Packet Sniffer to observe the byte stream being broadcasted by the device, and here it is: That is 31 bytes of data being broadcasted by the device to the network, and there are no other working devices around. 02 01 1A 1A FF 4C 00 02 15 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0C C6 64 On the other hand, Android logs claim that the data being received has the length of 62 bytes and it matches the data until the 29th[0-indexed] byte, having 0s for the rest of the data. 02-12 15:34:09.548: D/DEBUG(26801): len: 62 data:02011a1aff4c000215000000000000000000000000000000000000000cc60000000000000000000000000000000000000000000000000000000000000000 And this is the code piece I used in order to obtain the logs within the LeScanCallback method: int len = scanRecord.length; String scanHex = bytesToHex(scanRecord); Log.d("DEBUG", "len: " + len + " data:" + scanHex); The method used to convert byte array to hex representation: private static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; int v; for ( int j = 0; j < bytes.length; j++ ) { v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } I used a few other example projects including Dave Smith's example and RadiusNetworks' Android iBeacon Library and I ended up with the same results. I can't possibly understand why do I receive 62 bytes of data when "Packet Sniffer" shows (and I also know) that it should be 31 bytes. This would not be my main concern if I was able to read the data in the last byte correctly (I get 00 instead of 64 from Android's BluetoothAdapter). But that is not the case either. I would appreciate any suggestions about what might potentially be the reason for this missmatch for both the data(last byte only) and the data size between what Android receives and what is actually on the network. A: Your transmission is malformed, containing 31 bytes of payload data (PDU length of 37) when its internal length fields indicate it should in total contain only 30 bytes (PDU length 36). Let's take a look at your data 02 01 1a This is a length (2) of type codes - 01 and 1a, and good so far 1a ff 4c ... Now we have a problem - the 1a is a length code for this field (manufacturer specific data), value of 26. Yet 27 bytes of data follow it in your case, instead of the proper 26 you have indicated you will provide. Now, if you have a properly formed packet, you will still get a larger buffer padded with meaningless (likely uninitialized) values following the proper content, but you can simply ignore that by parsing the buffer in accordance with the field-length values and ignoring anything not accounted for in the proclaimed lengths. But with your current malformed packet, the copying of packet data to the buffer stops at the proclaimed content size, and the unannounced extra byte never makes it into the buffer your program receives - so you see instead something random there, as with the rest of the unused length. Probably, when you made up your all-zeroes "region UUID" (might want to rethink that) you simply typed an extra byte...
[ "gamedev.stackexchange", "0000136902.txt" ]
Q: InputField text to string variables of a struct So, here's my issue. I have a class that contains a struct. This struct contains about 7 different string variables. I can set the values of these variables via a constructor that takes the struct variables and matches them to separate holder variables that have the actual values. However, I'm having issues, getting these values. I need to retrieve them from 7 different InputFields. I've tried to do this already. I ended up having some variables without values and some with the same value. How can I retrieve the text value of the different InputFields and pass them to the 7 different holder variables that will set the values of the struct variables? Below is the first method I tried, this only resulted in Age actually having a value (Note, I had debugging logs to check the assignments, I left out anything that was deemed unnecessary such as debugging logs and methods that are irrelevant to the problem.). I also set the Collect() method to a Button so when the button was pressed it would collect the data. I also tried replacing all the if statements with a switch case, that yielded the same result. As further try, I set up Get methods for all the types and attached them to the InputFields themselves to have them return field.text to the variables. This resulted in the aforementioned issue that some had no values and some had the same value as Age. using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; namespace Handlers { public class EventHandler : MonoBehaviour { InputField field; public static string f_name; public static string l_name; public static string p_age; public static string p_height; public static string p_weight; public static string p_hair; public static string p_eye; private void Awake() { field = FindObjectOfType<InputField>(); } public void Save() { if (File.Exists(Application.persistentDataPath + "/PlayerData.dat")) { } else { BinaryFormatter formatter = new BinaryFormatter(); FileStream fstream = File.Create(Application.persistentDataPath + "/PlayerData.dat"); Profile playerData = new Profile(); formatter.Serialize(fstream, playerData); fstream.Close(); } } public void Collect() { if (field.name == "FirstName") { f_name = field.text; } if (field.name == "LastName") { l_name = field.text; } if (field.name == "Age") { p_age = field.text; } if (field.name == "Height") { p_height = field.text; } if (field.name == "Weight") { p_weight = field.text; } if (field.name == "Hair_Color") { p_hair = field.text; } if (field.name == "Eye_Color") { p_eye = field.text; } } } [Serializable] class Profile { struct Player { public static string firstName; public static string lastName; public static string age; public static string height; public static string weight; public static string hair_color; public static string eye_color; } public Profile() { Player.firstName = EventHandler.f_name; Player.lastName = EventHandler.l_name; Player.age = EventHandler.p_age; Player.height = EventHandler.p_height; Player.weight = EventHandler.p_weight; Player.hair_color = EventHandler.p_hair; Player.eye_color = EventHandler.p_eye; } } } Here's an example of the second attempt (just an example as the entire method system is laid out above, and there is no need to repeat the same process over and over): public void getFN() { f_name = field.text; } public void Collect() { getFN(); } getFN() would be placed on the InputField and Collect() would be on the button so that when the button was clicked it would call each individual like style methods of getFN(). (getLN(), getAge(), etc.)This in return, at least in my mind, should have gotten the individual texts but it didn't. A: You have a single field that is the first InputField found by FindObjectOfType. Apparently in your case it was the age InputField and that's why that was the only variable that was set. Read your code for the Collect method, if the value of field or field.name is not changing behind your back (it shouldn't be), the code will only enter one of the if clauses (you may aswell have used a switch statement). Instead you should be using Object.FindObjectsOfType it should give an array of InputField. Then in the Collect method you would iterate over that array, and for each item check the name and set the appropiate variable. Something like this: public class EventHandler : MonoBehaviour { InputField[] fields; // ... private void Awake() { fields = FindObjectsOfType<InputField>(); } public void Collect() { foreach (var field in fields) { // your old code here // or use a switch statement } } }
[ "stackoverflow", "0007682756.txt" ]
Q: Is it possible to have two instances of GKSession on the same device when using Bluetooth? I am writing mutliplayer game and thought I would create two instances of GKSession. One session set to GKSessionModeServer and the other to GKSessionModeClient. The server is properly reported when I call peersWithConnectionState: on the client peer and each session has different peer ids. But when I try to connect to the server I receive the message session:connectionWithPeerFailed:withError: with the error description "Failed while pending outgoing invitation.". Using two GKSessions works when Wi-Fi is available. I am afraid that there is some limitation with Bluetooth that disallows this but I am not sure. I could rewrite the code to use a single GKSession on the server but I would rather not code special cases if I know that someone else got it working with two instances. If I turn off both Wi-Fi and Bluetooth i get the error "Network not available." which I don't get if either is turned on. This makes me believe it won't work when there is another iPhone is nearby either. A: I rewrote the code so I only create one GKSession on the hosting device and send data between the server and the local client directly without using the GKSession. I could finally test this with two devices and they properly connect to each other. So the lesson is to have only one GKSession on the host and it will work with Bluetooth as well as Wi-Fi.
[ "ell.stackexchange", "0000034140.txt" ]
Q: When to double the consonant before the suffix "-able" I'm not a native English speaker and I was wondering what is the rule that decides whether to write double letter before -able. In programming, we have abused the (English) language in new ways, needing to name attributes of objects, which are derived from verbs, e.g.: freezable pushable poppable stoppable interruptible mappable And so on. What is the rule? Does p always repeat while the other letters do not? :) A: If it's a short vowel sound and a single consonant, then you double the consonant to signify that the vowel sound is supposed to stay short: map > mappable hit > hittable cancel > cancellable Otherwise (if the vowel is already long, or if there is more than one consonant already) you don't need to double anything, because the vowel sound won't change anyway: junk > junkable excite > excitable quote > quotable If you don't double the consonant when you're supposed to, it will look like the vowel is supposed to be long: mapable = "may-puh-bull", not "map-uh-bull"
[ "stackoverflow", "0033393612.txt" ]
Q: QColorPicker with bright slider When I open a QColorPicker, I click in the coloor map in the top center, and select any color (lets say red) this color appears as black in the selected color bar bottom center. I have to move additionally the slider on the top right (see red arrow) to its top position, to approach the selected color. Why is this slider not initially set to the highest value, so I do not see black always? A: In the documentation it refers to the Standard Dialogs example: void Dialog::setColor() { const QColorDialog::ColorDialogOptions options = QFlag(colorDialogOptionsWidget->value()); const QColor color = QColorDialog::getColor(Qt::green, this, "Select Color", options); if (color.isValid()) { colorLabel->setText(color.name()); colorLabel->setPalette(QPalette(color)); colorLabel->setAutoFillBackground(true); } } Note in QColorDialog::getColor how it specifies an initial color. This should set the brightness bar for you. http://doc.qt.io/qt-5/qcolordialog.html#getColor QColor QColorDialog::getColor(const QColor & initial = Qt::white, QWidget * parent = 0, const QString & title = QString(), ColorDialogOptions options = 0) Hope that helps.
[ "bitcoin.stackexchange", "0000004848.txt" ]
Q: How can I assure my consumers they are actually paying the correct person? (prevent MITM attacks) There are many network level attacks that give someone Man in the Middle ability to replace my Bitcoin address with their own. Since there is no way to cancel a transaction, and the best practice is to generate a unique address per sender... How can I assure my consumers they are actually paying the correct person? I want to avoid the situation where a sender actually sent payment to a spoofer (which can't be canceled), and still have a dynamic address that people can send money to based on the sender. A similar question is here, but it doesn't focus on the safety and security of communicating the address from the (anonymous) merchant to the (anonymous) recipient. A: There is a lot of evidence that man in the middle attacks are common, and this is a good question for the Bitcoin community to review. When publishing the Bitcoin address on a web page, either you will be using a static address (one address for many senders) or generating a new address for that particular user. Regardless of the frequency of generating a new address, the bottom line is if you send your Bitcoin address over HTTP you need to secure the DNS infrastructure, SSL, and make sure your site is protected from HTTP based XSS, CSRF attacks. Here are some links to get you started with securing HTTP: Send all traffic over SSL, and set cookies to Secure and HTTP Only Use a well known Public Key vendor and ask visitors to run Convergence.IO to prevent a stolen/hacked key from being used. Disable compression on the webserver or load balancer and configure SSL correctly Scan the client's machine for old plugins and ask them to upgrade Have a dedicated domain for purchases with only one "dot" in the name Ultra-modern DNS Security Use DNSSec with a trusted root domain that supports DNSSEC at the root (.com, .org, etc) Use TLSA RFC6698 to self-publish SSL keys into DNS For ToR clients Have a .onion address (users at Exit nodes can modify your HTTP/S session) Detect that the user is using ToR and redirect them to your .onion address
[ "stackoverflow", "0031752703.txt" ]
Q: numpy - meshgrid for multiple dimensions numpy has a beautiful function which generate multidimensional grid. It is easy to work with it when number of dimension is low and is known in advance, but what to do when number of dimension is only known at time of execution or simply big and it takes too long to type. I guess I am looking for something like import numpy as np x = np.meshgrid(y) where y is an array of arrays of evaluation points, for example y = [array([-3., 0., 3.]) array([-3., 0., 3.]) array([-3., 0., 3.])] Suggestions? A: Use the *-operator (i.e. the unpacking operator): x = np.meshgrid(*y) See https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists
[ "stackoverflow", "0061818046.txt" ]
Q: how to create a FIELD in marklogic using ml-gradle? I have create a Field in marklogic through Admin console and I want to configure the same setting through ml-gradle to avoid manually creation from Admin console. Is there any way to configure through ml-gradle? A: I was looking for an example in the ml-gradle project, but couldn't find one. There is an easy way to discover how to provide it though. There is documentation for the Management REST api that already provides a lot of detail, but an example usually works better. Now that you created a field with Admin ui manually, you can discover the JSON syntax for it easily using the Management REST api, and copy/paste that into your ml-gradle database config. You can use the database properties REST call to discover this: https://docs.marklogic.com/REST/GET/manage/v2/databases/[id-or-name]/properties This basically comes down to something like: http://localhost:8002/manage/v2/databases/my-database/properties?format=json You can also just navigate to http://localhost:8002/manage/v2/ with your browser, and navigate the HTML pages to your database. Find the properties, and add a format=json request parameter to the url to get them printed as JSON. You can use a JS or JSON formatter to pretty-print it for easier reading. In case you are speaking of a regular field with paths, here is an example: "field": [ { "field-name": "dateTime", "field-path": [ { "path": "dateTime", "weight": 1 }, { "path": "dateTimes", "weight": 1 } ] } ] The range index that can optionally go with this, is defined separately. HTH!
[ "stackoverflow", "0004574013.txt" ]
Q: struggling with timer in android All I am looking to do is run some function 5 seconds after the app starts. However i keep getting a "force close" after 5 sec. Is timerTask even the correct function to be using in a situation like this? How about if i want to press a button later in the program, and have an event occur 5 seconds after user presses the button? package com.timertest; import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class timerTest extends Activity { Timer timer = new Timer(); TextView test; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); test = (TextView)findViewById(R.id.test); timer.schedule(task, 5000); } TimerTask task = new TimerTask() { @Override public void run() { test.setText("task function run"); } }; } A: A TimerTask will run on a background thread but you're trying to change UI. You want to run your operation on the UI thread instead. Android traditionally uses messages posted to a Handler to do this. A Handler will not create a new thread, when used as shown below it will simply attach to the same message queue that your app uses to process other incoming UI events. public class Test extends Activity { private final Handler mHandler = new Handler(); private TextView mTest; private Runnable mTask = new Runnable() { public void run() { mTest.setText("task function run"); } }; /** Called when the activity is first created. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mTest = (TextView) findViewById(R.id.test); mHandler.postDelayed(mTask, 5000); } @Override protected void onDestroy() { super.onDestroy(); mHandler.removeCallbacks(mTask); } } A: If you want to execute some code after 5 secs try the following... new CountDownTimer(5000,5000) { @Override public void onTick(long millisUntilFinished) { } @Override public void onFinish() { // DO YOUR OPERATION } }.start();
[ "stackoverflow", "0009397116.txt" ]
Q: bash: grep only lines with certain criteria I am trying to grep out the lines in a file where the third field matches certain criteria. I tried using grep but had no luck in filtering out by a field in the file. I have a file full of records like this: 12794357382;0;219;215 12795287063;0;220;215 12795432063;0;215;220 I need to grep only the lines where the third field is equal to 215 (in this case, only the third line) Thanks a lot in advance for your help! A: Put down the hammer. $ awk -F ";" '$3 == 215 { print $0 }' <<< $'12794357382;0;219;215\n12795287063;0;220;215\n12795432063;0;215;220' 12795432063;0;215;220
[ "stackoverflow", "0056746874.txt" ]
Q: Error of TfidfVectorizer on cleaned text dataset I am trying to vectorize a sentiment data set. It has review text and sentimentlabel given. When I try to vectorize the data set It gives an error called 'LazyCorpusLoader' object is not iterable The reviews were cleaned as follows. remove html tags tokenize text to remove punctuations remove stop words POS tagging lemmatize text After these my dataframe reviewdataset_df has following columns: reviews_clean->cleaned review text SENTIMENT-> a sentiment label as positive or negative then I split the data set using below code, #splitting data set into training and testing X_train,X_test,Y_train,Y_test =train_test_split(reviewDataset_Df.head(10000).review_clean,reviewDataset_Df.head(10000).SENTIMENT,test_size=0.20,random_state=0,shuffle=True) print('Training data count:'+str(len(X_train))) print('Test data count:'+str(len(X_test))) That worked well. Then I use vectorizer using following code. #vectorizer tfidf=TfidfVectorizer(sublinear_tf=True,min_df=3,stop_words=english,norm='l2',encoding='utf-8',ngram_range=(1,3)) print("rr") train_features=tfidf.fit_transform(X_train) test_features=tfidf.transform(X_test) train_labels=Y_train test_labels=Y_test This gives an error as return frozenset(stop) TypeError: 'LazyCorpusLoader' object is not iterable I searched and tried on some solutions which didn't worked. How to overcome this error. I need to vectorize the data set to train for a recommendation system. note: I searched through internet and read similar question in stackoverflow but couldn't find a proper answer. A: Without a proper error trace we can only guess. Since the error involves stop my guess is that your variable english - that isn't in the code you shared at all - is inappropriately set up, and not a set of words. You probably meant to use stop_words="english" instead.
[ "stackoverflow", "0017627112.txt" ]
Q: How to use PushSharp with simple project I get the feeling that this question is either too basic or too complex to be covered by any documentation on pushSharp. But how exactly do I incorporate it into my project. I am used to Java/php, etc and have never really looked at C# before. I have been reading whatever I can find but am not really sure what I should be looking at. I have an ashx file that is handling my ajax calls and is currently using the example code from http://www.codeproject.com/Tips/434338/Android-GCM-Push-Notification to send push notifications. I would really like to incorporate pushSharp so that I can do this for ios and windows as well but am feeling a bit lost as to how to do this. With Java I would compile the library as a jar and include that in a project. Would I do the same here by compiling the whole pushsharp project as a dll or each folder (android/ios etc) or have I got this completely wrong? Any suggestions, or pointing me to the relevant tutorials/documentation would be greatly appreciated. A: Thanks @k3b did some research on this without considering pushsharp as being any different and got it resolved. thanks.
[ "puzzling.stackexchange", "0000027619.txt" ]
Q: Why Would One Willingly While Life Away? Nobody likes me. Nobody ever comes to see me just for fun. I'm nobody's hobby. People are always trying to avoid me. Yet every day people come to me. They spend precious time with me Though they could usually avoid me. After all, you usually know where I am. The more who come to me The worse I get. But don't think I'm evil. I'm legal in all 50 states of the union (though I only exist with any frequency in some of them). I'm not addictive, not in the least. If you must know... I'm slow as anything Yet Often the fastest way to get anywhere is through me. Who am I? A: You are ... a traffic jam. Nobody likes me. Nobody ever comes to see me just for fun. I'm nobody's hobby. People are always trying to avoid me. Nobody likes to be in a traffic jam, it's not fun or a hobby, everyone tries to avoid it. Yet every day people come to me. They spend precious time with me Though they could usually avoid me. After all, you usually know where I am. Some people are in a traffic jam everyday, on their way to work. They know where it is, but usually can't avoid it. The more who come to me The worse I get. The more people are there the worse is the jam. But don't think I'm evil. I'm legal in all 50 states of the union (though I only exist with any frequency in some of them). I'm not addictive, not in the least. It's obviously neither evil nor illegal, and definitely not addictive. If you must know... As suggested by Nyk 232, even though traffic jams are slow, using the highway is often faster despite the jam, than trying to go around the jam. A: You are most definitely the bane of my morning and evening, you are: traffic. Nobody likes me. Nobody ever comes to see me just for fun. I'm nobody's hobby. People are always trying to avoid me. While the great (enter your nationality here) road can be enjoyed when it is wide and open, when it is full of cars, it is not fun. You can take a leisurely drive at night, a fun road trip, etc, but no one goes to the roads eager to sit at lights or behind other cars. In fact, people often turn away from backups if they have the chance, and new routing systems can actively subvert heavy traffic. Yet every day people come to me. They spend precious time with me Though they could usually avoid me. After all, you usually know where I am. Every day, people (like me!) commute to work on the road, where they spend far too much time to get where they are going. Other forms of transit could help you avoid road traffic, in fact, you could avoid it almost anywhere-anywhere that isn't a road. But don't think I'm evil. I'm legal in all 50 states of the union (though I only exist with any frequency in some of them). I'm not addictive, not in the least. Traffic occurs on roads, because roads are in every state, as are the citizens who need to get to work. In Montana, not so much, in LA, New York, Chicago- ouch. You don't get hooked on traffic, you want to get away from it. Now... The hint makes it look like Irishpanda's answer is closer. It seems we were at work on our keyboards at roughly the same time. Whatever the answer really is, please Don't make me drive home tonight... A: You are bureaucracy Nobody likes or enjoys bureaucracy and everyone tries to avoid, yet we have to spend a lot of time to go through bureaucracy. You could easily avoid by efficient employees. It is slow as hell but if you need anything you have to go through it.
[ "stackoverflow", "0047447008.txt" ]
Q: setJMenuBar not working After extensive googling I've found that this issue is generally case-specific. I've tried many of the solutions found and none of them have worked for me, so I felt it was appropriate to create a post on it. I'm using setJMenuBar and the bar is never appearing, here is my code: NOTE: I believe the cause is that I update the frame, however the solution is still unknown. import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Toolkit; import java.awt.image.BufferStrategy; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; @SuppressWarnings("serial") public class testclass extends JFrame { public int updateRate = 60; public int screenWidth; public int screenHeight; public boolean finishedInitialPaint; private Graphics bufferGraphics; private BufferStrategy bufferStrategy; public int gridSize = 10; JMenuBar engineBar; JMenu fileMenu, editMenu, createMenu, toolsMenu, panelsMenu; JMenuItem fileNewScene, fileOpenScene, fileSaveScene, fileExit; JMenuItem editPreferences, editEngine; JMenuItem createEmpty, createStandard; JMenuItem toolsDebug; JMenuItem panelView2D, panelEditor2D, panelHierarchy, panelInspector, panelExplorer; public static void main(String[] args) { testclass testClassv = new testclass (); } public testclass () { Start (); while(true) { Update (); ClearBackBuffer (); try { Thread.sleep(1000 / updateRate); } catch (InterruptedException e) { } } } private void Start () { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); screenWidth = screenSize.width; screenHeight = screenSize.height; CreateDefaultEngineMenu (); setTitle("Test Window"); setSize(Math.round(screenWidth * 0.99f), Math.round(screenHeight * 0.9f)); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); } private void CreateDefaultEngineMenu () { engineBar = new JMenuBar (); /* * Building initial menus */ // Build the file menu fileMenu = new JMenu("File"); engineBar.add(fileMenu); // Build the edit menu editMenu = new JMenu("Edit"); engineBar.add(editMenu); // Build the create menu createMenu = new JMenu("Create"); engineBar.add(createMenu); // Build the tools menu toolsMenu = new JMenu("Tools"); engineBar.add(toolsMenu); // Build the panels menu panelsMenu = new JMenu("Panels"); engineBar.add(panelsMenu); /* * Building menu options */ // File menu options fileNewScene = new JMenuItem("New Scene"); fileMenu.add(fileNewScene); fileOpenScene = new JMenuItem("Open Scene"); fileMenu.add(fileOpenScene); fileSaveScene = new JMenuItem("Save Scene"); fileMenu.add(fileSaveScene); fileExit = new JMenuItem("Exit"); fileMenu.add(fileExit); // Edit menu options editPreferences = new JMenuItem ("Preferences"); editMenu.add(editPreferences); editEngine = new JMenuItem ("Engine Settings"); editMenu.add(editEngine); // Create menu options createEmpty = new JMenuItem("New Empty GameObject"); createMenu.add(createEmpty); createStandard = new JMenuItem("Standard GameObjects"); createMenu.add(createStandard); // Tools menu options toolsDebug = new JMenuItem ("Debug"); toolsMenu.add(toolsDebug); // Panels menu options panelView2D = new JMenuItem("View 2D"); panelsMenu.add(panelView2D); panelEditor2D = new JMenuItem("Editor 2D"); panelsMenu.add(panelEditor2D); panelHierarchy = new JMenuItem("Hierarchy"); panelsMenu.add(panelHierarchy); panelInspector = new JMenuItem("Inspector"); panelsMenu.add(panelInspector); panelExplorer = new JMenuItem("Explorer"); panelsMenu.add(panelExplorer); // Set the frame to use the bar setJMenuBar(engineBar); } private void Update () { //sceneObjects.activeObjects.get(0).transform.position.x += 0.1f; initialize (); ClearBackBuffer (); repaint (); DrawBackBufferToScreen (); } private void initialize () { if(bufferStrategy == null) { this.createBufferStrategy(2); bufferStrategy = this.getBufferStrategy(); bufferGraphics = bufferStrategy.getDrawGraphics(); } } public void paint(Graphics g) { // Something to go here } private void ClearBackBuffer () { bufferGraphics = bufferStrategy.getDrawGraphics(); try { bufferGraphics.clearRect(0, 0, this.getSize().width, this.getSize().height); Graphics2D g2d = (Graphics2D)bufferGraphics; paint2D(g2d); } catch (Exception e) { //Debug.EngineLogError("Engine", "Failed to clear rect for frame buffer (Failed to draw frame) - Exception"); } finally { bufferGraphics.dispose(); } } private void DrawBackBufferToScreen () { bufferStrategy.show(); Toolkit.getDefaultToolkit().sync(); } private void paint2D (Graphics2D g2d) { // Multi-Used Variables int canvasWidth = Math.round(screenWidth / 2); int canvasHeight = Math.round(screenHeight / 2); // Draw panel borders // View2D g2d.setColor(Color.black); g2d.drawRect((canvasWidth) - (canvasWidth / 2) - 1, canvasHeight - (Math.round(canvasHeight / 1.35f)) - 1, canvasWidth + 1, canvasHeight + 1); } } Any and all relevant answers are greatly appreciated. EDIT: Fixed code to be able to be tested raw A: There's a lot wrong in your code, but the biggest problem is here: public void paint(Graphics g) { // Something to go here } By overriding paint, you're preventing the JFrame from doing its necessary painting of itself, its borders, and relevant to your problem, its child components. So your menu never draws! You should never draw directly in the JFrame, but if you absolutely must (and you don't), at least call the super's painting method: public void paint(Graphics g) { super.paint(g); // Something to go here } Better still-- never override paint but instead draw inside a JPanel's paintComponent method (still calling the super's paintComponent method within) and display that JPanel within your JFrame. Key links: Lesson: Performing Custom Painting: introductory tutorial to Swing graphics Painting in AWT and Swing: advanced tutorial on Swing graphics I'm not sure what the rest of your code is trying to do, but you've got big threading issues, other painting issues,... do read the tutorials to avoid guessing. Also you will want to learn and use Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.
[ "unix.stackexchange", "0000436703.txt" ]
Q: Want to Zip files based on modified date A file (Paths.dat) which contains multiple Paths where it needs to find files which are 15 days old and zip it in same folder with modified date. Paths.dat :- contains multiple paths in File system ( with delimiter ' | ' ) /docusr1/user01 | /docusr2/user02 | /home/user01 ex:- /docusr1/user01 -rwxrwxrwx. 1 docusr2 docusr2 0 Mar 30 10:52 vinay.txt -rw-rw-r--. 1 docusr2 docusr2 0 Mar 30 10:52 sathish.txt -rw-rw-r--. 1 docusr2 docusr2 625 Apr 2 10:57 demo1.xml -rw-rw-r--. 1 docusr2 docusr2 4430 Apr 2 11:09 sample.xml -rw-rw-r--. 1 docusr2 docusr2 48 Apr 2 14:04 20180402140454.log -rw-rw-r--. 1 docusr2 docusr2 48 Apr 2 14:39 20180402143917.log -rw-rw-r--. 1 docusr2 docusr2 39 Apr 2 14:41 20180402144159.log -rw-rw-r--. 1 docusr2 docusr2 84 Apr 2 14:46 20180402144651.log -rw-rw-r--. 1 docusr2 docusr2 279 Apr 2 14:48 archive.sh -rw-rw-r--. 1 docusr2 docusr2 84 Apr 2 14:48 20180402144814.log -rw-rw-r--. 1 docusr2 docusr2 1228 Apr 5 10:10 real.xml search for files which are 15 days old and need to zip the files with modified date as zip file name(archive file) o/p expected:- 20170330.zip -> it should contain all file which are modified on 2017-03-30 20170402.zip 20170405.zip A: find . -maxdepth 1 -mtime +15 -type f -printf "%TY%Tm%Td %p\n" | while read date name ; do zip $date $name; done File's last modification time in Ymd format To do it for all underneath directories, there are different ways to do it, giving below a few, make sure to use absolute path with find, for example I use "/home/user" find /home/user -type d -print0 | while read -d '' -r dir; do cd "$dir" && pwd && find . -maxdepth 1 -mtime +15 -type f -printf "%TY%Tm%Td %p\n" | while read date name ; do zip $date $name; done; done or find /home/user -type d -print0 | xargs -0 -I {} sh -c 'cd '\"{}\"' && pwd && find . -maxdepth 1 -mtime +15 -type f -printf "%TY%Tm%Td %p\n" | while read date name ; do zip $date $name; done'
[ "softwareengineering.meta.stackexchange", "0000006280.txt" ]
Q: Design choice of existing code; Programmers.SE or CodeReview.SE? I want to ask a question about an abstract factory that I have implemented but am in doubt of the best design choice. My question is about should I have a design that requires addition of new make methods to the factory interface when extension is called upon, or should I use a generic approach that eliminates changes to the factory interface but requires an (ugly but runtime verified) down cast. Now, should I ask this question on Programmers.SE or on CodeReview.SE? A: if you post the Code on Code Review (following the guidelines for CodeReview questions) we will be more than happy to help you optimize for performance, or readability, or other things like that. Program design sounds more like a question for Programmers than it does for code review. Code Review likes to hammer out syntax and ways to make your design work. if it's a bad design then the code will probably look like a blob. deciding what the design should be and what design is going to work best sounds like Programmers to me, but if you have working code that you want reviewed, Code Review might (small chance) point you toward a new design choice, just depends on the code and functionality you are looking for. if you do post on CR and/or Programmers please comment on my answer with the links. Here is the link to on-topic questions on Code Review and this does say Best practices and design pattern usage AND However, if your question is not about a particular piece of code and instead is a generally applicable question about … Best practices in general (that is, it's okay to ask "Does this code follow common best practices?", but not "What is the best practice regarding X?") A: Your question sounds more like a Code Review question than a Programmers one, but you could try posting it in both sites. However you should take care to target each site's audience: Code Review only accepts questions that include working code, reviewing code isn't exactly a pleasant experience if the damn thing doesn't compile. If your code is relatively small and its working, you should go ahead and post there. If it isn't working, then perhaps you should start by posting a question on Stack Overflow. On Programmers, code isn't necessary. If you think a small piece of code would help clarify your question, then by all means include it, but ideally the question should stand without the code. What we are more interested in hearing is what your specific problem is, and what design choices you've already considered. If you've already dismissed an approach or two, please tell us why.
[ "stackoverflow", "0030340760.txt" ]
Q: Mean, Median, and Mode - Newb - Java We had a lab in Comsci I couldn't figure out. I did a lot of research on this site and others for help but they were over my head. What threw me off were the arrays. Anyway, thanks in advance. I already got my grade, just want to know how to do this :D PS: I got mean, I just couldn't find the even numbered median and by mode I just gave up. import java.util.Arrays; import java.util.Random; public class TextLab06st { public static void main(String args[]) { System.out.println("\nTextLab06\n"); System.out.print("Enter the quantity of random numbers ===>> "); int listSize = Expo.enterInt(); System.out.println(); Statistics intList = new Statistics(listSize); intList.randomize(); intList.computeMean(); intList.computeMedian(); intList.computeMode(); intList.displayStats(); System.out.println(); } } class Statistics { private int list[]; // the actual array of integers private int size; // user-entered number of integers in the array private double mean; private double median; private int mode; public Statistics(int s) { size = s; list = new int[size]; mean = median = mode = 0; } public void randomize() { Random rand = new Random(12345); for (int k = 0; k < size; k++) list[k] = rand.nextInt(31) + 1; // range of 1..31 } public void computeMean() { double total=0; for (int f = 0; f < size; f++) { total = total + list[f]; } mean = total / size; } public void computeMedian() { int total2 = 0; Arrays.sort(list); if (size / 2 == 1) { // total2 = } else { total2 = size / 2; median = list[total2]; } } public void computeMode() { // precondition: The list array has exactly 1 mode. } public void displayStats() { System.out.println(Arrays.toString(list)); System.out.println(); System.out.println("Mean: " + mean); System.out.println("Median: " + median); System.out.println("Mode: " + mode); } } A: Here are two implementations for your median() and mode() methods: public void computeMedian() { Arrays.sort(list); if ( (list.size & 1) == 0 ) { // even: take the average of the two middle elements median = (list[(size/2)-1] + list[(size/2)]) / 2; } else { // odd: take the middle element median = list[size/2]; } } public void computeMode() { // precondition: The list array has exactly 1 mode. Map<Integer, Integer> values = new HashMap<Integer, Integer>(); for (int i=0; i < list.size; ++i) { if (values.get(list[i]) == null) { values.put(list[i], 1); } else { values.put(list[i], values.get(list[i])+1); } } int greatestTotal = 0; // iterate over the Map and find element with greatest occurrence Iterator it = values.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); if (pair.getValue() > greatestTotal) { mode = pair.getKey(); greatestTotal = pair.getValue(); } it.remove(); } }
[ "stackoverflow", "0033699902.txt" ]
Q: QueueManager.Disconnect() and QueueManager.Close() Difference? I have a code which disconnects queuemanger when the connection is broken or exception is thrown like below if (queueManagerreceive != null) if (queueManagerreceive.IsConnected) { if (queuereceive != null) { queuereceive.Close(); } queueManagerreceive.Disconnect(); } So i have issue with the above code when i have a 'MQRC_RECONNECT_TIMED_OUT' exception then when it does a queuemanager.Disconnect() it throws an exception "MQRC_CONNECTION_BROKEN" and obviously which breaks the code as an exception is thrown so when i use queuemanager.Close() there was no exception thrown and the service was stable. What is the difference? what should i use to drop and recreate a new connection? Please help. A: The MQQueueManager.Disconnect() closes all queues/topics/processed opened and closes the connection to queue manager. Calling Disconnect() on an already disconnected connection helps in freeing any resources allocated internally. MQQueueManager.Close method is actually an inherited method of it's base class and this method closes any internal objects the MQQueueManager has allocated. . But you must always call Disconnect instead of Close because the Disconnect method closes the connection to queue manager while Close does not. After MQRC_RECONNECT_TIMED_OUT error you have to create a new connection again using new MQQueueManager constructor. You are getting a MQRC_RECONNECT_TIMED_OUT error which means that an established connection was broken (for whatever reason) and the MQ client attempted to reconnect for 30 minutes but still could not establish connection. You have to understand the reasons for this: 1) Is your queue manager down for that long? 2) Is there a network issue which is preventing connection to queue manager? 3) If your are using a multi-instance queue manager, why application is not getting connected to stand-by instance?
[ "stackoverflow", "0033480499.txt" ]
Q: (s)applying subset (i.e. `[`) to various list structures I've got a function from which I'd like to be able to return a quite relaxed set of structures: str1 <- list( list( key = 123, data = "test" ), list( key = 987, data = "test" ) ) str2 <- list( c(key = 123, data = "test"), c(key = 987, data = "test") ) str3 <- list( key = 123, data = "test" ) str4 <- c(key = 123, data = "test") From these return values I'd like to be able to capture all key-values in a concise manner. My attempt at a catch all solution was this: sapply(str1, `[`, "key") However, it only works for the nested structures(str1 & str2). The others return NA. I'm curious as to why I can do this: str4["key"] # 123 sapply(c(key = 1), `+`, 1) # 2 ...but not this? sapply(c(key = 123), `[`, "key") # NA I'm not as interested in a workaround as I am to understand where I'm going wrong here. A: To understand the difference between your two last lines of code, you can do: > sapply(c(key = 123), function(i) browser()) Called from: FUN(X[[i]], ...) Browse[1]> i [1] 123 Browse[1]> i+1 [1] 124 Browse[1]> i['key'] [1] NA You are basically try to extract the value by name on an ...unamed vector. To solve your problem, a possible approach would be: foo = function(str, key) {l=unlist(str); l[names(l) %in% key]} #> foo(str1,'key') # key key #"123" "987" #> foo(str2,'key') # key key #"123" "987" #> foo(str3,'key') # key #"123" #> foo(str4,'key') # key #"123"
[ "stackoverflow", "0058896701.txt" ]
Q: How to call Stream Builder after pressing a material button? Context: I am facing an issue that for some reason when I click on the button the logic inside the Stream Builder is not being called. He makes the api call to authenticate the user and enters the stream: userBloc.authenticationUserStream but not the builder What have I tried : Tried to see if there was some kind of return issue on the UserBloc class, but I think everything is correct. I have some other widget that does not involve clicking buttons (I can the api from the constructor) and it works fine so I think the problem can be on the clicking state. This is my code from the UI: class _LoginScreenState extends State<LoginScreen> { @override void initState() { super.initState(); userBloc = UserBloc(); } } final loginButton = Material( elevation: 5.0, borderRadius: BorderRadius.circular(30.0), color: Color(0xff01A0C7), child: MaterialButton( minWidth: MediaQuery.of(context).size.width, padding: EdgeInsets.fromLTRB(20, 15, 20, 15), onPressed: () { userBloc.authenticateUser(emailController.text.toString(), passwordController.text.toString()); StreamBuilder<ApiResponse<LoginResponse>>( // does not enter here stream: userBloc.authenticationUserStream, builder: (context, snapshot) { if (snapshot.hasData) { switch (snapshot.data.status) { case Status.LOADING: return Loading( loadingMessage: snapshot.data.message, ); break; case Status.COMPLETED: Navigator.push( context, MaterialPageRoute(builder: (context) => MovieScreen()), ); break; case Status.ERROR: Scaffold.of(context).showSnackBar(SnackBar( content: Text("Error"), )); break; } } return Container(); }); }, child: Text("Login", textAlign: TextAlign.center), ), ); This is my code for the UserBloc class UserBloc { UserRepository userRepository; StreamController streamController; StreamSink<ApiResponse<LoginResponse>> get authenticationUserSink => streamController.sink; Stream<ApiResponse<LoginResponse>> get authenticationUserStream => streamController.stream; UserBloc() { streamController = StreamController<ApiResponse<LoginResponse>>(); userRepository = UserRepository(); } authenticateUser(String email, String password) async { authenticationUserSink.add(ApiResponse.loading("Logging")); try { // success LoginResponse loginResponse = await userRepository.authenticateUser(email, password); authenticationUserSink.add(ApiResponse.completed(loginResponse)); } catch (e) { // error authenticationUserSink.add(ApiResponse.error(e.toString())); } } dispose() { streamController?.close(); } } Can someone give me a help understanding how to call this kind of stuff after pressing a button. I can share my user repository code if necessary, thanks in advance for the help. A: You can reference this https://medium.com/flutter-community/handling-network-calls-like-a-pro-in-flutter-31bd30c86be1 You need to move out StreamBuilder<ApiResponse<LoginResponse>> to a body/UI child not in a onPressed() demo code snippet @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Movie Mania')), backgroundColor: Colors.black54, body: RefreshIndicator( onRefresh: () => _bloc.fetchMovieList(), child: StreamBuilder<ApiResponse<List<Movie>>>( stream: _bloc.movieListStream, builder: (context, snapshot) { if (snapshot.hasData) { switch (snapshot.data.status) { case Status.LOADING: return Loading( loadingMessage: snapshot.data.message, ); break; case Status.COMPLETED: return MovieList(movieList: snapshot.data.data); break; case Status.ERROR: return Error( errorMessage: snapshot.data.message, onRetryPressed: () => _bloc.fetchMovieList(), ); break; } } return Container(); }, ), ), ); }
[ "stackoverflow", "0017528858.txt" ]
Q: Simple Image Processing for Android I need a simple image processing library that i can do auto local thresholding on a bitmap on Android . I searched over the net but i cannot find a simple library that can do that. Can someone suggest a library or a method for it? Thanks A: The library jhlabs have a lot of image filters that you can use. It is easy to add as a library to your project and easy to use. Take a look at https://code.google.com/p/android-jhlabs/ and see if some of the filters is the one that you want.
[ "stackoverflow", "0028824414.txt" ]
Q: How to understand the function definitions of curry/uncurry A definition about curry/uncurry(schönfinkel/unschönfinkel) from http://www.seas.upenn.edu/~cis194/lectures/02-lists.html, schönfinkel :: ((a,b) -> c) -> a -> b -> c schönfinkel f x y = f (x,y) unschönfinkel :: (a -> b -> c) -> (a,b) -> c unschönfinkel f (x,y) = f x y but I think these function definitions above should be: schönfinkel :: ((a,b) -> c) -> a -> b -> c schönfinkel f (x,y) = f x y -- schönfinkel(curry) converts an uncurried function -- (f (x,y), its type signature is (a,b) -> c) -- to a curried function -- (f x y, its type signature is a -> b -> c) unschönfinkel :: (a -> b -> c) -> (a,b) -> c unschönfinkel f x y = f (x,y) -- unschönfinkel(uncurry) converts a curried function -- (f x y , its type signature is a -> b -> c) -- to an uncurried function -- (f (x,y), its type signature is (a,b) -> c) Please could someone give me a simple explanation ? A: You probably misread / misunderstood the initial code, a proper indentation is probably sufficient to get it right: schönfinkel :: ((a,b) -> c) -> a -> b -> c schönfinkel f x y = f (x,y) unschönfinkel :: (a -> b -> c) -> (a,b) -> c unschönfinkel f (x,y) = f x y Now, let's open ghci and tried a few things: >>> let schönfinkel f x y = f (x,y) >>> let toBeCurried (x,y) = x ++ y >>> :t toBeCurried toBeCurried :: ([a], [a]) -> [a] >>> :t schönfinkel toBeCurried schönfinkel toBeCurried :: [a] -> [a] -> [a] Look at the unformal definition you gave and you'll see that it matches the behaviour of schönfinkel.
[ "stackoverflow", "0043802682.txt" ]
Q: because of 'multiple' attribute background color gets changed to grey .selected_aq{ background:#47D6EB !important; color : #fff; } <select id="abc" multiple="multiple"> <option value="Customer 1" class="selected_aq">Customer 1</option> <option value="Customer 1" class="selected_aq">Customer 1</option> </select > for (x=0;x<list.options.length;x++){ if (list.options[x].selected){ $(list.options[x]).addClass('selected_aq'); } Because of 'multiple' attribute background color gets changed to grey but only for last selected 'option'. A: You can use CSS only select[multiple]:focus option:checked { background: #47D6EB linear-gradient(0deg, #47D6EB 0%, #47D6EB 100%); color : #fff; } <select id="abc" multiple="multiple"> <option value="Customer 1" >Customer 1</option> <option value="Customer 2" >Customer 2</option> <option value="Customer 3" >Customer 3</option> <option value="Customer 4" >Customer 4</option> <option value="Customer 5" >Customer 5</option> <option value="Customer 6" >Customer 6</option> </select > Try to select multiple options by holding Ctrl button.
[ "tex.stackexchange", "0000345542.txt" ]
Q: Does anyone know of a package for typesetting Timelord? You know, Doctor Who. I figure if we've got Tengwar and Sindarin, we've probably got Timelord (specifically Circular Gallifreyan). Anyone? A: No, for the simple reason that the sentence structure is not linear. In general (and this is also how TeX works), fonts contain a bunch of symbols that are extracted from the font and placed in a line to form a sentence. The only adjustments made are horizontal kerning - moving the symbols left or right, depending on neighbouring symbols. Circular Gallifreyan is, well, circular and therefore not linear. Adjustments are made horizontally and vertically, together with rotation. The following is a word - a circle of symbols: The following is a sentence (a circle of circular symbols): The symbol/word/sentence structure of this "language" is more of an art form than what we commonly see in the recti-linear world of writing. You are most likely going to be forced to draw these words/sentences using a graphics package.
[ "stackoverflow", "0010450094.txt" ]
Q: How to map a SolrNet Query result to a class? I am trying to query Solr using the SolrNet client. I can index documents and search for them with the Solr web admin with out error. When I try to query using the same class I indexed the documents with I get an error like the following on every field. Error: Could not convert value 'System.Collections.ArrayList' to property 'Title' of document type Search.WebService.Handler.Document Why is Solr trying to map an arraylist to each field? Here are the details of my setup, the schema is based on the example schema. My Schema: <field name="ReferenceId" type="identifier" indexed="true" stored="true" required="true"/> <field name="Title" type="text_general" indexed="true" stored="true"/> <field name="Revision" type="identifier" indexed="true" stored="true"/> <field name="Author" type="text_general" indexed="true" stored="true"/> <field name="Filename" type="text_general" indexed="true" stored="true"/> My Document class: class Document { [SolrField("ReferenceId")] public string ReferenceId { get; set; } [SolrField("Title")] public string Title { get; set; } [SolrField("Revision")] public string Revision { get; set; } [SolrField("Author")] public string Author { get; set; } [SolrField("Filename")] public string Filename { get; set; } } An example query: string queryString = String.Format("Title :\"{0}\"", titleSearchTerm); SolrQuery query = new SolrQuery(queryString); SolrQueryResults<Document> results = index.Query(query); A: Added the attribute multiValued="false" to each of the fields. More details on multiValued fields is found in the documentation.
[ "superuser", "0000269276.txt" ]
Q: Remote desktop crashes when connecting with printing local resource enabled (XP to Server 2008) A client uses Remote Desktop (MSTSC) to connect to her office. Recently her network admin apparently did some sort of update on the server (Windows Server 2008), and after these every time she connects with local printing enabled MSTSC crashes. If printing is disabled then it works fine. Her machine is running XP Media Center Edition SP3 (32 bit). I've updated Remote Desktop to the latest version to no avail. I've also uninstalled/reinstalled her printer drivers, also with no effect. Ideas? A: Figured it out! It was actually the Dell AIO 926 printer driver that was causing the problem. I was so focused on the Brother MFC 8860DN (because that's her primary printer, and the one she uses for work) that I hadn't even considered the fact that ALL printers were being redirected. The solution was actually pretty simple. While there I ran Windows Update on her machine and WU detected (somehow) that there was a problem with the Dell driver. I let it fix that, as well as run the other updates and voilà! it works now.
[ "stackoverflow", "0060418947.txt" ]
Q: Why are new lines added to THREE.Line not rendered, despite setting verticesNeedUpdate? When I push points to my geometry after (!) renderer.render() was called, the new lines are not displayed. I am setting geometry.verticesNeedUpdate to true, as suggested. Minimal example: https://jsfiddle.net/y2374dr1/9/ Note: Remove the first renderer.render() call to see all lines. Is this a bug in THREE.js, or am I doing something wrong? A: This is not a three.js bug. First of all, you are using an outdated version of three.js (R60) which is several years old. I've updated the fiddle so it uses the latest version R113 and the latest supported API. Besides, it's important to know that THREE.Geometry is somewhat deprecated. It is internally converted to THREE.BufferGeometry. During this process, vertex buffer of a certain size are allocated. Since these buffers are fixed size (it's not possible to resize them), you see no effect of your vertex additions. You have to create a new geometry instead, so the renderer internally creates a new instance of THREE.BufferGeometry. For beginners, this is quite confusing. Hence, I recommend to completely avoid THREE.Geometry and focus on THREE.BufferGeometry instead. The restriction of using fixed-sized buffers becomes more obvious then. When working with THREE.BufferGeometry, you have to create sufficiently sized buffers in the first place that are large enough to hold all upcoming vertex additions. Otherwise you have to delete and recreate buffers which is however an expensive operation. https://jsfiddle.net/nqveab8y/1/ three.js R113
[ "stackoverflow", "0012623577.txt" ]
Q: Converting area within a polygon of coordinates to metres given a set of coordinates lat <- c(47.2325618, 47.2328269, 47.2330041, 47.2330481, 47.2330914, 47.2331172, 47.2331291, 47.2331499) lon <- c(11.3707441, 11.3707791, 11.3708087, 11.3708031, 11.3707818, 11.3707337, 11.3706588, 11.370284) coords <- cbind(lon,lat) I want to calculate the area of the polygon. I use the function areapl() from package splancs: library(splancs) areapl(coords) # [1] 1.4768e-07 this leaves me with a dimension in degrees squared (?). so my question is: how do i convert this into metres/kilometres? thanks a lot in advance. A: Either convert to a cartesian grid system (eg a UTM zone) using spTransform in the sp package, or try areaPolygon in the geosphere package. > areaPolygon(coords) [1] 7688.568
[ "bitcoin.stackexchange", "0000003458.txt" ]
Q: I sent money to a bitcoin wallet from Blizzcoin and there's nothing there? Using blizzcoin.com I sent bitcoins to the address I have for the bitcoin wallet client, and it took forever to sync the blocks. Once it had finished I was expecting to see the money there, but saw nothing. Can anyone explain or tell me how to resolve this? A: According to blockchain.info the coins weren't sent yet. Here's a post from another blizzcoin customer saying that it took 2 days for his purchased coins to be sent: apparently because I Manually transferred money to them instead of ordering through their web interface, it wasn't an instant transfer of bitcoins. Could that be your problem too? How long has it been since you sent the money to them?
[ "stackoverflow", "0010731723.txt" ]
Q: How to add Distinct in Hibernate Criteria In my database I have a Test table, with columns: testName, testType there are 2 different tests with the same type I.e "SUN", so I want only one of them for which I use Distinct in my hibernate / criteria as below, but it still giving me both the types with the same name as "sun". Criteria crit = session.createCriteria(Test.class); final ResultTransformer trans = new DistinctRootEntityResultTransformer(); crit.setResultTransformer(trans); List rsList = trans.transformList(crit.list()); Any idea what could be the reason, or any other way of filtering duplicates. A: Use Projections.distinct. Criteria crit = session.createCriteria(Test.class).setProjection( Projections.distinct(Projections.projectionList() .add(Projections.property("type"), "type") ) .setResultTransformer(Transformers.aliasToBean(YourBean.class)); List lst = crit.list(); where YourBean.class has a property "type". The returned list will be List<YourBean>. A: Try to use : cr.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); It work perfectly for me A: I finally have found out to get values of other columns: Criteria criteria = session.createCriteria(Test.class); ProjectionList projectionList = Projections.projectionList(); ProjectionList projectionList2 = Projections.projectionList(); projectionList2.add(Projections.distinct(projectionList.add(Projections.property("distinctColumn"), "distinctColumn"))); projectionList2.add(Projections.property("col1"), "col1"); projectionList2.add(Projections.property("col2"), "col2"); criteria.setProjection(projectionList2); criteria.setResultTransformer(Transformers.aliasToBean(Test.class)); List list = criteria.list();
[ "stackoverflow", "0048681010.txt" ]
Q: Jenkins pipeline CPS issue with parallel jobs I am trying to create a simple job that runs on all online nodes that have a certain label. I can get the node names and would expect the below code to work. However I get the below exception. def newJob(x) { return { node(x) { bat "dir" } } } def jobs = [:] def lgroups = Jenkins.instance.getLabel('win7') for (g in lgroups) { for (node in g.getNodes()) { def nodeName = node.getNodeName() if (Jenkins.instance.getNode(nodeName).toComputer().isOnline()) { jobs["${nodeName}_BS"] = newJob(nodeName) } } } parallel jobs The job is configured to run without the sandbox enabled. Exception: an exception which occurred: in field com.cloudbees.groovy.cps.impl.BlockScopeEnv.locals in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@90def78 in field com.cloudbees.groovy.cps.impl.ProxyEnv.parent in object com.cloudbees.groovy.cps.impl.LoopBlockScopeEnv@32864b7a in field com.cloudbees.groovy.cps.impl.ProxyEnv.parent in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@5a2e37ea in field com.cloudbees.groovy.cps.impl.ProxyEnv.parent in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@fb260f7 in field com.cloudbees.groovy.cps.impl.ProxyEnv.parent in object com.cloudbees.groovy.cps.impl.LoopBlockScopeEnv@fa692c0 in field com.cloudbees.groovy.cps.impl.ProxyEnv.parent in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@15ffb7f2 in field com.cloudbees.groovy.cps.impl.ProxyEnv.parent in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@60b6bff4 in field com.cloudbees.groovy.cps.impl.ProxyEnv.parent in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@4e29d7b4 in field com.cloudbees.groovy.cps.impl.CallEnv.caller in object com.cloudbees.groovy.cps.impl.FunctionCallEnv@1fa0ac69 in field com.cloudbees.groovy.cps.impl.ProxyEnv.parent in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@1efd7828 in field com.cloudbees.groovy.cps.impl.ProxyEnv.parent in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@157768c5 in field com.cloudbees.groovy.cps.impl.CpsClosureDef.capture in object com.cloudbees.groovy.cps.impl.CpsClosureDef@6c20bc58 in field com.cloudbees.groovy.cps.impl.CpsClosure.def in object org.jenkinsci.plugins.workflow.cps.CpsClosure2@757fe932 in field com.cloudbees.groovy.cps.impl.BlockScopeEnv.locals in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@31a3450e in field com.cloudbees.groovy.cps.impl.CpsClosureDef.capture in object com.cloudbees.groovy.cps.impl.CpsClosureDef@4d20e584 in field com.cloudbees.groovy.cps.impl.CpsClosure.def in object org.jenkinsci.plugins.workflow.cps.CpsClosure2@59bab622 in field org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.closures in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@5fa55074 in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@5fa55074 Caused: java.io.NotSerializableException: hudson.model.labels.LabelAtom A: You have to extract the non-serializable code into a method annotated with @NonCPS, maybe similar to the following: @NonCPS def getParallel() { def jobs = [:] def lgroups = Jenkins.instance.getLabel('win7') for (g in lgroups) { for (node in g.getNodes()) { def nodeName = node.getNodeName() if (Jenkins.instance.getNode(nodeName).toComputer().isOnline()) { jobs["${nodeName}_BS"] = newJob(nodeName) } } } return jobs } parallel getParallel()
[ "stackoverflow", "0014554176.txt" ]
Q: Prolog - Why is 'end-of-file' written to the output text file? I'm working on a programming assignment and I was wondering if somebody could help me out with this issue. This assignment says to write a program in Prolog which takes the text from an input text file and write it to an output text file. In order to get the location of the text files, the user needs to be prompted to write the path of the text files. I have figured out how to do it, but I have one small issue that is really annoying. Here is my code: main:- %Ask the user for the input text file and then open the file write('Please enter the filename you would like to read from:'), nl, read(X), open(X,read,In), %Ask the user for the output text file and then open the file write('Please enter the filename you would to write to:'), nl, read(Y), open(Y,write,Out), %Read in characters from the input text file and then put them %on the output text file. tell(Out), repeat, get_char(In,T), write(T), T == end_of_file, !, close(In), told, close(Out). Let's say the text file that is going to be read says "this is a test". My issue is if I use the program to save this text and write it to another text file, it will write "this is a testend_of_file" instead. I realize that this is happening because the loop isn't being terminated at the right time, but I'm not sure how to go about fixing the loop so "end_of_file" doesn't get accidentally written to the text file as well. Any help would be much appreciated. I feel like I've tried everything. A: You first do write(T), and after that your testing for T == end_of_file, so no surprise end_of_file will be written. Try ( T == end_of_file -> ! ; write(T), fail ), What Prolog system are you using, BTW?
[ "stackoverflow", "0005523012.txt" ]
Q: Android composite primary key? Can anyone tell me how to declare a composite primary key in Android 1.6 which includes an autoincrement _id column? I'm not sure of the syntax. I've ended up just enforcing it in Java when I try to add values (where registrationNumber + date has to be unique in the table): Cursor fuelUpsCursor = getFuelUps(registrationNumber, date); if(!fuelUpsCursor.moveToNext()) { //add registrationNumber and date } I don't really need the _id column but it can make life tricky if tables don't have one. Cheers, Barry A: Your question does not make much sense. Your subject line asks for a "composite foreign key", your first sentence asks for a "composite primary key" with an AUTOINCREMENT that your sample code then ignores. I am going to interpret your question this way: You want an _ID INTEGER PRIMARY KEY AUTOINCREMENT column in your table to be able to use Android's CursorAdapter, but you want to also make sure that the combination of two other columns is unique. In that case, I think that you want to use a UNIQUE constraint: Multiple Unique Columns in SQLite SQLite table constraint - unique on multiple columns http://sqlite.org/lang_createtable.html
[ "stackoverflow", "0027209771.txt" ]
Q: Game Center not asking my TestFlight users to log in? In my app, I use the following code in the view controller in my sprite kit project to authenticate a player using GameKit: -(void)autheticateLocalPlayer{ GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer]; localPlayer.authenticateHandler = ^(UIViewController *viewController, NSError *error){ if (error != nil){ NSLog(@"%@", [error localizedDescription]); } if (viewController != nil){ [self presentViewController:viewController animated:YES completion:nil]; }else{ if ([GKLocalPlayer localPlayer].authenticated){ _gameCenterEnabled = YES; [[GKLocalPlayer localPlayer]loadDefaultLeaderboardIdentifierWithCompletionHandler:^(NSString *leaderboardIdentifier, NSError *error) { if (error != nil){ NSLog(@"%@", [error localizedDescription]); } else{ _leaderboardIdentifier = leaderboardIdentifier; } }]; } else{ _gameCenterEnabled = NO; NSLog(@"game center not available"); } } }; } It works fine on my phone, but after building an Ad-Hoc build with a provisioning profile including a friend's phone to see how it would work, they were not asked to log in when they opened the app, whereas my phone was (and all simulator phones were). On top of that, attempting to open the leaderboards would simply show a message "game center is not available, user is not logged in" or something like that. I went to this friend's phone's Game Center settings, and verified that sandbox mode was ON. After that, I manually logged in to a Sandbox tester account I made in iTunes connect, and once I opened my app again, (on their phone), it displayed the "welcome back" message. However, the leaderboards showed "no scores", when I believe that my score should be on there. My questions are: 1. Why were they not asked to log in? Is it a problem with my code, or is that how it's supposed to work when beta testing with sandbox mode on? 2. Why doesn't it show the other scores? My leaderboard is in iTunes connect, and the leaderboard name is properly displayed in the app, but no score are visible. Thanks for any help! A: Apparently, it takes about 10 hours before the other user's scores will be updated. Today, all of my test users' scores are on game center. Would be nice if this was made more obvious, so developers didn't think Game Center wasn't working.
[ "stackoverflow", "0017464553.txt" ]
Q: Ember create object I'm trying to create a new record in ember. In the past I used to manually create each of the model's fields on the object controller, but that really seems superfluous. With the code in this fiddle, as I start typing information into the text boxes, I get an error Assertion failed: Cannot delegate set('name', t) to the 'content' property of object proxy <App.StockNewController:ember258>: its 'content' is undefined A: Basically what you are missing are some variables defined in your App.StockNewController. Because when the bindings defined in your templates kick in and there are no such properties defined on your backing controller you get the error. I've changed it a bit and now the error is gone. App.StockNewController = Em.ObjectController.extend({ name: '', code: '', description: '' }); See here a working jsbin. Let me know if it helps.
[ "stackoverflow", "0051075201.txt" ]
Q: How to override default login mechanism of Laravel 5.6? I want the user to login only if status field in users table is set to 1. If it is 0 then simply return error stating user account is not active. So after creating the status field in the table, where can I make the check that the user'status is 1 then only login otherwise throw error. I tried to find where the default auth check is made but cannot find it anywhere. A: You need to simply override credentials() which is defined in AuthenticatesUsers.php. the default login method use AuthenticatesUsers trait. so go login controller and overwrite like this. protected function credentials(Request $request) { return [ 'email'=>$request->{$this->username()}, 'password'=>$request->password, 'status'=>1 ]; } Note: don't forget to import Request class and don't change anything whatever defined in vendor directory.
[ "stackoverflow", "0007666669.txt" ]
Q: Running Wordpress PHP from command line - specifically for Plesk scheduled task I need to develop a script using Wordpress PHP that will run with the Plesk Scheduled task. I've seen a few topics with this on stackoverflow and the web, but I can't seem to get the wordpress or script to work. I'm fairly new to this, so I need a good step-by-step guide. Basically, I want to run a PHP Script using the command line. (what's the command to do this?... I had "php -q /path/to/file.php" but not sure if that's it.) Secondly, with this script, I need to be able to use Wordpress commands such as query_posts, add_post_meta, get_post_meta, etc. I've seen elsewhere that I need the following at the top of the php file: #!/usr/bin/php <?php $_SERVER = array( "HTTP_HOST" => "http://example.com", "SERVER_NAME" => "http://example.com", "REQUEST_URI" => "/", "REQUEST_METHOD" => "GET" ); require_once('/wp-load.php'); require_once('/wp-blog-header.php'); Is that it, or do I need more? I assume I can place the PHP script in my root Wordpress directory and run it from there? I've got the entire PHP part working, and can run it if I include it in a Wordpress page and simply load that page. So I know the Wordpress part works. I just need that other portion to get it working with the scheduled tasks. Thanks in advance for all your help. A: Yes that's it. Actually, all you need to do is set HOST_NAME.
[ "stackoverflow", "0043373088.txt" ]
Q: Trying to copy HTML from one file to another using batch I'm manipulating some HTML via Batch but even though I've setlocal enableDelayedExpansion, it still won't transfer tags. This is my script: @echo off setlocal enableDelayedExpansion del output.html for /f "delims=" %%x in (file.html) do call :putLineInHTMLFile %%x :putLineInHTMLFile echo !%*!>> output.html file.html contains: <tag 1> <tag 2> After running the script, output.html contains: ECHO is off. P.S.: I would like to keep using do call so I'm interested in an answer that makes this work without removing the do call statement. A: @echo off setlocal enableDelayedExpansion del output.html for /f "delims=" %%x in (file.html) do call :putLineInHTMLFile "%%x" goto :EOF :putLineInHTMLFile set "line=%~1" echo !line!>> output.html
[ "stackoverflow", "0034554711.txt" ]
Q: g++: error: `pkg-config: No such file or directory I installed cygwin and followed this for installation http://cs.calvin.edu/curriculum/cs/112/resources/installingEclipse/cygwin/ then I run this on my cmd cd opencv cd sources cd samples cd cpp g++ -ggdb `pkg-config --cflags --libs opencv` facedetect.cpp -o facedetect It resulted into this g++: error: `pkg-config: No such file or directory g++: error: opencv`: No such file or directory g++: error: unrecognized command line option '--cflags' g++: error: unrecognized command line option '--libs' what I'm trying to do is to run facedetect.cpp in opencv to test my classifier any help to fix this issue or provide alternative approach is appreciated A: Install the packages pkg-config and libopencv-devel http://cygwin.com/packages/x86_64/pkg-config http://cygwin.com/packages/x86_64/libopencv-devel
[ "stackoverflow", "0029428459.txt" ]
Q: PHP: How can I remove from String the last word? How can I remove, with PHP, the last word from a String? For example the string "Hi, I'm Gian Marco" would become "Hi, I'm Gian". A: try with this : $txt = "Hi, I'm Gian Marco"; $str= preg_replace('/\W\w+\s*(\W*)$/', '$1', $txt); echo $str out put Hi, I'm Gian A: check this <?php $str ='"Hi, I\'m Gian Marco" will be "Hi, I\'m Gian"'; $words = explode( " ", $str ); array_splice( $words, -1 ); echo implode( " ", $words ); ?> source : Remove last two words from a string A: You can do it with regular expression. (see answer of Ahmed Ziani.) However, in PHP you can also do it using some inbuilt function. see the code below $text = "Hi, I'm Gian Marco"; $last_space_position = strrpos($text, ' '); $text = substr($text, 0, $last_space_position); echo $text;
[ "stackoverflow", "0053575679.txt" ]
Q: Hubzilla won't start: /store/[data]/smarty3 must be writable by webserver I followed the manual instructions to set up Hubzilla here. https://project.hubzilla.org/help/en/admin/administrator_guide#Manual_Installation I ran the command chmod -R 777 store But it still gives me this error when I view the page in the browser. ERROR: folder /var/www/html//store/[data]/smarty3 must be writable by webserver. I tried chown -R apache:apache store and chmod o-w -R store to tighten it up, but that didn't work so I just ran chmod -R 777 store again. Here are the permissions. [root@fsphub html]# ls -ld store drwxrwxrwx. 3 apache apache 20 Dec 1 22:08 store [root@fsphub html]# ls -lR store store: total 0 drwxrwxrwx. 3 apache apache 21 Dec 1 22:08 [data] store/[data]: total 0 drwxrwxrwx. 2 apache apache 6 Dec 1 22:08 smarty3 store/[data]/smarty3: total 0 Apache is running as apache. [root@fsphub html]# ps -ef | grep http root 16997 1 0 21:47 ? 00:00:00 /usr/sbin/httpd -DFOREGROUND apache 16998 16997 0 21:47 ? 00:00:00 /usr/sbin/httpd -DFOREGROUND What could be wrong? PHP 7.2.12 A: It was due to SELinux being on. https://wiki.centos.org/HowTos/SELinux # sestatus SELinux status: enabled Current mode: enforcing # sealert -a /var/log/audit/audit.log SELinux is preventing /usr/sbin/httpd from write access on the directory smarty3. ***** Plugin httpd_write_content (92.2 confidence) suggests *************** If you want to allow httpd to have write access on the smarty3 directory Then you need to change the label on 'smarty3' Do # semanage fcontext -a -t httpd_sys_rw_content_t 'smarty3' # restorecon -v 'smarty3' Raw Audit Messages type=AVC msg=audit(1543792561.65:60034): avc: denied { write } for pid=21907 comm="httpd" name="smarty3" dev="vda1" ino=621797 scontext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:httpd_sys_content_t:s0 tclass=dir # ls -lZd store/\[data\]/smarty3/ drwxrwxrwx. apache apache unconfined_u:object_r:httpd_sys_content_t:s0 store/[data]/smarty3/ So I ran # semanage fcontext -a -t httpd_sys_rw_content_t store/\[data\]/smarty3/ # restorecon -v store/\[data\]/smarty3/ But that just didn't work so I used setenforce 0 To change the mode to permissive.
[ "stackoverflow", "0052936019.txt" ]
Q: angular 6 patchValue updates the value but not when I submit? I am updating the value of a field on blur making it into a currency value on blur. When I type my value and leave the formcontrol the update on blur works and makes the value (20.00) to ($20.00) or (20.05060) to ($20.00) however when I click the generate form button it console.logs the value as it was before my patchValue. How can I fix that? export class InvoicesComponent implements OnInit { invoiceGeneratorForm: FormGroup; subtotalSub: Observable<any>; subTotal = 0; itemPriceCurrent: Observable<any>; prices = []; constructor(public fb: FormBuilder, private currencyPipe: CurrencyPipe) {} ngOnInit() { this.invoiceGeneratorForm = this.fb.group({ firstName: [""], lastName: [""], email: [""], itemsArray: this.fb.array([this.getItems()]), tax: [""], subTotal: [{ value: this.subTotal, disabled: true }], invoiceTotal: [""] }); } private pushCurrentPrice(index: number){ const control = <FormArray>this.invoiceGeneratorForm.controls["itemsArray"]; const currentControl= control.at(index)['controls']['itemPrice']; const typeCheck = parseFloat(currentControl.value)||0; const subFormatted = this.currencyPipe.transform( typeCheck, "USD", "symbol-narrow", "1.2-2" ); currentControl.patchValue(subFormatted,{onlySelf: true, emitEvent: false}); console.log(currentControl); } private getItems() { return this.fb.group({ itemName: ["", Validators.required], itemPrice: [ "", Validators.compose([ Validators.required ]) ] }); } private addItemRow() { const control = <FormArray>this.invoiceGeneratorForm.controls["itemsArray"]; control.push(this.getItems()); } private deleteItemRow(index: number) { const control = <FormArray>this.invoiceGeneratorForm.controls["itemsArray"]; control.removeAt(index++); } onGenerateForm() { console.log(this.invoiceGeneratorForm.value); } } A: This is expected. You are using pipes which modifies your data on client side and do not change the actual value of the data. Pipes are used to process the data. Please read https://angular.io/guide/pipes which might give you more details.
[ "stackoverflow", "0036616583.txt" ]
Q: Best practices to use Fog::Logger What are the best practices to use Fog::Logger. Fog provides 3 types of logging: debug deprecation warning module Fog class Logger @channels = { :deprecation => ::STDERR, :warning => ::STDERR } @channels[:debug] = ::STDERR if ENV["DEBUG"] def self.[](channel) @channels[channel] end def self.[]=(channel, value) @channels[channel] = value end def self.debug(message) write(:debug, "[light_black][fog][DEBUG] #{message}[/]\n") end def self.deprecation(message) write(:deprecation, "[yellow][fog][DEPRECATION] #{message}[/]\n") end def self.warning(message) write(:warning, "[yellow][fog][WARNING] #{message}[/]\n") end def self.write(key, value) channel = @channels[key] if channel message = if channel.tty? value.gsub(Fog::Formatador::PARSE_REGEX) { "\e[#{Fog::Formatador::STYLES[$1.to_sym]}m" }.gsub(Fog::Formatador::INDENT_REGEX, "") else value.gsub(Fog::Formatador::PARSE_REGEX, "").gsub(Fog::Formatador::INDENT_REGEX, "") end channel.write(message) end nil end end end If we use debug logging then it is only visible when debug mode is on. What is the best way to use it, please give some examples if possible. A: The logger is intended for messages from fog to end users, rather than for direct use from end-users. I would suggest the levels would be used something like this: debug - Not really used much, more for usage during development than something I would expect to be used for messaging to end-users. deprecation - Any time we have changed a behavior, but left a backwards-compatible adapter we try also to have a deprecation warning explaining and hopefully driving users to update. warning - This makes sense for anything related to usage that the user should be made aware of in addition to what is happening (ie if something changed on the provider side or the provider returns a warning, but it isn't broken enough to actually raise an error). Hope that helps, but certainly happy to discuss further as needed.
[ "wordpress.stackexchange", "0000089933.txt" ]
Q: How to validate inputs with filter in register_setting callback I now have this function that works well : function wpPartValidate_settings( $input ) { if ( check_admin_referer( 'wpPart_nonce_field', 'wpPart_nonce_verify_adm' ) ) { // Create our array for storing the validated options $output = array(); foreach( $input as $key => $value ) { // Check to see if the current option has a value. If so, process it. if( isset( $input[$key] ) ) { // Strip all HTML and PHP tags and properly handle quoted strings $output[$key] = strip_tags( stripslashes( $input[ $key ] ) ); } // end if } // end foreach } // end if // Return the array processing any additional functions filtered by this action return apply_filters( 'wpPartValidate_settings', $output, $input ); } I wonder how to implement filters into that function. The goal is to inform the administrator that one input has not been correctly filled (with a correct email, url, numbers, date...) A: First of all I would recommend you to rename your function to wpPartSanitize_settings, because this function doesn't validate anything. As it doesn't validate anything, then you aren't able to "inform" administrator that one input is invalid. Nevertheless, to create your hook for wpPartValidate_settings filter, just do it like this: add_filter( 'wpPartValidate_settings', 'wpse8170_sanitize_settings', 10, 2 ); function wpse8170_sanitize_settings( $output, $input ) { // ... return $output; }
[ "raspberrypi.stackexchange", "0000024213.txt" ]
Q: Car computer how to connect to car battery and also not drain battery when the car is switched off I am doing research on creating a car computer with raspberry pi (so I have all the basics down before I start this project) and I am looking on a way to switch the whole device automatically whenever the car is switched off. I have found Android ROMs that do this exact thing but I want to build it from scratch with Raspberry pi. As my car battery is not huge, the device cannot and must not run when the car is switched off unless I explicitly turn it on. What I want is functionality similar to how the car radio turns off at the exact moment the car is turned off so it does not drain my car battery. I do not know if this should be done in code or with specific hardware. I am just looking for guidelines on how to proceed. I am also looking for ways on how to connect to the car battery and use that as my power source. A: I have not measured it myself, but this person claims the pi draws about 110 mA after shutdown, i.e., when the OS has halted and just the red PWR led glows. Figures regarding the number of amp-hours in a car battery seem to vary quite widely; if we assume 50, then that's 50 / .11 ~= 454.5 hours such a battery should last with an inoperative pi attached. Of course, if you want to use the battery to start your car, you probably don't to go even half that far (also, draining a lead acid battery excessively shortens its lifespan). The important part here is that the OS be shutdown. Otherwise, even when idle the pi draws at least 300 mA. There are people who sell power off switches for the pi; these use a GPIO pin to signal the system to shutdown, wait for confirmation, then cut the power. Note this also requires a bit of software. If you search online you'll find such switches (they are built specifically for the pi) for ~$15-20. I do not know if this should be done in code There has to be some kind of hardware involved to accomplish this. If you wire the pi so the power is linked to the ignition state (on or off), you still need to signal the pi first so it can cleanly shutdown (if you don't do this, you will eventually run into problems). If you leave the power on, you need hardware to do the same thing, plus cut the power (as per the switches above). I am also looking for ways on how to connect to the car battery and use that as my power source You need a 12v - 5v DC converter, I guess. These are cheap and widely available.
[ "stackoverflow", "0013184661.txt" ]
Q: What category / filter structure is this using? Nested Interval? You can see on their category links that it's quite obvious that the only portion of their URL that matters is the small hash near the end of the URL itself. For instance, Water Heaters category found under Heating/Cooling is: http://www.lowes.com/Heating-Cooling/Water-Heaters/_/N-1z11ong/pl?Ns=p_product_avg_rating|1 and Water Heaters category found under Plumbing is: http://www.lowes.com/Plumbing/Water-Heaters/_/N-1z11qhp/pl?Ns=p_product_avg_rating|1 That being said, obviously their structure could be a number of different things... But the only thing I can think is it's a hex string that gets decoded into a number and denominator but I can't figure it out... apparently it's important to them to obfuscate this for some reason? Any ideas? UPDATE At first I was thinking it was some sort of base16 / hex conversion of a standard number / denom or something? or the ID of a node and it's adjacency? Does anyone have enough experience with this to assist? A: They are building on top of IBM WebSphere Commerce. Nothing fancy going on here, though. The alpha-numeric identifiers N-xxxxxxx are simple node identifiers that do not capture hierarchical structure in themselves; the structure (parent nodes and direct child nodes) is coded inside the node data itself, and there are tell-tale signs to that effect (see below.) They have no need for nested intervals (sets), their user interface does not expose more than one level at a time during normal navigation. Take Lowe's. If you look inside the cookies (WC_xxx) as well as see where they serve some of their contents from (.../wcsstore/B2BDirectStorefrontAssetStore/...) you know they're running on WebSphere Commerce. On their listing pages, everything leading up to /_/ is there for SEO purposes. The alpha-numeric identifier is fixed-length, base-36 (although as filters are applied additional Zxxxx groups are tacked on -- but everything that follows a capital Z simply records the filtering state.) Let's say you then wrote a little script to inventory all 3600-or-so categories Lowe's currently has on their site. You'd get something like this: N-1z0y28t /Closet-Organization/Wood-Closet-Systems/Wood-Closet-Kits N-1z0y28u /Closet-Organization/Wood-Closet-Systems/Wood-Closet-Towers N-1z0y28v /Closet-Organization/Wood-Closet-Systems/Wood-Closet-Shelves N-1z0y28w /Closet-Organization/Wood-Closet-Systems/Wood-Closet-Hardware N-1z0y28x /Closet-Organization/Wood-Closet-Systems/Wood-Closet-Accessories N-1z0y28y /Closet-Organization/Wood-Closet-Systems/Wood-Closet-Pedestal-Bases N-1z0y28z /Cleaning-Organization/Closet-Organization/Wood-Closet-Systems N-1z0y294 /Lighting-Ceiling-Fans/Chandeliers-Pendant-Lighting/Mix-Match-Mini-Pendant-Shades N-1z0y295 /Lighting-Ceiling-Fans/Chandeliers-Pendant-Lighting/Mix-Match-Mini-Pendant-Light-Fixtures N-1z0y296 /Lighting-Ceiling-Fans/Chandeliers-Pendant-Lighting/Chandeliers ... N-1z13dp5 /Plumbing/Plumbing-Supply-Repair N-1z13dr7 /Plumbing N-1z13dsg /Lawn-Care-Landscaping/Drainage N-1z13dw5 /Lawn-Care-Landscaping N-1z13e72 /Tools N-1z13e9g /Cleaning-Organization/Hooks-Racks N-1z13eab /Cleaning-Organization/Shelves-Shelving/Laminate-Closet-Shelves-Organizers N-1z13eag /Cleaning-Organization/Shelves-Shelving/Shelves N-1z13eak /Cleaning-Organization/Shelves-Shelving/Shelving-Hardware N-1z13eam /Cleaning-Organization/Shelves-Shelving/Wall-Mounted-Shelving N-1z13eao /Cleaning-Organization/Shelves-Shelving N-1z13eb3 /Cleaning-Organization/Baskets-Storage-Containers N-1z13eb4 /Cleaning-Organization N-1z13eb9 /Outdoor-Living-Recreation/Bird-Care N-1z13ehd /Outdoor-Living N-1z13ehn /Appliances/Air-Purifiers-Accessories/Air-Purifiers N-1z13eho /Appliances/Air-Purifiers-Accessories/Air-Purifier-Filters N-1z13ehp /Appliances/Air-Purifiers-Accessories N-1z13ejb /Appliances/Humidifiers-Dehumidifiers/Humidifier-Filters N-1z13ejc /Appliances/Humidifiers-Dehumidifiers/Dehumidifiers N-1z13ejd /Appliances/Humidifiers-Dehumidifiers/Humidifiers N-1z13eje /Appliances/Humidifiers-Dehumidifiers N-1z13elr /Appliances N-1z13eny /Windows-Doors Notice how entries are for the most part sequential (it's a sequential identifier, not a hash), mostly though not always grouped together (the identifier reflects chronology not structure, it captures insertion sequence, which happened in single or multiple batches, sometimes years and thousands of identifiers apart, at the other end of the database), and notice how "parent" nodes always come after their children, sometimes after holes. These are all tell-tale signs that, as categories are added and/or removed, new versions of their corresponding parent nodes are rewritten and the old, superseded or removed versions are ultimately deleted. If you think there's more you need to know you may want to further inquire with WebSphere Commerce experts as to what exactly Lowe's might be using specifically for its N-xxxxxxx catalogue (though I suspect that whatever it is is 90%+ custom.) FWIW I believe Home Depot (who also appear to be using WebSphere) upgraded to version 7 earlier this year. UPDATE Joshua mentioned Endeca, and it is indeed Endeca (those N-xxxxxxx identifiers) that is being used behind Websphere in this case (though I believe since the acquisition of Endeca Oracle is pushing SUN^H^H^Htheir own Java EE "Endeca Server" platform.) So not really a 90% custom job despite the appearances (the presentation and their javascripts are heavily customized, but that's the tip of the iceberg.) You should be able to use Solr as a substitute.
[ "stackoverflow", "0038623632.txt" ]
Q: Joining 3 tables I have 3 tables STUDENT, STUDENT_GPA, STUDENT_ATTENDANCE as below STUDENT -------- STUDENT_ID STUDENT_NAME ----------------------- 1 A 2 B 3 C 4 D 5 E SUBJECTS -------- STUDENT_ID GPA UPDATE_FLG --------------------------- 2 8 Y 4 7 Y 5 8 N STUDENT_ATTENDANCE ------------------ STUDENT_ID ATTENDANCE UPDATE_FLG ---------------------------------- 3 92 Y Output should be STUDENT_ID STUDENT_NAME GPA ATTENDANCE -------------------------------------- 2 B 8 NULL 3 C NULL 92 4 D 7 NULL I tried the below query, but it is not working correctly. It is missing rows from either of tables SELECT S.STUDENT_ID, S.STUDENT_NAME, SD.GPA, SA.ATTENDANCE FROM STUDENT S LEFT OUTER JOIN STUDENT_GPA SD ON (S.STUDENT_ID=SD.STUDENT_ID AND SD.UPDATE_FLG='Y') LEFT OUTER JOIN STUDENT_ATTENDANCE SA ON (S.STUDENT_ID=SA.STUDENT_ID AND SA.UPDATE_FLG='Y') Please help! Thanks A: Although, it is not very clear from your question as to what resultset you need, however, looks like you want to select the data for those students whose GPA is updated or whose attendance is updated and you want to ignore all other records. Based on this understanding, below query gives you the expected resultset. SELECT S.STUDENT_ID, S.STUDENT_NAME, SD.GPA, SA.ATTENDANCE FROM STUDENT S LEFT OUTER JOIN STUDENT_GPA SD ON (S.STUDENT_ID=SD.STUDENT_ID) LEFT OUTER JOIN STUDENT_ATTENDANCE SA ON (S.STUDENT_ID=SA.STUDENT_ID) WHERE SA.UPDATE_FLG = 'Y' OR SD.UPDATE_FLG = 'Y'
[ "stackoverflow", "0001156022.txt" ]
Q: Transferring an Image using TCP Sockets in Linux I am trying to transfer an image using TCP sockets using linux. I have used the code many times to transfer small amounts but as soon as I tried to transfer the image it only transfered the first third. Is it possible that there is a maximum buffer size for tcp sockets in linux? If so how can I increase it? Is there a function that does this programatically? A: I would guess that the problem is on the receiving side when you read from the socket. TCP is a stream based protocol with no idea of packets or message boundaries. This means when you do a read you may get less bytes than you request. If your image is 128k for example you may only get 24k on your first read requiring you to read again to get the rest of the data. The fact that it's an image is irrelevant. Data is data. For example: int read_image(int sock, int size, unsigned char *buf) { int bytes_read = 0, len = 0; while (bytes_read < size && ((len = recv(sock, buf + bytes_read,size-bytes_read, 0)) > 0)) { bytes_read += len; } if (len == 0 || len < 0) doerror(); return bytes_read; } A: TCP sends the data in pieces, so you're not guaranteed to get it all at once with a single read (although it's guaranteed to stay in the order you send it). You basically have to read multiple times until you get all the data. It also doesn't know how much data you sent on the receiver side. Normally, you send a fixed size "length" field first (always 8 bytes, for example) so you know how much data there is. Then you keep reading and building a buffer until you get that many bytes. So the sender would look something like this (pseudocode) int imageLength; char *imageData; // set imageLength and imageData send(&imageLength, sizeof(int)); send(imageData, imageLength); And the receiver would look like this (pseudocode) int imageLength; char *imageData; guaranteed_read(&imageLength, sizeof(int)); imageData = new char[imageLength]; guaranteed_read(imageData, imageLength); void guaranteed_read(char* destBuf, int length) { int totalRead=0, numRead; while(totalRead < length) { int remaining = length - totalRead; numRead = read(&destBuf[totalRead], remaining); if(numRead > 0) { totalRead += numRead; } else { // error reading from socket } } } Obviously I left off the actual socket descriptor and you need to add a lot of error checking to all of that. It wasn't meant to be complete, more to show the idea.
[ "english.stackexchange", "0000352511.txt" ]
Q: What does 'vetted' mean in this context? Finally - and most significantly - at least two shipments of MANPADS have arrived into northern #Syria, to “vetted” FSA groups. Oxford defines it as: make a careful and critical examination of (something). How does it fit into this context? For more details, the original context: A: Vetted refers to the FSA (Free Syrian Army) groups that are considered reliable. If something is vetted, it is checked carefully to make sure that it is acceptable to people in authority. [mainly British] [be V-ed] : He can find no trace of a rule requiring research to be vetted before publication. [be V-ed] ⇒ All objects are vetted by a distinguished panel of experts. [V n] ⇒ He had not been allowed to read any book until his mother had vetted it. Collins Dictionary
[ "stackoverflow", "0053478429.txt" ]
Q: I have a question regarding practical implementation of Named Entity Recognition in NLP If we Consider two Named Entity Relation systems, one based on the use of word embedding and the other using both word and character embedding jointly. How can we intuitively conclude which model is better for NER task? Is any illustration possible for above case? A: If I understand your question correctly, you may train (if they require training) your models on some annotated dataset like CONL-2003 https://www.clips.uantwerpen.be/conll2003/ner/ and compare their accuracies using the test-part of the dataset.
[ "stackoverflow", "0009524543.txt" ]
Q: Advantages of HTML 5 Drag and Drop over jQuery UI Drag and Drop I'm writing a new web application that needs to support drag and drop operations for elements on the page (not file drag and drop). This the answer to this question html5 vs jquery drag and drop recommends using Modernizr to check whether the browser supports HTML5 drag and drop and either use that support or fall back to an alternative like jQuery UI. Since they have quite different models, that means that all drag and drop code would have to be implemented and tested separately (very little shared implementation). It only seems logical to do that if there are significant, user-impacting benefits to HTML5 drag and drop and if the fallback to jQuery UI would provide a degraded experience. Are there significant benefits to implementing both variants? A: I would guess that eventually jQuery will take advantage of built-in browser capabilities like html 5 drag and drop. And if different browsers implement it differently...jQuery will deal with it. A: I think the biggest advantage to HTML5 drag and drop over jQuery is the elimination of the sizable jQuery UI library and css files. That being said, there is the current issue of browser compatibility that makes jQuery very much needed. A: Ok, having implemented both, I'd recommend doing it manually with mousedown/mousemove events (basically as jquery UI does it). I agree that jQuery UI can be a bit heavy, but there are lots of tutorials/code snippets available to code it yourself. Why do I recommend a manual approach rather then the native implementation in modern browsers? Because html5 DnD sux! It might be new for current browsers, but is modeled after an old implementation back in IE5. If you are talking about moving things between windows for from the desktop, then maybe I'd consider using html5 DnD as it has browser/OS hooks. Else if you are simply moving DOM nodes on a single webpage, do it manually with js mouse events. -Paul
[ "stackoverflow", "0061950722.txt" ]
Q: glDrawArrays is not working for some reason? I do not understand why this is not working with glDrawArrays. If you see anything out of place or missing I really need to know. #define GLEW_STATIC #include <GL/glew.h> static int CompileShader(unsigned int type, const std::string& Source) { unsigned int id = glCreateShader(type); const char* src = Source.c_str(); glShaderSource(id, 1, &src, nullptr); glCompileShader(id); int result; glGetShaderiv(id, GL_COMPILE_STATUS, &result); if (result == GL_FALSE) { int length; glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length); char* message = (char*)alloca(length * sizeof(char)); glGetShaderInfoLog(id, length, &length, message); std::cout << message ; } return id; } static unsigned int CreateShader(const std::string& Vertexshader, const std::string& Fragmentshader) { unsigned int program = glCreateProgram(); unsigned int vertex = CompileShader(GL_VERTEX_SHADER, Vertexshader); unsigned int fragment = CompileShader(GL_FRAGMENT_SHADER, Fragmentshader); glAttachShader(program, vertex); glAttachShader(program, fragment); glLinkProgram(program); glValidateProgram(program); return program; } int main(void) { GLFWwindow* window; /* Initialize the library */ if (!glfwInit()) return -1; /* Create a windowed mode window and its OpenGL context */ window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL); if (!window) { glfwTerminate(); return -1; } /* Make the window's context current */ glfwMakeContextCurrent(window); if (GLEW_OK == glewInit()) { } float vertices[6] = { -0.5, -0.5, 0.0, 0.5, 0.5, 0.5 }; unsigned int buffer1; glGenBuffers(1, &buffer1); glBindBuffer(GL_ARRAY_BUFFER, buffer1); glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(float), vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 6, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0); glEnableVertexAttribArray(0); std::string Vertexshader = "#version 330 core\n" "\n" "layout (location = 0)in vec4 position;" "\n" "void main()\n" "{\n" " gl_Position = position;\n" "}\n"; std::string Fragmentshader = "#version 330 core\n" "\n" "layout (location = 0)out vec4 color;" "\n" "void main()\n" "{\n" " color = vec4(1.0, 0.0, 0.0, 1.0);\n" "}\n"; unsigned int shader = CreateShader(Vertexshader, Fragmentshader); glUseProgram(shader); /* Loop until the user closes the window */ while (!glfwWindowShouldClose(window)) { /* Render here */ glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glUseProgram(shader); glDrawArrays(GL_TRIANGLES, 0, 3); /* Swap front and back buffers */ glfwSwapBuffers(window); /* Poll for and process events */ glfwPollEvents(); } glfwTerminate(); return 0; } A: The 2nd parameter of glVertexAttribPointer is the tuple size of a coordinate, rather then the number of floats in the array of vertices. Each of the vertices in the array consists of 2 components, hence the size argument has to be 2 rather than 6: glVertexAttribPointer(0, 6, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0);
[ "salesforce.stackexchange", "0000099800.txt" ]
Q: issues updating the IsExternallyVisible flag on email message We have a trigger on before insert of an EmailMessage to check the contacts in the from, to and cc and based on that, determine if the mail message should be visible to externals. The code itself always runs fine and is pretty simple and gives the proper yes / no value to update the IsExternallyVisible flag but sometimes, it seems that the code just isn't called... even though, it's just a simple "before insert" without filtering out any records... Running the same code again afterwards for those records that got skipped by the trigger then correctly sets the IsExternallyVisible flag... Might there be situations where the "before insert" of an EmailMessage isn't executed??? A: Like I thought, it didn't have anything to do with the code as such but the issue was as follows: Salesforce itself also has it's logic to determine if the "IsExternallyVisible" flag should be true or false. You can find an explanation of their logic here: http://releasenotes.docs.salesforce.com/en-us/summer15/release-notes/rn_service_emails_case_feed.htm What is important to know is that the code of Salesforce for the IsExternallyVisible flag executes between the "before insert" and "after insert" event. We didn't know that at first and logically, our logic to set the IsExternallyVisible field was being launched in the "before insert" handler. So, in the end, causing the Salesforce logic around the IsExternallyVisible to be the boss instead our own custom logic... So, how we will fix it is either: executing the same logic but in the after insert. (meaning we will have to re-query the records cause those from the trigger context would be read only) or, executing the logic as a future method In my eyes, this is very strange behaviour of Salesforce and in any case not handy. They should at least put this a bit more clear in the documentation. Will definitely log a case for this. UPDATE: I assume the logic will also have to be executed in the "after update" for the case where someone would have first saved an email message as a draft... UPDATE 2: it was not possible to execute the code to set the IsExternallyVisible flag in the after insert and I had to do it with a future method. When trying to update the email message in the after insert, I got something like method not allowed, or some permission error. I remember getting this when the email message you were trying to update also contained other fields apart from the "IsExternallyVisible" flag but this wasn't the case now. Doing exactly the same in a future call did the trick.
[ "stackoverflow", "0025391048.txt" ]
Q: Height of convex, non-rectangular quad at position x,y? If I have a convex, non-rectangular quad which is facing "up" (the normal has a positive Z value) how can I find the z coordinate at a given x,y location? I've already determined that the x,y coordinate is within the quad. We can assume the quad points are all co-planar if that makes things easier. The more code-like an answer the more helpful it will be, as mathematical symbols don't really work in code. A: The plane passing through a point p=(px,py,pz) which has normal vector n=(nx,ny,nz) is composed by points (x,y,z) which satisfy the equation: nx * (px-x) + ny * (py-y) + nz * (pz-z) = 0. If you know that nz != 0 you can compute z: z = pz + (nx * (px - x) + ny * (py -y))/nz
[ "stackoverflow", "0024249621.txt" ]
Q: is it possible to make a field in Mysql table to to have length max=700, to be unicode (3 bytes) and to be unique? Mysql said that it only supports 700 char unique field in mysql table. So if I set the field to be unique then it will say error (like max length is 700 error). The reason is that unicode takes 3 bytes, so 700 unicode chars will be 2100 chars & Mysql can't set a field with 2100 to be unique. Is that any way to fix this issue? I am using Mysql 5.0. A: The default length limit on an index in InnoDB is 765 bytes. This means if you use a multi-byte character set, the limit is smaller, based on the greatest number of bytes per character. For example, 255 characters for utf8, or 191 characters if you use utf8mb4. You can set the configuration value innodb_large_prefix, and this allows InnoDB to support index length up to 3072 bytes, but you must use the Barracuda row formats (DYNAMIC or COMPRESSED). These row format are not supported in MySQL 5.0. Example: mysql> SET GLOBAL innodb_large_prefix=ON; mysql> create table b (v varchar(3073), key(v)) row_format=dynamic; ERROR 1071 (42000): Specified key was too long; max key length is 3072 bytes mysql> create table b (v varchar(3072), key(v)) row_format=dynamic; Query OK, 0 rows affected (0.02 sec) mysql> create table butf8 (v varchar(1025), key (v)) row_format=dynamic, character set=utf8; ERROR 1071 (42000): Specified key was too long; max key length is 3072 bytes mysql> create table butf8 (v varchar(1024), key (v)) row_format=dynamic, character set=utf8; Query OK, 0 rows affected (0.01 sec) See http://dev.mysql.com/doc/refman/5.6/en/innodb-parameters.html#sysvar_innodb_large_prefix Other storage engines may have greater limits, but it is implementation-specific. For example, in MyISAM, the default index length limit is 1000 bytes, so you can create an index on a varchar(333) in utf8, and varchar(250) in utf8mb4. In TokuDB, the maximum index length is 3072 bytes. But I couldn't find any mention of TokuDB support for MySQL 5.0. Tokutek distributes a binary build of MySQL 5.5 with TokuDB storage engine. But all the above, while answering your question literally, avoids the greater issue: do you really want a unique index on such long strings? Long index sizes are not as efficient as short index sizes, (both in terms of size on disk or in memory, and in terms of runtime performance). You would do better to limit your string size, or else store a hash or a soundex of the string, and apply uniqueness to that column. Re your comment: I can use trigger to prevent the duplicated row I assume you mean you will do a SELECT inside the trigger to search for a row where the long string matches, and abort the operation if one is found. I want to add another piece of information that may help this trigger function more efficiently: You can still create an index on a very long string, but define the index as a "prefix index" so that it indexes the first N characters. This is not suitable for a UNIQUE constraint, because two different strings may have the same characters in the leading part of the string. But it will help your SELECT in the trigger search only among strings that are same at least in that leading portion. The other comment is that MySQL 5.0 does not have any syntax in a trigger to abort the operation. The SIGNAL functionality was introduced in MySQL 5.5. One hack I have seen used to abort a trigger is to declare a local integer variable in the trigger, and then inside an IF statement try to assign a string value to the integer variable, which will cause an error. DECLARE foo INT; IF ( ... ) THEN SET foo = 'Duplicate string found'; END IF; When you try to insert a duplicate, you get this: ERROR 1366 (HY000): Incorrect integer value: 'Duplicate string found' for column 'foo' at row 2 The clever thing is that you can make the string you try to assign contain the error message you want displayed to the user, and you can make the local variable have the same name as the column that you want to preserve uniqueness. The only strange part is that the error says "Incorrect integer value".
[ "physics.stackexchange", "0000147847.txt" ]
Q: New subatomic particles In reference to the findings talked about here http://online.wsj.com/articles/two-new-subatomic-particles-found-using-large-hadron-collider-scientists-say-1416409980 and other similar articles describing these, and other, subatomic particles. What role do such newly discovered particles play in the standard model? Physics in general? What does the discovery mean for physics? With the Higg's boson, there was an immediate problem, of sorts, or fact more accurately, which was proven when it was discovered, but with these particles there is nothing that appears to be as sensational! A: The new particles are baryons, and baryons are composite particles made up from three quarks. So the new particles aren't fundamental in the way that the Higgs is. To make an analogy, suppose physicists discover a new element. That's interesting, but like all atoms it's made of electrons, neutrons and protons. So the new element is just another way of arranging more fundamental particles. Likewise, the new particles are just another way of arranging three quarks. So they are interesting, but not Earth shattering. A: The good thing about this discovery is that those particles were predicted by the standard model but never measured before. So it is, yet again, another good news for the standard model, it seems to work perfectly. In science anyway you are more exited when you discover something that you didn't expect. In this sense the Higgs boson was unusual: we were expecting it and yet there was a big excitement. Long story short: we invested so much money and time that it became really important to discover it.
[ "stackoverflow", "0046271269.txt" ]
Q: Regex: match only if word occurs once I would like this to ONLY return a match if there is no more than one 'Yes'. EXAMPLE: This would be a match: Event 1 (Yes) Event 2 (No) Event 3 (No) This would NOT be a match: Event 1 (Yes) Event 2 (No) Event 3 (Yes) I've tried so many different combinations based on other answers I've found. A: You can match one Yes with: ^([^Y]|Y[^e]|Ye[^s])*Yes([^Y]|Y[^e]|Ye[^s])*$ assuming you are using Perl or PCRE regex.
[ "stackoverflow", "0054042306.txt" ]
Q: Multiple UserForms that trigger each other; UserForm_QueryClose not working as expected I've got 5 UserForms and some of them activate depending on what the input of the first UserForm is. The first UserForm code is below. Private Sub OptionButton1_Click() If OptionButton1.Value = True Then WsName = "CAT" Unload Me End If End Sub Private Sub OptionButton2_Click() If OptionButton2.Value = True Then WsName = "DOG" Unload Me End If End Sub Private Sub OptionButton3_Click() If OptionButton3.Value = True Then WsName = "CATDOG" Unload Me End If End Sub Private Sub OptionButton4_Click() If OptionButton4.Value = True Then WsName = "DOGCAT" Unload Me End If End Sub Private Sub UserForm_Initialize() Me.StartUpPosition = 0 Me.Top = Application.Top + 250 Me.Left = Application.Left + Application.Width - Me.Width - 600 End Sub Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer) End End Sub When I press the Red "X" to end the entire module that calls the UserForm the module is exited and I am happy. When I press one of the options on the userform like OptionButton1.Value = True then the code also exits the module and I am sad. What am I doing wrong? I would like for the user to be able to press the Red "X" at any point in any UserForm to close out the Module and break out of the code. A: The answer to this question was Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer) If OptionButton1.Value = False And OptionButton2.Value = False OptionButton3.Value = False And OptionButton4.Value = False Then End End If End Sub
[ "stackoverflow", "0002203806.txt" ]
Q: Android: Eclipse MAT does not appear to show all my app's objects I have created an hprof file by inserting the statement Debug.dumpHprofData("/sdcard/myapp.hprof"); in my app's code; I have then run the hprof file through hprof-conv and opened the converted file in Eclipse. Following the advice of the MAT "Cheat Sheet" I have obtained an analysis of my app's memory usage by going to "Leak Identification -> Component Report" entering "com.prepbgg.*" and hitting Finish. I know that my app is consuming large amounts of memory: in particular at the stage where I called dumpHprofData it had a one megapixel bitmap object and a canvas that must have consumes several hundred KB. (I also suspect that it is leaking significant amounts of memory because performance degrades severely after the screen has been rotated a few times.) However, the Component Report for com.prepbgg.* shows total memory of only 38.7KB. The Histogram view shows for android.graphics.Bitmap (presumably this is the total of all apps including mine) 404 objects and Shallow Heap 12,928. Is that 12,928 bytes? Clearly, my app consumes more than 38.7KB and the Bitmap far more than 12,928 bytes. Where am I going wrong? How can I see the total memory consumed by my app? A: most of the space for the bitmap will be on the native heap. see the source for Bitmap: it has seven fields. assume each field is four bytes (almost certain for the reference and ints, and plausible for the booleans) add an extra four bytes for the object header, and: (7*4 + 4) * 404 = 12928 i don't think there's any easy way to examine the native heap without running your own build yet. you can ask how much stuff's been allocated: http://developer.android.com/reference/android/os/Debug.html#getNativeHeapAllocatedSize()
[ "stackoverflow", "0027362799.txt" ]
Q: Using RxJava to fetch object, transform a containing list, and use the list The high level problem I'm trying to solve is transforming a list of Foo objects contained in a fetched FooContainer (Observable) to a list of FooBar objects using RxJava. My (confused) attempt: fooContainerObservable .map(container -> container.getFooList()) .flatMap(foo -> transformFooToFooBar(foo)) .collect( /* What do I do here? Is collect the correct thing? Should I be using lift? */) .subscribe(fooBarList -> /* Display the list */); My confusion (or at least one point of it) is the step moving the flattened list back to a list. Note: I'm attempting to do this in an Android app. A: toList can collect all items of an Observable into a List and emit it. toList can be implemented using collect, but it's much easier than collect. For your example, it will be: fooContainerObservable .map(container -> container.getFooList()) .flatMap(foo -> transformFooToFooBar(foo)) .toList() .subscribe(fooBarList -> /* Display the list */);
[ "stackoverflow", "0021183661.txt" ]
Q: How can I send tcpdump output to a database? I have an access point running openWRT v12.09 with tcpdump installed. On a server I have node.js running with couchdb. I would like the output of tcpdump to be written to couchdb. This is where I'm a bit in the dark. I can't figure out how to make the connection between openWRT/tcpdump to node.js/couchdb. I read a pipe is way to have one side reading data and the other side storing the data. That would be the goal since the storage capacity of the access point is limited. I would like the output of tcpdump to be converted in to JSON, is that possible? So it's easy to read and store in the database. I read about, openVPN, pipe, nodecat and tried a bunch of things but I need some assistance please, thank you. A: Why won't you use simple HTTP protocol? That's exactly the case for which it was invented - moving resources accross the Web. Install lightweight HTTP server on the access point, if you don't have one there already. For example, boa is very lightweight, single-tasking HTTP server, which could be more than enough for this purpose. Then, just: let the tcpdump store the file in the server directory tree at the access point on the server, use HTTP module of node.js to download the file store it in the database. That's it. There's no need nor is it a good idea to convert your binary data into JSON!
[ "stackoverflow", "0016551461.txt" ]
Q: Using HTML 5 GeoLocation API to get location time I just came to know that HTML 5 includes GeoLocation API to determine location via Browser. I want to know whether it is possible to determine user's TimeZone, and local time using this API. If yes, how? A: According to the W3C specification, there is a timestamp that the position was last delivered. But it will be delivered without timezone data. Since you are using Javascript, and running on a client device. You could add some code into the position callback that obtains the timezone data that you're looking for, and the local user's time along with the position data.
[ "stackoverflow", "0006113343.txt" ]
Q: Are there tutorials for how to transfer pictures with iTunes file sharing between Mac/PC and iOS? I'd like some kind of overview tutorial that shows how this works. I have only found very specific ones so far which deal with complex problems like file packages etc., but I only need simple images import/export. Does someone know a tutorial or example project which does just that? A: Better late than never, I guess... This is the best documentation I've seen for file sharing: http://www.raywenderlich.com/1948/how-integrate-itunes-file-sharing-with-your-ios-app If your needs are basic you can just enable UIFileSharingEnabled in your Info.plist and you should be able to read/write to the documents directory of the app without further coding.
[ "stackoverflow", "0044428704.txt" ]
Q: D3 - get number of dimensions in radial chart This is probably a basic selector in D3, but can't find it. I just want to get the count of the number of dimensions (rings) in this radial chart. http://blockbuilder.org/anonymous/1b5e5b56c33ef5c8840160da3e403105 Counting from the inner most blue ring/circle to the outermost ring (e.g. NodeLinkTreeLayout) the count is 5. What d3 query or property can I use to get this number? A: For counting the number of layers, or rings as you called them, you just need to find the depth property with the highest value in the data array: var rings = d3.max(partition.nodes(root), function(d){ return d.depth }) + 1; console.log("the number of rings is " + rings) Since depth is zero-based, I'm adding 1 to the maximum value. Have a look at the console in the updated blockbuilder: http://blockbuilder.org/anonymous/9ac9d8a21f366202f077393b67239cc3
[ "stackoverflow", "0045111875.txt" ]
Q: Synchronous Emitted Events With csv-parser I'm trying to use the npm package csv-parser for parsing my csv files and have run into an issue with the order of events occurring. Events are emitted in this order 'headers': Want to insert metadata about the csv into a database and return an id value 'data': Want to use the returned id value from the headers event for all data events 'data' 'data' ... end Obviously the asynchronous nature of node means that my slow database access in 'headers' hasn't returned by the time the first 'data' event is emitted and therefore I don't have the id of the csv yet. The only option I can think of is to cache all data rows into some temporary variable and then push everything once the whole csv has been read. Considering that I may have very large csv files, this seems like a bad idea? Any suggestions on a better method of tackling this problem? EDIT: Added some code (pseudo code, not actually tested) let headerList = null; let dataArray = []; fs.createReadStream(path) .pipe(csv()) // Parse the headers into a comma delimminated string .on('headers', function(headers) { // some parsing logic and then assigned to variable headerList = headers; }) .on('data', function (data) { // Some push of data into a variable dataArray.push(data); }) .on('end', function() { // create the base upload object const id = uploads.createUpload(filename, headerList, new Date()); // insert data uploads.insertUploadData(id, dataArray); }) A: When you get the headers event, unpipe() the read stream. This will put the file reader into a paused state so you don't have to buffer a bunch of stuff in memory. Because data is read from disk in chunks (usually 64 kB), the CSV parser will still emit data events as it continues to parse the current chunk. You'll still need to buffer a small number of rows in an array. When you have all the information you need from the database: Submit the buffered rows to the database. Remove the original data event handler (the one that queues to an array) and attach one that submits rows directly to the database. pipe() the read stream back to the CSV parser. You may also want to consider what happens if your program reads from disk and parses CSV faster than your database can accept data. Since there's no backpressure, a large number of database operations may end up queuing up in memory until you run out. You should pause the file read stream if there are many pending DB operations.
[ "datascience.stackexchange", "0000025596.txt" ]
Q: How to plot two columns of single DataFrame on Y axis i have two DataFrames(Action,Comedy). Action contains two columns(year,rating) ratings columns contains average rating with respect to year. Comedy Dataframe contains same two columns with different mean values. i merge both dataframe in a total_year Dataframe Output of total_year Now i want to plot total_year on line graph in which X axis should contain year column and Y axis should contain both action and comedy columns. i can plot only 1 column at a time on Y axis using following code. total_year[-15:].plot(x='year', y='action' ,figsize=(10,5), grid=True ) How i can plot both columns on Y axis? i took this photo from google just to let you know guys i want to draw graph in this way A: Feeding your column names into the y values argument as a list works for me like so: total_year[-15:].plot(x='year', y=['action', 'comedy'], figsize=(10,5), grid=True) Using something like the answer at this link is better and gives you way more control over the labels and whatnot: adding lines with plt.plot()
[ "stackoverflow", "0004020184.txt" ]
Q: What would be a clever design for layered panels? I would like to design a light "members listing/editing" app in one and only window. My guess was that the best and simplest way to achieve this would be to have the "listing" part (mostly a datagridview and some search stuff) on a panel, and the "editing" (new member or modify member) on another, each panel hiding the other depending on what User wants to do. That's what I have to end up with, visually speaking. I've thought of many ways to design this but no one sounded actually good to me, mainly when it comes to instantiate the viewmodel of the editing panel passing the selected member in the dgv of the listing panel or stuff like that. I still consider myself a beginner at WPF and I'm sure the most clever solution is something that didn't come to my mind. Can't wait to read expert's suggestions ;) A: You should be thinking more in terms of DataTemplate. Split your two different views up, eg. MemberListingView.XAML and MemberEditView.XAML. Create view-models for each view. To put it all together, follow the data templating technique: <DataTemplate DataType="{x:Type vm:MemberListingVM}"> <AdornerDecorator> <views:MemberListingView /> </AdornerDecorator> </DataTemplate> <DataTemplate DataType="{x:Type vm:MemberEditVM}"> <AdornerDecorator> <views:MemberEditView /> </AdornerDecorator> </DataTemplate> // Now use a content presenter <ContentPresenter Content="{Binding CurrentView}" /> You should have somewhere in your context a property that specifies the current view that you need to show. private ViewModelBase _currentView; public ViewModelBase CurrentView { get { return _currentView; } set { _currentView = value; RaisePropertyChanged("CurrentView"); } } // ... public void OnSelectedMemberChanged(Member member) { // Depending on your logic // If some condition... CurrentView = new MemberEditVM(member); // else CurrentView = MemberListingVM; }
[ "math.stackexchange", "0002016132.txt" ]
Q: Showing lower-semi-continuity of a function. Let $f_\lambda: \mathbb{R} \rightarrow \mathbb{R} (\lambda \in \Lambda)$ be a family of continuous functions. Let $$ F(x) = \sup_{\lambda \in \Lambda} f_\lambda (x), x \in \mathbb{R}.$$ Show that $F$ is lower-semi-continuous. My attempt: We must show that $\liminf_{x \rightarrow x_0} F(x) \geq F(x_0)$ for all $x_0 \in \mathbb{R}$. Since each $f_\lambda$ is continuous, it is also lower-semi-continuous. Thus, $$\liminf_{x \rightarrow x_0} f_\lambda(x) \geq f_\lambda (x_0).$$ Is it true then that $\liminf_{x \rightarrow x_0} \sup f_\lambda(x) \geq \sup f_\lambda (x_0)$? Why? Is there a way I should justify this? Is it because $\liminf_{x \rightarrow x_0} \sup f_\lambda(x) \geq \sup (\liminf_{x \rightarrow x_0} f_\lambda(x)) \geq \sup f_\lambda (x_0)?$ A: Let $\epsilon >0$, By definition of $\sup$, there is a $\lambda \in \Lambda $ such that $F(x_0)-\epsilon<f_{\lambda}(x_0)$. As $f_{\lambda}$ is continuous there is a neighborhood $U$ containing $x_0$ such that $F(x_0)-\epsilon<f_{\lambda}(x)$ whenever $x\in U$. But $f_{\lambda}\le F$ so in fact $F(x_0)-\epsilon<F(x)$. This is one of the equivalent definitions of lower-semicontinuity so we are done. But to prove that this definition coincides with the one you are using, choose $N\in \mathbb N$ so that $(x_0-1/N,x_0+1/N)\in U$. Then if $n\ge N$, $F(x_0)-\epsilon<F(x)$ for all $x\in U_n \doteq (x_0-1/n,x_0+1/n)$, which implies $F(x_0)-\epsilon\le\inf_{x\in U_n}F(x)$ for all $n\ge N$ which means that $F(x_0)-\epsilon\le \lim_{n\to \infty}\inf_{x\in U_n}F(x)$. The result now follows because $\epsilon $ is arbitrary.
[ "civicrm.stackexchange", "0000024837.txt" ]
Q: Display CIVICRM Contact Dasboard Drupal 7.59 Civi 4.7.27 In Blocks there is a default CiviCRM Contact Dashboard. #block-civicrm-3 I have assigned it to Content. It displays for Admin but not for any other roles. I want it to display for role Donor. In the block config I have Roles checked to display Admin & Donor. Under Civi > Administer > Users > Permissions > Drupal Access Control I checked for Donor: CiviCRM: view my contact & CiviCRM: access Contact Dashboard But the Donor role still cannot see the link to access their dashboard. When signed in as a donor I can go to /civicrm/user and see the dashboard. It is just not displaying this default block that has the link. Any ideas what is keeping this from displaying? A: I created a new block with with the link civicrm/user and assigned it to role Donor and it shows up. Not sure why the default one does not show up, all the settings are the same.
[ "stackoverflow", "0052698249.txt" ]
Q: How should I type hint UserModel in a Laravel package? I want to type hint the User model in a package. By default, it's App\User. In a channel class, this would be ok: class ChannelExample { public function join(\App\User $user) { // } } If the App namespace has been changed (using artisan app:name for instance), it will no more work. In a package, obviously, it's not possible to know what namespace users will use. Therefore, typehinting is not a good idea... What is the best practice to type hint and keep the package work with any App namespace? A: use the Contract that laravel uses for it's Auth Classes. public function join(Illuminate\Contracts\Auth\Authenticatable $user) { // }
[ "stackoverflow", "0007551822.txt" ]
Q: Changing the text / content using properties files at runtime I'm using ResourceBundle.getBundle() to load property file in our portlet But If any user wants to change contents of that property file at runtime without deploying that portlet again. How can it reflect in UI[get latest value from property file] without deploying portlet? Thanks in Advance, Mayur Patel A: There's no such functionality in Liferay. You'd have to change Liferay code to make this work the way you want. To understand where in Liferay code .properties files are loaded into ResourceBundle-s see com.liferay.portlet.PortletConfigImpl class getResourceBundle(Locale locale)� method and com.liferay.portal.language.LanguageResources _loadLocale(Locale locale)� method.
[ "math.stackexchange", "0001121652.txt" ]
Q: To find the total no. of six digit numbers that can be formed having property that every succeeding digit is greater than preceding digit. I have a question and got strucked on this.. To find the total no. of six digit numbers that can be formed having property that every succeeding digit is greater than preceding digit. Please guide me to solve this. Thanks in advance. A: Hint: Once you've picked six different digits, there is only one way to arrange them to satisfy the conditions given. A: Or to look at it another way. There is only one 9 digit number with this condition 123456789. What about 8 digits?: there are nine answers 12345678, 12345679, 12345689, 12345789, 12346789, 12356789, 12456789, 13456789, 23456789. So all I have done is strike out each digit in turn. $9\times 1$ digit = 9 possibilities. For 7 digits, you need to strike out 2 digits - how many ways of doing this are there? does $\binom{9}{2}$ ring a bell? And so for 6 digit number you need to lose 3 digits.........
[ "stackoverflow", "0023768971.txt" ]
Q: How are each of the iOS background fetch UIBackgroundFetchResult types handled after the completion handler is called? After your application completes its actions during a background fetch you must call the completionHandler block with one of the three UIBackgroundFetchResult states: UIBackgroundFetchResultNoData, UIBackgroundFetchResultNewData, or UIBackgroundFetchResultFailed. How are each of these three results handled by the OS once the completion handler is called? A: From the iOS App App Programming guide: When the application:performFetchWithCompletionHandler: method of your delegate is called, use that method to check for new content and to download that content if it is available. When your downloads are complete, execute the provided completion handler block, passing a result that indicates whether content was available. Executing this block tells the system that it can move your app back to the suspended state and evaluate its power usage. Apps that download small amounts of content quickly and accurately reflect when they had content to download are more likely to receive execution time in the future than apps that take longer to download their content They don't give us so many details, but I think is clear enough: you pass the result of the fetch to the System, so it can decide when to give background execution time (and how much). Example, consider two different apps: - one downloads files that are updated every night - the other downloads files that are updated more frequently, many times in a day In both cases, the system will wake up your app, takes note of the start time, your app starts the download and then tells the system that there was or not content available. After some time, you'll see that the system will wake up the first app less frequently than the second one, optimizing battery consumption. Moreover, if you use NSURLSession to start you download, the system will evaluate your app's power consumption (since using NSURLSession you have "unlimited" time to download files), even this metric is used to decide how often wake up your app.
[ "gardening.stackexchange", "0000035425.txt" ]
Q: Why would a broccoli plant have grey patches on only a single leaf? I'm making a temporary garden for a client at home to move to the landscaping location. He requested his garden contain broccoli which is the plant I'm worried about currently. It seems to have grey patches on a single leaf at the moment. I'm living in Australia and we are currently going through winter, minimum 2° celcius (35° fahrenheit) nights and 8° celcius (46° fahrenheit) days. Here is the broccoli leaf: A: That leaf is the oldest leaf and is in the process of dying. Totally normal. Cut it off so that plant can concentrate its energy making its flower!
[ "stackoverflow", "0052188920.txt" ]
Q: System.identityHashCode is equal on String instances because of reasons I am trying to copy/clone instances of objects. And in the case of String i tried something like this: I do have an object like class Foo{ private String test; //Getters && Setters are generated } and a copy method like: private static Object copyMemberData(Object originalMemberData) { if (originalMemberData == null) { return null; } ... if (originalMemberData instanceof String) { return String.valueOf(originalMemberData); } ... } which is used like PropertyDescriptor propDesc = new PropertyDescriptor("test", Foo.class); //Get Data from original object final Object originalMemberData = propDesc.getReadMethod().invoke(originalFoo); final Object copiedMemberData = copyMemberData(originalMemberData); And afterwards I tried to compare the result with System.identityHashCode to ensure that I am not working on a reference. if (System.identityHashCode(copiedMemberData) == System.identityHashCode(originalMemberData)) { throw new RuntimeException("Cloning is buggy!"); } And I am suprised this actually matches and throws me an error. Maybe someone can explain me the reason for that. A: I found it out :-) The String is the same even if I do compare it with == instead of equals. This is the case because the toString() method of the String.java class which is used in String.valueOf(Object obj) is implemented like: public String toString() { return this; } To successfully copy a String use: return new String(((String)originalMemberData).toCharArray());
[ "stackoverflow", "0002725415.txt" ]
Q: MySQL query pulling from two tables, display in correct fields I'm trying to select all fields in two separate tables as long as they're sharing a common ID. //mysql query $result = mysql_query("SELECT * FROM project, links WHERE project.id = links.id and project.id = $clientID") //displaying the link if ($row['url'] != null){ echo "<div class='clientsection' id='links'>Links</div>"; echo "<a class='clientlink' id='link1' href='" . $row['url'] . "'>" . $row['name'] . "</a>"; } else { echo "<a class='clientlink' id='link1' href='" . $row['url'] . "' style='display:none;'>" . $row['name'] . "</a>"; }; As you can see, my tables are "projects", and "links" Each is sharing a common field "id" for reference. It looks as though where both links.id and project.id are equal, it outputs anything, but when there is no links.id associated with a given $clientID the container relative to the $clientID doesn't display at all. Essentially I'm using this to add links dynamically to a specific client in this CMS and if there are no links, I want the container to show up anyway. Hopefully I've expressed myself clearly, any pointers in the right direction are appreciated. Thanks! A: Using the SQL ANSI explicit join syntax, you can specify a LEFT OUTER JOIN, as opposed to the INNER JOIN that you are doing in your implicit join. The LEFT OUTER JOIN returns results in the first table even if there are no matching rows in the joining table: SELECT * FROM project LEFT OUTER JOIN links ON links.id = project.id WHERE project.id = $clientID For rows where there is no matching id in the links table, links.id will be NULL. Edit If you want just the first link, where the autoincrement primary key links.linkid specifies the order, you can do a self join like this: SELECT * FROM project LEFT OUTER JOIN links ON links.id = project.id LEFT OUTER JOIN links l2 ON l2.id = project.id AND l2.linkid < links.linkid WHERE project.id = $clientID AND l2.id IS NULL What this does is join in any links table rows where the linkid is smaller, and then exludes those rows in the WHERE clause. You end up with just the rows where there is no smaller linkid, hence the link with the smallest linkid for each project.
[ "stackoverflow", "0022559728.txt" ]
Q: The public function call is not getting executed after the code of private variable <?php /* example for access specifiers*/ class myClass { var $car = "alto"; //if we declare as var it is automatically considered as public public $pub = "alphanso"; //even no need to using public keyword as it is public bydefault private $pri = "zen"; public function myPublic() { echo "I'm public...can be accessible everywhere"; } private function myPrivate() { echo "I'm private...no where am accessible,except in current class"; } } $accss = new myClass; echo $accss->car . "<br>"; echo $accss->pub . "<br>"; echo $accss->pri . "<br>"; $accss->myPublic(); $accss->myPrivate(); //visible only in the class where it is declared. ?> A: You cannot access a private member or a method outside of the class, trying to do that will raise a FATAL error. It cannot access $accss -> myPublic(); because you encounter a FATAL error here echo $accss -> pri."<br>"; as per the above condition I specified. So the rest of the code will not be executed.
[ "stackoverflow", "0010604307.txt" ]
Q: Sending UDP packet from android platform I'm trying to build a UDP client on an android tablet. The application can create a socket juste fine, but when I try to send it: public void SendMessage( String message ) { sendBuffer = message.getBytes(); packet = new DatagramPacket( sendBuffer, sendBuffer.length, address, 4445 ); //packet = new DatagramPacket( sendBuffer, sendBuffer.length, address, port ); try { socket.send( packet ); } catch (IOException ioe) { Log.d( "NETWORK", "Failed to send UDP packet due to IOException: " + ioe.getMessage() ); ioe.printStackTrace(); } catch( Exception e ) { Log.d( "NETWORK", "Failed to send UDP packet due to Exeption: " + e.getMessage() ); e.printStackTrace(); } } Eclipse pops a new window saying "source not found" and I have this printed out in the LogCat: android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099) at libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:175) at ... I'm wondering if maybe the port I'm using is blocked or can something block my UDP connection (because I've tried many different ports all with the same result). I'm asking this because of the LogCat (BlockGuardOS) which could indicate it's blocking some input/output This is the actual initialization is here: public ClientSocketThread( String address, int port ) { this.port = port; try { this.address = InetAddress.getByName( address ); Log.d( "NETWORK", "Address successfully resolved" ); } catch( UnknownHostException ue ) { ue.printStackTrace(); Log.d( "NETWORK", "Failed to resolve ip address due to UnknownException: " + ue.getMessage() ); } try { this.socket = new DatagramSocket(); Log.d( "NETWORK", "UDP Socket successfully created" ); } catch( SocketException se ) { Log.d( "NETWORK", "Failed to create socket due to SocketException: " + se.getMessage() ); se.printStackTrace(); } } A: android.os.NetworkOnMainThreadException You are no longer allowed to do networking from the main (UI) thread. You were always warned against it in the documentation, but it is now pro-actively trapped. The topic has been covered numerous times here on SO and in other sources.
[ "stackoverflow", "0030595536.txt" ]
Q: What does StackExchange.Redis do with the configured Masters/Slaves? I'm looking at StackExchange.Redis and notice it has features for automatically determining which of the configured servers is master, and which are slaves. I've not managed to spot what StackExchange actually does with the configured Masters/Slaves. Does it always run commands on Master, and only use configured Slaves for failover? Or is the answer more in-depth than that? Any pointers appreciated! A: The key thing here is CommandFlags, a parameter on every method. By default, most are PreferMaster, however; note that write commands escalate to DemandMaster automatically. However, if you want to spread load, you can elect to push some read commands (preferably the expensive ones) to slaves via PreferSlave and DemandSlave. The other things it let's you do is to switch master (promote to master) - although this is naturally more invasive.
[ "stackoverflow", "0012362877.txt" ]
Q: Delete entity from index? Am I doing this right? I'm trying to delete an entity from the index in this method, it's the first time I try so I don't know if it's working: def get(self): timeline = datetime.now () - timedelta (days = 59) edge = datetime.now () - timedelta (days = 60) ads = Ad.all().filter("published =", True).filter("modified <", timeline).filter("url IN", ['www.koolbusiness.com']).filter("modified >", edge) for ad in ads: if ad.title: subject= ad.title else: subject = 'Reminder' message = mail.EmailMessage(sender='[email protected]', subject=subject) reminder = 'You can renew your advertisement' message.body = ('%s \nhttp://www.koolbusiness.com/vi/%d %s') % (reminder, ad.key().id(), '\nIf you like, you can also add us on Facebook \nhttp://apps.facebook.com/koolbusiness') message.to=ad.email message.bcc='[email protected]' message.send() index = search.Index(name='ad', consistency=Index.PER_DOCUMENT_CONSISTENT) index.remove(str(ad.key()) The above code is supposed to send a reminder for timed out advertisements and then remove then from the index. If the advertisement is renewed it can be added to the index again. Will it work? A: You code should work, but IMHO it is best to mark the ad as expired instead of removing it from the index. This will save you the need to reindex renewed ads and will give you better audit on your ads.
[ "expressionengine.stackexchange", "0000014317.txt" ]
Q: exp:channel:form and relationships So, running on 2.5.5 I would do the following (with SafeCracker instead): {exp:channel:form channel="resumeer" return="folketinget/resume_ret/ENTRY_ID" include_jquery="no"} <p>Overskrift: <input type="text" name="title" id="title" value="{title}" size="50" maxlength="100" /></p> <input type="hidden" name="url_title" id="url_title" value="{url_title}" maxlength="75" size="50" /> <input type="hidden" name="allow_comments" value="y" /> <input type="hidden" name="relation_lovforslag" value="<?php echo $entry_id; ?>" /> <input type="hidden" name="status" value="Closed" /> {field:wygwam_basic} <p><input type="submit" name="submit" value="GEM KLADDE" class="form-submit" /></p> {/exp:channel:form} This is for creating a related entry to the main channel entry. The field relation_lovforslag is for that purpose and it just sends the entry_id of the main entry. However, this doesn’t work anymore and I wonder what the proper syntax is for 2.7? A: I ended up getting it to work with: <input type="hidden" name="relation_lovforslag[data][]" value="<?php echo $entry_id; ?>" />
[ "mathoverflow", "0000286612.txt" ]
Q: $q$-analog of an integral from quantum field theory? This question has been completely reformulated and a new property for the function $f_q$ has been added due to a series of helpful comments by fedja. Consider the integral from quantum field theory due to F.A. Smirnov (see this MSE post): \begin{align} &\int_{-\infty}^{\infty}\prod_{j=1}^3\Gamma\Bigl(\frac 1 3 -\frac {\alpha-\beta_j}{2\pi i}\Bigr) \Gamma\Bigl(\frac 1 3 +\frac {\alpha-\beta_j}{2\pi i}\Bigr)(3\alpha-\sum\beta_m)e^{-\frac{\alpha}2}d\alpha\nonumber\\ &=\frac{(2\pi \Gamma(\frac 2 3))^2}{\Gamma(\frac 4 3)} \prod_{k\neq j}\Gamma\Bigl(\frac 2 3 -\frac {\beta_k-\beta_j}{2\pi i}\Bigr) e^{-\frac12\sum\beta_m}\sum e^{\beta_m},\quad |\text{Im}~\beta_j|<2\pi/3. \end{align} Some analytical and numerical calculations suggest that it has a $q$-analog of the form \begin{align} &\int_{-\infty}^\infty\prod_{j=1}^3\frac{\Gamma_q\left(\frac13+\frac{x-\beta_j}{2\pi i}\right)}{\Gamma_q\left(\frac23+\frac{x-\beta_j}{2\pi i}\right)}\frac{\sum q^{-\frac{\beta_m}{2 \pi i}}-\left(1+q^\frac13+q^{-\frac13}\right) q^{-\frac{x}{2 \pi i}}}{\prod_{m}\sin\left(\frac{\pi}3-\frac{x-\beta_m}{2 i}\right)}e^{-\frac{x}2}dx\\ &=\frac{-2\pi i}{(q;q)_{\infty }^9}\frac{\Gamma_q^2\left(\frac23\right)}{\Gamma_q\left(\frac43\right)}\frac{q^{5/9}}{(1-q)^2}e^{-\frac{1}{2} (\beta_1+\beta_2+\beta_3)} q^{-\frac{\beta_1+\beta_2+\beta_3}{6 \pi i}}\prod_{k\neq j}\Gamma_q\left(\frac23+\frac{\beta_j-\beta_k}{2\pi i}\right)\\ &\times\frac{\theta_q(q^{\frac{\beta_1-\beta_2}{2\pi i}})}{\sin\frac{\beta_1-\beta_2}{2 i}}\frac{\theta_q(q^{\frac{\beta_2-\beta_3}{2\pi i}})}{\sin\frac{\beta_2-\beta_3}{2 i}} \frac{\theta_q(q^{\frac{\beta_3-\beta_1}{2\pi i}})}{\sin\frac{\beta_3-\beta_1}{2 i}} \cdot f_{q_1}(\beta_1,\beta_2,\beta_3).\tag{5} \end{align} where $q_1=e^{-\frac{4 \pi ^2}{\ln(1/q)}}$, $\Gamma_q$ is the $q$-Gamma function and $$ \theta_q(z)=(q;q)_\infty(z;q)_\infty(q/z;q)_\infty. $$ The exact form of the function $f_q$ is unknown but there is evidence that it has a relatively simple closed form expression in terms of finite combination of theta functions. Obviously $f_q(x,y,z)$ is symmetric in all three arguments $x,y,z$. It is known also that it has the following properties \begin{align} &f_q(x+c,y+c,z+c)=e^cf_q(x,y,z),\tag{1}\\ \\ &f_q\left(\frac{2\pi i}{3},0,z\right) \begin{aligned}[t] & =\left(e^z-1\right) \frac{\theta_q\left(e^{\frac{4 i \pi }{3}-z}\right)}{\theta_q\left(e^{-z}\right)}\\ & =\left(e^z-1\right)e^{-\frac{\pi i}{3}} q_1^{-\frac{1}{9}+\frac{z}{6 \pi i}}\frac{\theta_{q_1}\left(q_1^{\frac13+\frac{z}{2\pi i}}\right)}{\theta_{q_1}\left(q_1^{\frac{z}{2\pi i}}\right)} \end{aligned} \tag{2}\\ \\ &f_q(x,y,z)=e^x+e^y+e^z\\ &+\frac32\left(e^x+e^y+e^z\right)\left(1+e^{x-y}+e^{y-x}+e^{y-z}+e^{z-y}+e^{z-x}+e^{x-z}\right)q\\ &+i\frac{\sqrt{3}}{2}\left(e^{-x}+e^{-y}+e^{-z}\right)\left(e^{2x}+e^{2y}+e^{2z}\right)q+O(q^2) \tag{3} \\ &f_{q}(x,y,z)= e^{-\frac{\pi i}{3}} q_1^{-\frac29} \small{\frac{\left(e^z-e^y\right) q_1^{\frac{-2 x+y+z}{6 \pi i}}+\left(e^x-e^z\right) q_1^{\frac{x-2 y+z}{6 \pi i}}+\left(e^y-e^x\right) q_1^{\frac{x+y-2 z}{6 \pi i}}}{\Big(1-q_1^{\frac{x-y}{2 \pi i}}\Big) \Big(1-q_1^{\frac{z-x}{2 \pi i}}\Big) \Big(1-q_1^{\frac{y-z}{2 \pi i}}\Big)}\left(1+O(q_1^{\frac13})\right)}\tag{4} \\ \end{align} Eq. $(2)$ is a condition that the difference of LHS and RHS of $(5)$ is an entire function. $(3)$ has been extracted from numerical calculations. $(4)$ has been found from exact $q$-series representation of the integral assuming $\beta_j\in\mathbb{R}$. However numerical calculations show that asymptotics $(4)$ holds if all differences $|\text{Im}~(\beta_j-\beta_k)|\leq \frac{2\pi}{3}$, and one can check that $(4)$ is consistent with $(2)$. Q: Can anybody make a good guess from these data $1-4$ what this function $f_q(x,y,z)$ might be? A: The function $$ f_q(x,y,z)=\sum_{cyc}e^z\frac{\theta_q\left(e^{\frac{2 \pi i}{3}+x-z}\right) \theta_q\left(e^{\frac{2 \pi i}{3}+y-z}\right)}{\theta_q\left(e^{x-z}\right) \theta_q\left(e^{y-z}\right)} $$ satisfies all $4$ conditions and also has been confirmed numerically.
[ "stackoverflow", "0011887910.txt" ]
Q: Proper way to denote array data type for phpDocumentor? Which of the following is the proper way to document the return type of this method for phpDocumentor? Method 1: /** * @return array Foo array. */ public function foo() { return array(1, 2, 3); } Method 2: /** * @return integer[] Foo array. */ public function foo() { return array(1, 2, 3); } Also, are there any IDE implications from either method? Edit: It appears that both PhpStorm and Netbeans 7.1+ IDEs support the 2nd method. A: Both methods are technically correct, but this one is considered 'better' because it's more specific (int and integer are interchangeable): @return int[] Documented here: http://www.phpdoc.org/docs/latest/guides/types.html A: At the moment of writing this answer, these are the accepted ways of phpDocumentor (and probably other PHPDoc implementations) to denote an array: unspecified, no definition of the contents of the represented array is given. Example: @return array specified containing a single type, the Type definition informs the reader of the type of each array element. Only one Type is then expected as element for a given array. Example: @return int[] Please note that mixed is also a single type and with this keyword it is possible to indicate that each array element contains any possible type. specified containing multiple types, the Type definition informs the reader of the type of each array element. Each element can be of any of the given types. Example: @return (int|string)[]
[ "stackoverflow", "0057835150.txt" ]
Q: How to extract only article body from knowledge graph api in php? I am trying to get only the article body from json-ld in php but i can't understand how. I'm not too familiar with encoding and decoding json from php, so nothing seems to work. "@context": { "@vocab": "http://schema.org/", "goog": "http://schema.googleapis.com/", "resultScore": "goog:resultScore", "detailedDescription": "goog:detailedDescription", "EntitySearchResult": "goog:EntitySearchResult", "kg": "http://g.co/kg" }, "@type": "ItemList", "itemListElement": [ { "@type": "EntitySearchResult", "result": { "@id": "kg:/m/0dl567", "name": "Taylor Swift", "@type": [ "Thing", "Person" ], "description": "Singer-songwriter", "image": { "contentUrl": "https://t1.gstatic.com/images?q=tbn:ANd9GcQmVDAhjhWnN2OWys2ZMO3PGAhupp5tN2LwF_BJmiHgi19hf8Ku", "url": "https://en.wikipedia.org/wiki/Taylor_Swift", "license": "http://creativecommons.org/licenses/by-sa/2.0" }, "detailedDescription": { "articleBody": "Taylor Alison Swift is an American singer-songwriter and actress. Raised in Wyomissing, Pennsylvania, she moved to Nashville, Tennessee, at the age of 14 to pursue a career in country music. ", "url": "http://en.wikipedia.org/wiki/Taylor_Swift", "license": "https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License" }, "url": "http://taylorswift.com/" }, "resultScore": 896.576599 } ] } I only need the article body which is "Taylor Alison Swift is an American singer-songwriter and actress...". How do i achieve this? A: You have to decode this string with json_decode then it's just picking up your needs from an array. E.g. $j = '{"@context": {"@vocab": "http://schema.org/", "goog": "http://schema.googleapis.com/", "resultScore": "goog:resultScore" }}'; $arr = json_decode($j, true); echo $arr['@context']['goog']; For articleBody it should be: $arr['itemListElement'][0]['result']['detailedDescription']['articleBody']
[ "stackoverflow", "0018883695.txt" ]
Q: Creating arrow key navigation in a command line application? I'm trying to dynamically generate a list from file names in a directory using Ruby. I already have all the code, but my problem is the user interface. In programs such as "testdisk" and "photorec", menu navigation is done via the arrow keys and the enter key alone, without having to type out the name of the option. Is there a way to reproduce this behavior in a Ruby program? A: Ruby Toolbox is a great resource for finding gems that you can use, the link here pointing toward the search for 'curses'. ncurses should work with any ANSI/Posix compliant system.
[ "pt.stackoverflow", "0000140853.txt" ]
Q: Utilizar o mesmo jFormattedTextField para máscara de CPF e CNPJ Gostaria de saber se é possível em um mesmo JFormattedTextField, alternar máscara para CPF e CNPJ. Quando eu uso a máscara do JFormattedTextField o valor já fica estático, e se colocar pra o CPF, não caberá o CNPJ e caso coloque no padrão do CNPJ, o CPF vai ficar desconfigurado. O que venho tentando fazer são 2 checkBoxes, cada um com sua respectiva distinção e quando selecionados, aplicam a máscara correta. Porém não está limpando, depois que seleciono alguma máscara. O código pra inserir a máscara que estou usando é: if (jCheckBox1.isSelected()) { try { MaskFormatter format = new MaskFormatter("##.###.###/####-##"); format.install(jFormattedTextField1); } catch (ParseException ex) { Logger.getLogger(FormTeste.class.getName()).log(Level.SEVERE, null, ex); } } A: Você quer alterar em tempo de execução a máscara do campo, só que o install aparentemente não funciona, mas de acordo com essa resposta, você precisa alterar pela chamada do setFormatterFactory(), onde for necessário. No seu exemplo, eu sugeriria mudar para JRadioButton para não correr risco de conflito das máscaras. Você cria um grupo, adiciona os radiobuttons nele, dessa forma, somente será possivel selecionar um item por vez, evitando o problema citado no parágrafo anterior. ButtonGroup radioGroup = new ButtonGroup(); radioGroup.add(radioButtonCPF); radioGroup.add(radioButtonCNPJ); Também é interessante criar as máscaras antes de usá-las, pra que o tratamento da exceção do ParseException ocorra uma vez apenas. private MaskFormatter CNPJMask; private MaskFormatter CPFMask; //... try { CNPJMask = new MaskFormatter("##.###.###/####-##"); CPFMask = new MaskFormatter("###.###.###-##"); } catch (ParseException ex) { ex.printStackTrace(); } Depois, basta adicionar um ItemListener em cada RadioButton, e dentro do intemStateChanged, verificar se ele foi checado: radioButtonCPF.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { fmtField.setValue(null); fmtField.setFormatterFactory(new DefaultFormatterFactory(CPFMask)); } } }); radioButtonCNPJ.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { fmtField.setValue(null); fmtField.setFormatterFactory(new DefaultFormatterFactory(CNPJMask)); } } }); O fmtField.setValue(null); precisa ser chamado antes de aplicar a máscara, pois se tiver algum conteúdo no campo, a troca não é realizada. A consequência disso é que, cada vez que a troca é efetuada, o que foi digitado será perdido. Dá pra melhorar, mas o exposto já está bem simplificado. Segue um exemplo executável da aplicação de troca de mascaras, caso queira ver funcionando antes de alterar seu código: import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.text.ParseException; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.JFormattedTextField; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.border.EmptyBorder; import javax.swing.text.DefaultFormatterFactory; import javax.swing.text.MaskFormatter; public class ChoiceMaskTextFormattedFieldTest extends JFrame { private static final long serialVersionUID = 1L; private JPanel contentPane; private JFormattedTextField fmtField; private JRadioButton radioButtonCNPJ; private JRadioButton radioButtonCPF; private MaskFormatter CNPJMask; private MaskFormatter CPFMask; public static void main(String[] args) { EventQueue.invokeLater(() -> { new ChoiceMaskTextFormattedFieldTest().setVisible(true); }); } public ChoiceMaskTextFormattedFieldTest() { initComponents(); } public void initComponents() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setPreferredSize(new Dimension(190, 250)); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS)); fmtField = new JFormattedTextField(); radioButtonCPF = new JRadioButton(); radioButtonCNPJ = new JRadioButton(); radioButtonCPF.setText("CPF"); radioButtonCNPJ.setText("CNPJ"); // adiciona os radiobuttons no groupbutton // pra que apenas um seja selecionavel ButtonGroup radioGroup = new ButtonGroup(); radioGroup.add(radioButtonCPF); radioGroup.add(radioButtonCNPJ); // cria as mascaras e já a deixa pronta pra uso try { CNPJMask = new MaskFormatter("##.###.###/####-##"); CPFMask = new MaskFormatter("###.###.###-##"); } catch (ParseException ex) { ex.printStackTrace(); } // adiciona um listener aos radiobuttons radioButtonCPF.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { fmtField.setValue(null); fmtField.setFormatterFactory(new DefaultFormatterFactory(CPFMask)); } } }); radioButtonCNPJ.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { fmtField.setValue(null); fmtField.setFormatterFactory(new DefaultFormatterFactory(CNPJMask)); } } }); contentPane.add(fmtField); contentPane.add(Box.createVerticalStrut(30)); contentPane.add(radioButtonCPF); contentPane.add(radioButtonCNPJ); contentPane.add(Box.createVerticalStrut(100)); pack(); } }
[ "ru.stackoverflow", "0000409486.txt" ]
Q: Получение this от начальной функции Здравствуйте. Есть вот такая функция: function test(test) { this.test = test; $('#test').click(function(){ alert(this.test); }); } Подскажите, пожалуйста, как получить this.test, который мы передали при вызове? Вот пример на jsfiddle. A: Сделать лексическое замыкание на тот this: function test(test) { this.test = test; var that = this; // замкнулись $('#test').click(function(){ alert(that.test); }); } Форк Вашего примера на jsfiddle
[ "stackoverflow", "0022678016.txt" ]
Q: File I/O Basics I'm working on a school programming lab and I've gotten stuck. The book is not too helpful in teaching how to format I/O properly, or at least I'm not understanding it properly. I need a bit of help getting on with the next steps, but here's the full requirements of the program I'm supposed to be making: A hotel salesperson enters sales in a text file. Each line contains the following, separated by semicolons: The name of the client, the service sold (such as Dinner, Conference, Lodging, and so on), the amount of the sale, and the date of that event. Write a program that reads such a file and displays the total amount for each service category. Display an error if the file does not exist or the format is incorrect. In addition to the program specifications listed, your program should both print the results as well assend the results to a separate output file. Example of input.txt: Elmer Fudd;Lodging;92.00;11-01-2014 Elmer Fudd;Conference;250.00;11-02-2014 Daffy Duck;Dinner;19.89;11-02-2014 Daffy Duck;Conference;275.00;11-02-2014 Mickey Mouse;Dinner;22.50;11-02-2014 Mickey Mouse;Conference;275.00;11-02-2014 I'm currently stuck on figuring out how to get the file properly loaded and formatted, which I think I did right, but then my professor suggested breaking each into it's own line, but nowhere in my book does it clearly tell how to do that. Just to be clear, I'm not looking for a coding miracle, I just would like someone to help guide me in the right direction as to what I should do next. Possibly a better way to handle this situation in a nicely detailed guide? Nothing fancy though. Thank you in advance, and here's my current code. import java.util.*; import java.io.*; public class Sales { public static void main(String[] args) throws FileNotFoundException { File inputFile = new File("input.txt"); Scanner in = new Scanner(inputFile); PrintWriter out = new PrintWriter("output.txt"); double dinnerTotal = 0; double conferenceTotal = 0; double lodgingTotal = 0; Scanner lineScanner = new Scanner(inputFile); lineScanner.useDelimiter(";"); while (lineScanner.hasNext()) { String line = in.nextLine(); //Here's where I'm really stuck System.out.print(line); //Not to say I'm not stumped all over. } in.close(); out.close(); lineScanner.close(); } } From what Jason said, I'm at this now: import java.util.*; import java.io.*; public class Sales { public static void main(String[] args) throws FileNotFoundException { File inputFile = new File("input.txt"); Scanner in = new Scanner(inputFile); PrintWriter out = new PrintWriter("output.txt"); double dinnerTotal = 0; double conferenceTotal = 0; double lodgingTotal = 0; while (in.hasNext()) { String line = in.nextLine(); String[] parts = line.split(";"); if(parts[1].equals("Conference")) { conferenceTotal += Double.parseDouble(parts[2]); } else if(parts[1].equals("Dinner")) { dinnerTotal += Double.parseDouble(parts[2]); } else if(parts[1].equals("Lodging")) { lodgingTotal += Double.parseDouble(parts[2]); } } in.close(); out.close(); } } A: Stick to one scanner. Read each line in total, rather than breaking on the ';'. Then use String.split() to break the line of text apart at the ';' separator. Then check the second part (zero based index) to retrieve the service category and add the value in the third part to the relevant total. String line = in.nextLine(); String[] parts = line.split(";"); if(parts[1].equals("Conference")) { conferenceTotal += Double.parseDouble(parts[2]); } else if(parts[1].equals("Dinner")) { dinnerTotal += Double.parseDouble(parts[2]); } else if(parts[1].equals("Lodging")) { lodgingTotal += Double.parseDouble(parts[2]); }
[ "stackoverflow", "0034132891.txt" ]
Q: Update or add data on nested array in mongodb I am new to mongodb. I want to update or add a new array value on existing document. My input is: { "_id" : "Tx8Yo3FJC7WpqNpGs", "sharedId" : "LnkvSu8zdaahHjQmu", "data" : [{ "ownerId" : "100", "taskId" : 1000, "taskName" : "trip" },{ "ownerId" : "100", "taskId" : 2000, "taskName" : "meeting" }] } if ownerId or taskId is same just update. if ownerId or taskId is different add to current array. Expected output is: { "_id" : "Tx8Yo3FJC7WpqNpGs", "sharedId" : "LnkvSu8zdaahHjQmu", "data" : [{ "ownerId" : "100", "taskId" : 1000, "taskName" : "trip" },{ "ownerId" : "100", "taskId" : 2000, "taskName" : "meeting" },{ "ownerId" : "100", "taskId" : 3000, "taskName" : "games" } ] } I have tried this but did not get success. SharedTask.update({ sharedId: sharedToIds, data: { ownerId: userId, taskId: taskId }, }, { $push: { data: [{ 'ownerId': userId, 'taskId': taskId, 'taskName': taskName }] } }, { upsert: true }); A: Make use of $addToSet The $addToSet operator adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array. SharedTask.update({ sharedId: sharedToIds, }, { $addToSet: { data: { 'ownerId': userId, 'taskId': taskId, 'taskName': taskName } },{ upsert: true } }); $push changed to $addToSet data value was array, changed to single object
[ "math.stackexchange", "0001170331.txt" ]
Q: Polynomial division challenge Let $x,y,n \in \mathbb{Z} \geq 3$, Find $A,B$ such that $$x^{n-1}+x^{n-2}y+x^{n-3}y^2+\cdots+x^2y^{n-3}+xy^{n-2}+y^{n-1}= A(x^2+xy+y^2)+B$$ What is the best method to approach this? A: If $n=3m$, where $m\in\mathbb{Z}$, then the polynomial is exactly divisible by $x^2+xy+y^2$, and the result (using polynomial long division, see image below for some old fashioned pen and paper working) is $$A=\sum_{k=0}^{m-1}x^{n-3-3k}y^{3k}$$ while $B=0$. For the other two cases, when $n=3m+1$ the remainder $B=y^{n-1}$, and for $n=3m+2$ we have $B=xy^{n-1}+y^n$ - the polynomial $A$ being same of the form, for these two cases $$A=\sum_{k=0}^{m-1}x^{n-3-3k}y^{3k}$$ An alternative notation for the summation index for $A$ for all three cases (in terms of $n$) is as follows, making use of the floor function:- $$A=\sum_{k=0}^{\left\lfloor\frac{n}{3}\right\rfloor-1}x^{n-3-3k}y^{3k}$$
[ "stats.stackexchange", "0000449955.txt" ]
Q: What is the actual distribution that we are modelling in case of a Bayesian Regression Model? I have come across blog posts that speak about modelling a regression problem using Bayesian approaches. I completely understand that, to set up example data, they generate a sine wave using a one dimensional data $X$ and then add Gaussian noise around the $Y_i$ value for every $X_i$ and consider this as a training data. Now, when we say we are going to determine the parameters of a probability distribution which generated our data, which data are we referring to? Are we modelling the parameters of the distribution that generated $X$ or are we talking of generating $Y$? A: In Bayesian inference we typically are interested in the conditional distribution of our parameters $\theta$ given data. In the case of regression, we condition on our predictors $X$ and outcomes $y$. Given known Gaussian noise with known variance, this reduces to inferring the conditional distribution of regression coefficients $\beta$ given the data $X,y$: $$ p(\beta|X,y) \propto p(y|\beta,X) p(\beta) $$ Since in linear regression $y \sim N(X\beta, \sigma^2)$, $p(y|\beta, X)$ is the likelihood of a normal distribution. $p(\beta)$ is the prior for regression coefficients, often inverse gamma. Thus we are interested in the probability distribution over the parameters that generated $y$ given $X$.
[ "stackoverflow", "0032486820.txt" ]
Q: Posting JSON to Flask view using Requests returns 404 I want to post JSON data to a Flask view using Requests. However, I get a 404 when I make the request. Why isn't my code working? How do I correctly post JSON data? @app.route('/foo/<foo>', defaults={'foo': 'foo'}) @app.route('/foo/<foo>') def foo(foo): print "here" data = request.get_json(force=True) print data k = data.get('k', 20) return jsonify(k=k, foo=foostatus='ok') import requests params = {'k': 2} d = requests.get('http://localhost:9090/foo', params=params) Flask logs a 404 for the request. 127.0.0.1 - - [09/Sep/2015 11:26:26] "GET /foo?k=2 HTTP/1.1" 404 - A: Issue a post request with JSON data, not a get request with query parameters. The route needs to allow the POST method as well. The 404 is because you are not going to a pattern matching /foo/<foo>. Change the route with the default to exclude <foo>, or go to the correct url. You do not need to use force=True with get_json when the request has the correct mimetype. The syntax foo=foostatus='ok' in your jsonify call is invalid. Passing a status value is redundant, since a 200 response code implies it. @app.route('/hello', defautls={'name': 'world'}, methods=['POST']) @app.route('/hello/<name>', methods=['POST']) def hello(name): print(name) # will be 'world' when going to bare /foo data = request.get_json() k = data.get('k', 20) return jsonify(k=k, status='ok') requests.post('http://localhost/hello', json={'k': 2})
[ "travel.stackexchange", "0000005303.txt" ]
Q: How to visit Malbork Castle from Gdansk? I'm wondering how I can visit Malbork Castle if I'm visiting Gdansk. Wikitravel says that Malbork is 1.5 hours from Gdansk by train, but doesn't say how much the train is and if it's allowed to go inside the castle and how much admission is. The question is: if I'm in Gdansk, what should be my budget to visit Malbork castle and return to Gdansk? Also, is it possible to go and return in a morning or do I need the whole day? Image is under Creative Commons license (MediaWiki) A: The website is great for train schedules. It shows the quickest trip to Malbork from the main station in Gdansk is 53 minutes, and 8 zloty is about 2 Euro. Malbork castle is huge so allow a few hours, and it is well worth getting a guide because there is so much you will miss otherwise. A guided tour takes about two and a half hours. A: The ticket prices for Malbork castle you can find here. There are a lot of different tickets available, for example, with or without guide, only the interior or also the exterior building, etc. When we were there this summer, we went through the whole castle inside and outside without a guide. It took approximately 2 hours. We arrived in late afternoon. So I would guess that you should be able to do it in one morning if you're there in time. During winter season the castle opens at 10. This tourist information site says the train ticket is 8 zloty each way. (But they also say the train takes only 45 minutes). A: In Your Pocket has a mini-guide to Malbork, including all the info you need about getting there and back, what to do/see, etc. It's comprehensive.
[ "ru.stackoverflow", "0000955881.txt" ]
Q: Расположение поля toast У меня есть метод, который показывает сообщение об ошибке. Сейчас поле вылезает в самом верху по середине, а как сделать, чтобы оно вылезало немного ниже самого верха и так же посередине? public void oshibka () { Toast problem = Toast.makeText(MainActivity.this, ss, Toast.LENGTH_SHORT); problem.setGravity(Gravity.TOP, 0, 0); problem.show(); } A: Вы пишете Gravity.TOP, поэтому и в самом верху. Напишите Gravity.CENTER (будет в середние экрана) и подберите вручную оффсет, который вам нужен. Например, так: problem.setGravity(Gravity.TOP, 0, 20); Возможные значения параметра Gravity: документация. Неудобства метода setGravity: в качестве оффсета он принимает целые числа, которые обозначают число пикселей. Поэтому вертикальный оффсет 200 на экране 480x800 будет четверть экрана, а на экране 2160х3840 эти 200 пикселей и не заметишь. Можно использовать метод setMargin(). Он задает относительное смещение тоста. Эти параметры выведут тостер ниже середины экрана: problem.setMargin(0, (float) 0.33);
[ "workplace.stackexchange", "0000042497.txt" ]
Q: How to ask to be relocated for internship I recently received an internship offer from a major bank for software development. I'm very excited to have the opportunity to work for them. HR called me this Friday to discuss the details of the offer. Unfortunately, my cell phone was about to die so I have decided to call them back on Monday. The problem is that one of the internship locations is in a city I do not want to stay in for the summer. I interviewed at one of the satellite offices in the city I go to college in. It's a great city, but I would really like to intern at their headquarters in New York City. I am considering moving to NYC after I graduate so it would be great to experience the city for a summer. How do I mention to HR how I want to relocate? I do not want to seem unappreciative because I assume they would want me to do the internship in the city I interviewed in. I was thinking of mentioning how I would like to be closer to family (I live in Boston), but thought that would sound weird. How should I approach this? A: And they probably assume that you want to intern in the city they interviewed you in. Just ask. Worst case, they say no. I don't think you should make up an excuse. I think you should just say that you are considering moving to NYC after graduation. Aka the truth.
[ "stackoverflow", "0050118837.txt" ]
Q: Using Font Awesome with Bootstrap 4 A Major problem I found while developing with Bootstrap 4 and trying to create a Font Awesome button that when I create a series of buttons, I get different size buttons, the only way to get the same size buttons is to use the same font for each one So the problem is due to Font Awesome sizes is not the same for every one. <a class="btn btn-outline-warning" type="button" href="#"> <i class="fa fa-edit"></i> </a> <a class="btn btn-outline-danger" type="button" href="#"> <i class="fa fa-trash"></i> </a> Does one have a practical exemple to get Off this problem ? A: While you can certainly manually adjust the font size of your Font Awesome icons, I would suggest a less dramatic approach: .fa-fw. This is a utility class that is part of Font Awesome's stylesheet that helps unify the width of your fonts. Per the 4.7.0 documentation: Use fa-fw to set icons at a fixed width. Great to use when different icon widths throw off alignment. Especially useful in things like nav lists & list groups. <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" type="text/css" rel="stylesheet"> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"></script> <script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> <a class="btn btn-outline-warning" href="#"> <i class="fa fa-fw fa-edit"></i> </a> <br> <a class="btn btn-outline-danger" href="#"> <i class="fa fa-fw fa-trash"></i> </a> <br> <a class="btn btn-outline-success" href="#"> <i class="fa fa-fw fa-wrench"></i> </a> <br> <a class="btn btn-outline-info" href="#"> <i class="fa fa-fw fa-stop"></i> </a> In the above example you can see how .fa-fw has adjusted your icon spacing and everything looks the same. You might notice though that I did also remove type="button" from your anchor tag as this was resulting in Bootstrap not applying the full CSS of the ban-outline-* you were declaring.
[ "gaming.stackexchange", "0000223378.txt" ]
Q: Can I recover a Skyrim saved game from a condemned computer? My computer is affected by a virus and so is Skyrim. Can I copy the saved game file, put it on a pendrive, and play Skyrim from the last saved point after formatting the whole computer? Will this trick work or is the saved game file also affected by the virus? A: Yes, you can copy your save across to another machine/the same machine after reformatting. However, if you've plugged a USB drive into an infected computer, chances are the drive itself could have been infected too. I would highly recommend creating an Antivirus LiveCD, booting your computer from it and checking the USB drive and saved files, before plugging the USB drive into anything else at all. You may find you can also repair/recover your computer using the LiveCD, however if you have any questions on that, you're probably better off asking on our sister site Super User.