qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
2,055
I don't know if I should ask this here because the question is more like a sociology one. Anyway, I will give it a try, since most of the sociologists are also philosophers, so maybe I'll be lucky finding an answer. I am preparing for an exam, and I understand really well Lévi-Strauss's structuralism and I also understand well functionalism(Malinowski). My problem is that later on in the book I have a question that asks me to explain what Structural-Functionalism is. I don't know how to answer that: -Is that the same as just functionalism or is it a new point of view? -Could you define or explain it a little bit for me please? Please don't just give me a link to Wikipedia, because I've already been there and was not helpful to me.
2012/01/06
[ "https://philosophy.stackexchange.com/questions/2055", "https://philosophy.stackexchange.com", "https://philosophy.stackexchange.com/users/1342/" ]
Malinowski suggested that individuals have physiological needs (reproduction, food, shelter) and that social institutions exist to meet these needs. There are also culturally derived needs and four basic "instrumental needs" (economics, social control, education, and political organization), that require institutional devices. Each institution has personnel, a charter, a set of norms or rules, activities, material apparatus (technology), and a function. Malinowski argued that uniform psychological responses are correlates of physiological needs. He argued that satisfaction of these needs transformed the cultural instrumental activity into an acquired drive through psychological reinforcement (Goldschmidt 1996:510; Voget 1996:573). Radcliffe-Brown focused on social structure rather than biological needs. He suggested that a society is a system of relationships maintaining itself through cybernetic feedback, while institutions are orderly sets of relationships whose function is to maintain the society as a system. Radcliffe-Brown, inspired by Augustus Comte, stated that the social constituted a separate "level" of reality distinct from those of biological forms and inorganic matter. Radcliffe-Brown argued that explanations of social phenomena had to be constructed within the social level. Thus, individuals were replaceable, transient occupants of social roles. Unlike Malinowski's emphasis on individuals, Radcliffe-Brown considered individuals irrelevant (Goldschmidt 1996:510).
Malinowski concentrated much on the biological needs or the primary needs of the individual and how the sociocultral or the social institutions exist to meet those needs.Simply means culture exists to meet biological needs.Also humans can never live without culture since it is there to satisfy biologiacal needs.Much on the individual Brown emphasis on the society as a whole.society as an organism which consists of various parts and these parts are interrelated and interdepedent to work together as a whole for the development or the survival of the society.Much on the society
29,298,549
I would like to confirm the correct use of the following: 1) Use a global variable to get return values from a function only once (since my function will be returning some Sequence values) 2) Use that variable inside a cursor multiple times 3) All of these will be inside a procedure Below shows a sample. ``` CREATE OR REPLACE Procedure insert_myTable is --declare variables for insert v_firstNO VARCHAR2(10); v_secondNO VARCHAR2(6); --declare variable to store the sequence number var_ASeqno varchar2(6); -- Validation v_check VARCHAR2 (10 Byte); v_table_name varchar2(50):='myTable'; cursor c1 is select distinct firstNO, secondNO from (SELECT hdr.someNum firstNO, -- using variable to assign the sequence no var_ASeqno secondNO FROM someOtherTable hdr WHERE -- some condition union SELECT hdr.someNum firstNO, -- using variable to assign the sequence no var_ASeqno secondNO FROM someOtherTable hdr WHERE -- some other conditions union SELECT hdr.someNum firstNO, -- using variable to assign the sequence no var_ASeqno secondNO FROM someOtherTable hdr WHERE -- some other other conditions begin if c1%isopen then close c1; end if; v_check:=null; FOR i IN c1 LOOP --assign variables for insert v_firstNO := i.firstNO ; v_secondNO := i.secondNO ; begin -- calling the Function aSeqNoFunc and assign the --Sequence Number into the variable var_ASeqno var_ASeqno := aSeqNoFunc(); select firstNO into v_check from myTable a where firstNO = i.firstNO and secondNO =i.secondNO; exception when no_data_found then --insert into target table INSERT INTO myTable (firstNO, secondNO) values (v_firstNO, v_secondNO); end ; end loop; end; ``` As can be seen, the function 'aSeqNoFunc' is called before the Insert near the end. The values are assigned to the variable 'var\_ApmSeqno' which in turn is used three times inside the cursor. Thank you.
2015/03/27
[ "https://Stackoverflow.com/questions/29298549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2828435/" ]
A few suggestions: 1. You have an `END;` statement after the declaration of `cursor c1` which doesn't match up with anything. You should remove this from your code. 2. There's no need to check to see if the cursor is open when you enter the procedure. It won't be. Even better, don't use an explicit cursor declaration - use a cursor FOR-loop. 3. Use UNION ALL instead of UNION unless you know what the difference between the two is. ([And go read up on that](http://docs.oracle.com/cd/B28359_01/server.111/b28286/queries004.htm#SQLRF52323). 99.9% of the time you want UNION ALL...). 4. However, as it appears that all the rows are being selected from the same table you may be able to eliminate the UNION's altogether, as shown below. 5. There's no benefit to assigning NULL to a variable at the beginning of a function. Variables are initialized to NULL if there's no other explicit initialization value given. 6. IMO there's no benefit to having a function which returns the next value from a sequence. It just makes understanding the code more difficult. Get rid of `FUNCTION aSeqNoFunc` and just invoke `SOME_SEQUENCE.NEXTVAL` where appropriate - so in the above I suggest you use `var_ASeqno := SOME_SEQUENCE.NEXTVAL`. 7. You need to assign the value to `var_ASeqno` before cursor `c1` is opened. As written above`var_ASeqno` will be null at the time the cursor is opened, so the cursor will probably not return what you expect. But more to the point I don't see that there's any reason to have the cursor return the value of `var_ASeqno`. Just use the value of `var_ASeqno` in your INSERT statements or wherever else they're needed. 8. Use a MERGE statement to insert data if it doesn't already exist. This avoids the awkward "SELECT...catch the NO\_DATA\_FOUND exception...INSERT in the exception handler" logic. 9. And as @boneist points out in her comment, by the time we've gone this far there's really no point to the cursor. You might as well just use the MERGE statement to perform the INSERTs without using a cursor. So I'd try rewriting this procedure as: ``` CREATE OR REPLACE Procedure insert_myTable is begin MERGE INTO MYTABLE m USING (SELECT FIRSTNO, SOME_SEQUENCE.NEXTVAL AS SECONDNO FROM (SELECT DISTINCT hdr.someNum AS FIRSTNO FROM someOtherTable hdr WHERE (/* some condition */) OR (/* some other conditions */) OR (/* some other other conditions */))) d ON d.FIRSTNO = m.FIRSTNO AND d.SECONDNO = m.SECONDNO WHEN NOT MATCHED THEN INSERT (FIRSTNO, SECONDNO) VALUES (d.FIRSTNO, d.SECONDNO); end INSERT_MYTABLE; ```
Taking into account the fact that you want all the rows being inserted to have the same sequence number assigned, I think you could probably rewrite your procedure to something like: ``` create or replace procedure insert_mytable is v_seq_no number; begin v_seq_no := somesequence.nextval; merge into mytable tgt using (select firstno, v_seq_no secondno from (select hdr.somenum firstno from someothertable1 hdr where -- some condition union select hdr.somenum firstno from someothertable2 hdr where -- some other conditions union select hdr.somenum firstno from someothertable3 hdr where -- some other other conditions ) ) src on (tgt.firstno = src.firstno and tgt.secondno = src.secondno) when not matched then insert (tgt.firstno, tgt.secondno) values (src.firstno, src.secondno); end insert_mytable; / ``` If this doesn't match with what you're trying to do, please edit your question to provide more information on what the aim of the procedure is. Example input and output data would be appreciated, so that we have a better idea of what you're wanting (since we can't see your table structures, data, etc). --- ETA: Info on performance considerations between set-based and row-by-row approaches. Here's a simple script to insert of a million rows, both row-by-row and as a single insert statement: ``` create table test (col1 number, col2 number); set timing on; -- row-by-row (aka slow-by-slow) approach begin for rec in (select level col1, level * 10 col2 from dual connect by level <= 1000000) loop insert into test (col1, col2) values (rec.col1, rec.col2); end loop; end; / commit; truncate table test; -- set based approach (keeping in an anonymous block for comparison purposes) begin insert into test (col1, col2) select level, level*10 from dual connect by level <= 1000000; end; / commit; drop table test; ``` Here's the output I get, when I run the above in Toad: ``` Table created. PL/SQL procedure successfully completed. Elapsed: 00:00:21.87 Commit complete. Elapsed: 00:00:01.03 Table truncated. Elapsed: 00:00:00.22 PL/SQL procedure successfully completed. Elapsed: 00:00:01.96 Commit complete. Elapsed: 00:00:00.03 Table dropped. Elapsed: 00:00:00.18 ``` Do you see the elapsed time of 21 seconds for the row-by-row approach, and 2 seconds for the set-based approach? Massive difference in performance, don't you agree? If that's not reason to consider writing your code as set based in the first instance, then I don't know what else will convince you/your boss!
21,001,672
I am creating a header with a logo and CSS menu. I want them to be both on the same line, and when I did this, I used ``` #header img, #header ul{ display:inline-block; } ``` When I was using a custom menu I made, this worked fine. However, I decided to use a CSS menu generator to design a nicer looking menu. This broke it, and I am not sure what the problem is. [JSFiddle](http://jsfiddle.net/KYMfv/) I also noticed that in the jsFiddle, my hover color for the links is not working. It works fine locally so I'm assuming this is either a jsFiddle issue or I forgot to upload something. But I just copied and pasted the whole thing so I'm not sure what that would be. Thanks!
2014/01/08
[ "https://Stackoverflow.com/questions/21001672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2070478/" ]
[Here is JsFiddle](http://jsfiddle.net/zaheerahmed/KYMfv/1/) Try add padding to header, change inline-block to inline and remove width: ``` #header { text-align:center; margin-top:0px; margin-bottom:0px; padding:10px; width:100%; } ``` to show at bottom [Here is Demo](http://jsfiddle.net/zaheerahmed/KYMfv/2/): ``` #header { text-align:center; margin-bottom:0px; padding-top:150px; padding-bottom:10px; width:100%; } #header img, #header ul{ display:inline; } ```
I couldn't view your image from your code, so I'm not sure what is exactly you wanted. But I made this simple code to make the logo and menu on the same line, whereby the menu is aligned in the middle of the height of logo/header. You can check the fiddle [HERE](http://jsfiddle.net/sJZx5/) ``` .header{ height: 100px; width: 100%; display: block; border-top: 1px solid #ccc; border-bottom: 1px solid #ccc; padding: 8px 0; overflow: hidden; } .logo{ display: inline-block; float: left; padding-left: 15px; } .menu{ float: right; list-style: none; margin: 0; text-align: right; line-height: 100px; padding-right: 15px; } .menu li{ display: inline; margin: 0 10px; } ```
4,707,690
> > **Possible Duplicate:** > > [Storing Images in DB - Yea or Nay?](https://stackoverflow.com/questions/3748/storing-images-in-db-yea-or-nay) > > > I need to store profile pictures. Lots of them. I'm not sure if I should store them in the database. I'm not even sure if that's a good idea to begin with, or if I should just store them in a separate directory on the server, and disallow access to them with HTAccess. But I'm not overly familiar with HTAccess and when I have used snippets to disallow access to a folder, it has just never worked. I am using winhost.com to host my sites, so I would assume that HTAccess would work. Can anyone suggest which way would be better for storing tens of thousands of profile pictures on a single server? I have read many blogs, forum posts etc that I've found on Google, and am a little bit more confused since half of them suggest one thing, and the other half disagree and suggest using a database would be perfectly fine.
2011/01/16
[ "https://Stackoverflow.com/questions/4707690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Personal experience says that storing lots of image in a database makes the database very slow to back up. That can be irritating when you come to run repeatable tests, or update the DB schema and you want to take an ad-hoc backup, as well as in a general case. Also, depending on database, storing blobs (which inevitably means that you're storing rows of non-fixed length) can make querying the table quite slow - although that can easily be fixed with appropriate indexing. If you store them in the filesystem and serve them directly with your webserver as you suggest, one problem you will find is how to appropriately access-control them if you want only logged-in users to see them. That will depend on the design of your application and may not be a problem. Two other options: * you can store them in the filesystem and serve them with an application page, so that it can e.g. check access control before fetching the image and sending it to the client. * you can use X-SendFile: headers if your webserver supports them to serve a file on the filesystem - the application page tells the webserver the file to fetch, and the webserver will fetch the file and send it. Potentially the application and the image files can live on different machines if you use e.g. FastCGI, and the image is never sent over the FastCGI connection. You may also want to consider cacheing - if you write any programmatic way to send the file, you'll need to add additional logic so that the image can be cached by the browser, or you'll just end up serving the image over and over again and upping your bandwidth costs.
I'd definitely root for storing only the image path in the database. Storing the image data will slow your site down and put extra strain on your system. The only case I could imagine an advantage in storing the image data inside the database would be, if you're planning on moving the site around. Then you wouldn't have to worry about filepaths etc..
5,491,376
Basically, I'm not sure where to start: I have my Shell.xaml window. I also have my Popup.xaml window. I set the Shell.xaml to import the PopupWindow then when the PopupWindow Loaded event fires, it does: ``` Popup.Owner = this; Popup.Show(); ``` Now, I need to be able to have the PopupWindow's ViewModel communicate with the Shell.xaml. Basically, I need to be able to have the PopupWindow tell the Shell's ViewModel information the user inputs. --- ### Update: In keeping this decoupled, I don't want to pass in any instance of the Client's viewmodel to the popup, I'd much rather have the Popup's ViewModel somehow have a way of communicating to the Client's ViewModel without knowing who it is actually talking to.
2011/03/30
[ "https://Stackoverflow.com/questions/5491376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/535637/" ]
Have a look at the event aggregator in Prism. The aggregated events in Prism are intended as a means of facilitating decoupled, inter-viewmodel communication. If you are going for "pure" MVVM, I *think* that it would go something like this: * Your ViewModel publishes a message (interaction request) that it want's to display a popup. * Your View is listening for the message, and shows the popup window (decouples your viewmodel from understanding how prompts are displayed) * Your ViewModel gets the results of the popup window (your popup window is just a view, and should know nothing about raising aggregate events) * Your ViewModel raises a Prism Aggregate Event (an object containing the user input is the payload) * Your shell is listening for that event.
I'm no PRISM/MEF guru but if I were attacking this problem I'd take a slightly different approach and add a tad more decoupling. Essentially you want the **ViewModels** of your windows (Shell and Popup) to communicate - windows (**Views**) should only communicate with the user and update properties (in a decoupled, model-bound fashion) on their **ViewModels**. Once you're in this position then Shell's **ViewModel** can request the user information (say from a property) of Popup's **ViewModel**. Though, of course, they are not the **ViewModels** of either Shell nor Popup - they are merely **ViewModels** that these Views happen to be bound to :) Purists would go even further and talk about message queues between the various communicating parties but one step at a time, methinks. Dan **Edit** Following Michael's comment: As I said I'm not expert in PRISM but I think it depends how far you want to go with the decoupling. There's nothing stopping the Client ViewModel creating and showing the popup and then querying the popup's ViewModel for data before disposing of it. It's not pure MVVM because your Client ViewModel is doing some fairly direct communication with the Popup and its ViewModel but it will work and it's not that big a sin. I would go with a pragmatic approach in cases such as this where a natural dependency exists anyway. You still have the separation of View and ViewModel. I imagine there are folks here who can instruct on a more decoupled approach - which I would also be interested in reading about.
34,231,571
In MATLAB, I have a 256x256 RGB image and a 3x3 kernel that passes over it. The 3x3 kernel computes the colour-euclidean distance between every pair combination of the 9 pixels in the kernel, and stores the maximum value in an array. It then moves by 1 pixel and performs the same computation, and so on. I can easily code the movement of the kernel over the image, as well as the extraction of the RGB values from the pixels in the kernel. HOWEVER, I do have trouble efficiently computing the colour-euclidean distance operation for every pair combination of pixels. For example if I had a 3x3 matrix with the following values: [55 12 5; 77 15 99; 124 87 2] I need to code a loop such that the 1st element performs an operation with the 2nd,3rd...9th element. Then the 2nd element performs the operation with the 3rd,4th...9th element and so on until finally the 8th element performs the operation with the 9th element. Preferrably, the same pixel combination shouldn't compute again (like if you computed 2nd with 7th, don't compute 7th with 2nd). Thank you in advance. EDIT: My code so far ``` K=3; s=1; %If S=0, don't reject, If S=1 Reject first max distance pixel pair OI=imread('onion.png'); Rch = im2col(OI(:,:,1),[K,K],'sliding') Gch = im2col(OI(:,:,2),[K,K],'sliding') Bch = im2col(OI(:,:,3),[K,K],'sliding') indexes = bsxfun(@gt,(1:K^2)',1:K^2) a=find(indexes); [idx1,idx2] = find(indexes); Rsqdiff = (Rch(idx2,:) - Rch(idx1,:)).^2 Gsqdiff = (Gch(idx2,:) - Gch(idx1,:)).^2 Bsqdiff = (Bch(idx2,:) - Bch(idx1,:)).^2 dists = sqrt(double(Rsqdiff + Gsqdiff + Bsqdiff)) %Distance values for all 36 combinations in 1 column [maxdist,idx3] = max(dists,[],1) %idx3 is each column's index of max value if s==0 y = reshape(maxdist,size(OI,1)-K+1,[]) %max value of each column (each column has 36 values) elseif s==1 [~,I]=max(maxdist); idx3=idx3(I); n=size(idx3,2); for i=1:1:n idx3(i)=a(idx3(i)); end [I,J]=ind2sub([K*K K*K],idx3); for j=1:1:a [M,N]=ind2sub([K*K K*K],dists(j,:)); M(I,:)=0; N(:,J)=0; dists(j,:)=sub2ind; %Incomplete line, don't know what to do here end [maxdist,idx3] = max(dists,[],1); y = reshape(maxdist,size(OI,1)-K+1,[]); end ```
2015/12/11
[ "https://Stackoverflow.com/questions/34231571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3749634/" ]
If I understood the question correctly, you are looking to form unique pairwise combinations within a sliding `3x3` window, perform euclidean distance calculations consider all three channels, which we are calling as *colour-euclidean distances* and finally picking out the largest of all distances for each sliding window. So, for a `3x3` window that has `9` elements, you would have `36` unique pairs. If the image size is `MxN`, because of the sliding nature, you would have `(M-3+1)*(N-3+1)` = `64516` (for `256x256` case) such sliding windows with 36 pairs each, and therefore the distances array would be `36x64516` sized and the output array of maximum distances would be of size `254x254`. The implementation suggested here involves [`im2col`](http://www.mathworks.com/help/images/ref/im2col.html) to extract sliding windowed elements as columns, [`nchoosek`](http://www.mathworks.com/help/matlab/ref/nchoosek.html) to form the pairs and finally performing the square-root of squared differences between three channels of such pairs and would look something like this - ``` K = 3; %// Kernel size Rch = im2col(img(:,:,1),[K,K],'sliding') Gch = im2col(img(:,:,2),[K,K],'sliding') Bch = im2col(img(:,:,3),[K,K],'sliding') [idx1,idx2] = find(bsxfun(@gt,(1:K^2)',1:K^2)); %//' Rsqdiff = (Rch(idx2,:) - Rch(idx1,:)).^2 Gsqdiff = (Gch(idx2,:) - Gch(idx1,:)).^2 Bsqdiff = (Bch(idx2,:) - Bch(idx1,:)).^2 dists = sqrt(Rsqdiff + Gsqdiff + Bsqdiff) out = reshape(max(dists,[],1),size(img,1)-K+1,[]) ```
Your question is interesting and caught my attention. As far as I understood, you need to calculate euclidean distance between RGB color values of all cells inside 3x3 kernel and to find the largest one. I suggest a possible way to do this by using `circshift` function and 4D array operations: Firstly, we pad the input array and create 8 shifted versions of it for each direction: ``` DIM = 256; A = zeros(DIM,DIM,3,9); A(:,:,:,1) = round(255*rand(DIM,DIM,3));%// random 256x256 array (suppose it is your image) A = padarray(A,[1,1]);%// add zeros on each side of image %// compute shifted versions of the input array %// and write them as 4th dimension starting from shifted up clockwise: A(:,:,:,2) = circshift(A(:,:,:,1),[-1, 0]); A(:,:,:,3) = circshift(A(:,:,:,1),[-1, 1]); A(:,:,:,4) = circshift(A(:,:,:,1),[ 0, 1]); A(:,:,:,5) = circshift(A(:,:,:,1),[ 1, 1]); A(:,:,:,6) = circshift(A(:,:,:,1),[ 1, 0]); A(:,:,:,7) = circshift(A(:,:,:,1),[ 1,-1]); A(:,:,:,8) = circshift(A(:,:,:,1),[ 0,-1]); A(:,:,:,9) = circshift(A(:,:,:,1),[-1,-1]); ``` Next, we create an array that calculates the difference for all the possible combinations between all the above arrays: ``` q = nchoosek(1:9,2); B = zeros(DIM+2,DIM+2,3,size(q,1)); for i = 1:size(q,1) B(:,:,:,i) = (A(:,:,:,q(i,1)) - A(:,:,:,q(i,2))).^2; end C = sqrt(sum(B,3)); ``` Finally, what we have is all the euclidean distances between all possible pairs within a 3x3 kernel. All we have to do is to extract the maximum values. As far as I understood, you do not consider image edges, so: ``` C = sqrt(sum(B,3)); D = zeros(DIM-2); for i = 3:DIM for j = 3:DIM temp = C(i-1:i+1,j-1:j+1); D(i-2,j-2) = max(temp(:)); end end ``` `D` is the 254x254 array with maximum Euclidean distances for A(2:255,2:255), i.e. we exclude image edges. Hope that helps. P.S. I am amazed by the shortness of the code provided by @Divakar.
1,132,567
I have a program that reads server information from a configuration file and would like to encrypt the password in that configuration that can be read by my program and decrypted. Requirments: * Encrypt plaintext password to be stored in the file * Decrypt the encrypted password read in from the file from my program Any reccomendations on how i would go about doing this? I was thinking of writing my own algorithm but i feel it would be terribly insecure.
2009/07/15
[ "https://Stackoverflow.com/questions/1132567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/104998/" ]
A simple way of doing this is to use Password Based Encryption in Java. This allows you to encrypt and decrypt a text by using a password. This basically means initializing a `javax.crypto.Cipher` with algorithm `"AES/CBC/PKCS5Padding"` and getting a key from `javax.crypto.SecretKeyFactory` with the `"PBKDF2WithHmacSHA512"` algorithm. Here is a code example (updated to replace the less secure MD5-based variant): ``` import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.AlgorithmParameters; import java.security.GeneralSecurityException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.util.Base64; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; public class ProtectedConfigFile { public static void main(String[] args) throws Exception { String password = System.getProperty("password"); if (password == null) { throw new IllegalArgumentException("Run with -Dpassword=<password>"); } // The salt (probably) can be stored along with the encrypted data byte[] salt = new String("12345678").getBytes(); // Decreasing this speeds down startup time and can be useful during testing, but it also makes it easier for brute force attackers int iterationCount = 40000; // Other values give me java.security.InvalidKeyException: Illegal key size or default parameters int keyLength = 128; SecretKeySpec key = createSecretKey(password.toCharArray(), salt, iterationCount, keyLength); String originalPassword = "secret"; System.out.println("Original password: " + originalPassword); String encryptedPassword = encrypt(originalPassword, key); System.out.println("Encrypted password: " + encryptedPassword); String decryptedPassword = decrypt(encryptedPassword, key); System.out.println("Decrypted password: " + decryptedPassword); } private static SecretKeySpec createSecretKey(char[] password, byte[] salt, int iterationCount, int keyLength) throws NoSuchAlgorithmException, InvalidKeySpecException { SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512"); PBEKeySpec keySpec = new PBEKeySpec(password, salt, iterationCount, keyLength); SecretKey keyTmp = keyFactory.generateSecret(keySpec); return new SecretKeySpec(keyTmp.getEncoded(), "AES"); } private static String encrypt(String property, SecretKeySpec key) throws GeneralSecurityException, UnsupportedEncodingException { Cipher pbeCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); pbeCipher.init(Cipher.ENCRYPT_MODE, key); AlgorithmParameters parameters = pbeCipher.getParameters(); IvParameterSpec ivParameterSpec = parameters.getParameterSpec(IvParameterSpec.class); byte[] cryptoText = pbeCipher.doFinal(property.getBytes("UTF-8")); byte[] iv = ivParameterSpec.getIV(); return base64Encode(iv) + ":" + base64Encode(cryptoText); } private static String base64Encode(byte[] bytes) { return Base64.getEncoder().encodeToString(bytes); } private static String decrypt(String string, SecretKeySpec key) throws GeneralSecurityException, IOException { String iv = string.split(":")[0]; String property = string.split(":")[1]; Cipher pbeCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); pbeCipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(base64Decode(iv))); return new String(pbeCipher.doFinal(base64Decode(property)), "UTF-8"); } private static byte[] base64Decode(String property) throws IOException { return Base64.getDecoder().decode(property); } } ``` One problem remains: Where should you store the password that you use to encrypt the passwords? You can store it in the source file and obfuscate it, but it's not too hard to find it again. Alternatively, you can give it as a system property when you start the Java process (`-DpropertyProtectionPassword=...`). The same issue remains if you use the KeyStore, which also is protected by a password. Basically, you will need to have one master password somewhere, and it's pretty hard to protect.
The big point, and the elephant in the room and all that, is that *if your application can get hold of the password, then a hacker with access to the box can get hold of it too!* The only way somewhat around this, is that the application asks for the "master password" on the console using Standard Input, and then uses this to decrypt the passwords stored on file. Of course, this completely makes is impossible to have the application start up unattended along with the OS when it boots. However, even with this level of annoyance, if a hacker manages to get root access (or even just access as the user running your application), he could dump the memory and find the password there. **The thing to ensure, is to not let the entire company have access to the production server (and thereby to the passwords), and make sure that it is impossible to crack this box!**
409,305
A similar question was asked at [Partial upgrade - why remove MariaDB?](https://askubuntu.com/questions/292245/partial-upgrade-why-remove-mariadb). The answer to that question basically was stating that dist-upgrade is the issue. This question is asking if there is some workaround (or fix). Sometimes it is necessary to do a dist-upgrade and not just an upgrade. Can we change something in our sources.list (or elsewhere) to tell Ubuntu to NOT remove MariaDB? ![removing maria db on dist-upgrade](https://i.stack.imgur.com/LeU7i.png) ``` marc@db01:~$ dpkg --get-selections | grep mysql libdbd-mysql-perl install libmysqlclient18 install mysql-common install marc@db01:~$ dpkg --get-selections | grep maria libmariadbclient18 install mariadb-client-10.0 deinstall mariadb-client-5.5 install mariadb-client-core-5.5 install mariadb-common install mariadb-server install mariadb-server-10.0 deinstall mariadb-server-5.5 install mariadb-server-core-5.5 install marc@db01:~$ sudo apt-get check Reading package lists... Done Building dependency tree Reading state information... Done marc@db01:~$ dpkg --list | grep mysql ii libdbd-mysql-perl 4.020-1build2 Perl5 database interface to the MySQL database ii libmysqlclient18 5.5.34+maria-1~precise Virtual package to satisfy external depends ii mariadb-common 5.5.34+maria-1~precise MariaDB database common files (e.g. /etc/mysql/conf.d/mariadb.cnf) ii mysql-common 5.5.34+maria-1~precise MariaDB database common files (e.g. /etc/mysql/my.cnf) marc@db01:~$ sudo apt-get dist-upgrade -o Debug::pkgProblemResolver=true -o Debug::pkgProblemResolver::ShowScores=true Reading package lists... Done Building dependency tree Reading state information... Done Calculating upgrade... Starting Settings used to calculate pkgProblemResolver::Scores:: Important => 3 Required => 2 Standard => 1 Optional => -1 Extra => -2 Essentials => 100 InstalledAndNotObsolete => 1 Depends => 1 Recommends => 1 AddProtected => 10000 AddEssential => 5000 Show Scores 10000 linux-image-3.8.0-29-generic [ amd64 ] < 3.8.0-29.42~precise1 > ( kernel ) 6306 dpkg [ amd64 ] < 1.16.1.2ubuntu7.2 > ( admin ) 5409 libc-bin [ amd64 ] < 2.15-0ubuntu10.5 > ( libs ) 5371 debianutils [ amd64 ] < 4.2.1ubuntu2 > ( utils ) 53 libsqlite3-0 [ amd64 ] < 3.7.9-2ubuntu1.1 > ( libs ) 10 mariadb-common [ amd64 ] < 5.5.34+maria-1~precise > ( database ) 8 mysql-common [ amd64 ] < 5.5.34+maria-1~precise -> 5.5.35-0ubuntu0.12.04.1 > (database ) 6 libmariadbclient18 [ amd64 ] < 5.5.34+maria-1~precise > ( libs ) 6 libmysqlclient18 [ amd64 ] < 5.5.34+maria-1~precise -> 5.5.35-0ubuntu0.12.04.1 > ( libs ) 2 mariadb-client-5.5 [ amd64 ] < 5.5.34+maria-1~precise > ( misc ) 2 mariadb-server-core-5.5 [ amd64 ] < 5.5.34+maria-1~precise > ( misc ) 2 mariadb-client-core-5.5 [ amd64 ] < 5.5.34+maria-1~precise > ( misc ) 1 mariadb-server-5.5 [ amd64 ] < 5.5.34+maria-1~precise > ( misc ) Starting 2 Investigating (0) mysql-common [ amd64 ] < 5.5.34+maria-1~precise -> 5.5.35-0ubuntu0.12.04.1 > ( database ) Broken mysql-common:amd64 Breaks on mysql-client-5.1 [ amd64 ] < none > ( none ) Conflicts//Breaks against version 10.0.7+maria-1~precise for mariadb-client-10.0 but that is not InstVer, ignoring Considering mariadb-client-5.5:amd64 2 as a solution to mysql-common:amd64 8 Added mariadb-client-5.5:amd64 to the remove list Broken mysql-common:amd64 Breaks on mysql-client-core-5.1 [ amd64 ] < none > ( none ) Considering mariadb-client-core-5.5:amd64 2 as a solution to mysql-common:amd64 8 Added mariadb-client-core-5.5:amd64 to the remove list Broken mysql-common:amd64 Breaks on mysql-server-core-5.1 [ amd64 ] < none > ( none ) Considering mariadb-server-core-5.5:amd64 2 as a solution to mysql-common:amd64 8 Added mariadb-server-core-5.5:amd64 to the remove list Conflicts//Breaks against version 5.5.34+maria-1~precise for mariadb-galera-server-5.5 but that is not InstVer, ignoring Fixing mysql-common:amd64 via remove of mariadb-client-5.5:amd64 Fixing mysql-common:amd64 via remove of mariadb-client-core-5.5:amd64 Fixing mysql-common:amd64 via remove of mariadb-server-core-5.5:amd64 Investigating (0) libmariadbclient18 [ amd64 ] < 5.5.34+maria-1~precise > ( libs ) Broken libmariadbclient18:amd64 Depends on libmysqlclient18 [ amd64 ] < 5.5.34+maria-1~precise -> 5.5.35-0ubuntu0.12.04.1 > ( libs ) (= 5.5.34+maria-1~precise) Considering libmysqlclient18:amd64 6 as a solution to libmariadbclient18:amd64 6 Removing libmariadbclient18:amd64 rather than change libmysqlclient18:amd64 Investigating (0) mariadb-server-5.5 [ amd64 ] < 5.5.34+maria-1~precise > ( misc ) Broken mariadb-server-5.5:amd64 Depends on mariadb-client-5.5 [ amd64 ] < 5.5.34+maria-1~precise > ( misc ) (>= 5.5.34+maria-1~precise) Considering mariadb-client-5.5:amd64 2 as a solution to mariadb-server-5.5:amd64 1 Removing mariadb-server-5.5:amd64 rather than change mariadb-client-5.5:amd64 Investigating (0) mariadb-server [ amd64 ] < 5.5.34+maria-1~precise > ( database ) Broken mariadb-server:amd64 Depends on mariadb-server-5.5 [ amd64 ] < 5.5.34+maria-1~precise > ( misc ) (= 5.5.34+maria-1~precise) Considering mariadb-server-5.5:amd64 1 as a solution to mariadb-server:amd64 0 Removing mariadb-server:amd64 rather than change mariadb-server-5.5:amd64 Done Done The following packages will be REMOVED: libmariadbclient18 mariadb-client-5.5 mariadb-client-core-5.5 mariadb-server mariadb-server-5.5 mariadb-server-core-5.5 The following packages will be upgraded: libmysqlclient18 mysql-common 2 upgraded, 0 newly installed, 6 to remove and 0 not upgraded. Need to get 957 kB of archives. After this operation, 107 MB disk space will be freed. Do you want to continue [Y/n]? n Abort. marc@db01:~$ ``` Now that MariaDB has updated their PPA: ``` marc@db01:~$ apt-cache show mysql-common | grep Version Version: 5.5.35+maria-1~precise Version: 5.5.35-0ubuntu0.12.04.2 Version: 5.5.35-0ubuntu0.12.04.1 Version: 5.5.22-0ubuntu1 marc@db01:~$ apt-cache show libmysqlclient18 | grep Version Version: 5.5.35+maria-1~precise Version: 5.5.35-0ubuntu0.12.04.2 Version: 5.5.35-0ubuntu0.12.04.1 Version: 5.5.22-0ubuntu1 marc@db01:~$ sudo apt-get dist-upgrade Reading package lists... Done Building dependency tree Reading state information... Done Calculating upgrade... Done 0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded. ```
2014/01/22
[ "https://askubuntu.com/questions/409305", "https://askubuntu.com", "https://askubuntu.com/users/238729/" ]
I am having the same issue with Ubuntu 13.10. However I am able to resolve the situation without having to log out and back in again. If you have the "Show current input source in the menu bar" checkbox selected in System Settings -> Keyboard -> Layout Settings (a.k.a "Text Entry" settings), then even though "English (UK)" will be selected in the drop down menu when you click the icon in the menu bar, if you deselect it (by clicking on the "English (UK)" entry in the drop down list) then it will give you back your UK layout, which is a little odd. You can then reselect it if you wish and it will still be the UK layout. I know this isn't exactly a fix, but its a little less drastic than logging out and back in again.
Try this--at the top of your desktop is a bar that contains buttons for various services such as Bluetooth,wifi, and system power etc. There must be a button that says En2 or En1 depending on the layout you've selected. Adjust your keyboard layout using this button. A keyboard layout chart is available in the same drop-down menu which can be used as a reference.
60,088,893
I want to add LambdaFunctionAssociation to my existing CloudFront which is created manually [lambdafunctionassociation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-lambdafunctionassociation.html) Thanks in advance.
2020/02/06
[ "https://Stackoverflow.com/questions/60088893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3065730/" ]
As of mlflow 1.11.0, the recommended way to permanently delete runs within an experiment is: [`mlflow gc [OPTIONS]`](https://www.mlflow.org/docs/latest/cli.html#mlflow-gc). From the documentation, `mlflow gc` will > > Permanently delete runs in the *deleted* lifecycle stage from the specified backend store. This command deletes all artifacts and metadata associated with the specified runs. > > >
I am adding SQL commands if you want to delete permanently Trash of MLFlow if you are using PostgreSQL as backend storage. Change to your MLFlow Database, e.g. by using: `\c mlflow` and then: ``` DELETE FROM experiment_tags WHERE experiment_id=ANY( SELECT experiment_id FROM experiments where lifecycle_stage='deleted' ); DELETE FROM latest_metrics WHERE run_uuid=ANY( SELECT run_uuid FROM runs WHERE experiment_id=ANY( SELECT experiment_id FROM experiments where lifecycle_stage='deleted' ) ); DELETE FROM metrics WHERE run_uuid=ANY( SELECT run_uuid FROM runs WHERE experiment_id=ANY( SELECT experiment_id FROM experiments where lifecycle_stage='deleted' ) ); DELETE FROM tags WHERE run_uuid=ANY( SELECT run_uuid FROM runs WHERE experiment_id=ANY( SELECT experiment_id FROM experiments where lifecycle_stage='deleted' ) ); DELETE FROM params WHERE run_uuid=ANY( SELECT run_uuid FROM runs where experiment_id=ANY( SELECT experiment_id FROM experiments where lifecycle_stage='deleted' )); DELETE FROM runs WHERE experiment_id=ANY( SELECT experiment_id FROM experiments where lifecycle_stage='deleted' ); DELETE FROM experiments where lifecycle_stage='deleted'; ``` The difference is, that I added the 'params' Table SQL Delete command there.
67,672,278
In my program code which is posted below, I need to assign a variable of Swift enum type to a variable of NSObject type. However, the compiler doesn't allow this. I know this is not allowed. So, I wonder whether there is a way to change the enum somehow so that it can be assigned to an NSObject variable. Thank you! Photo+CoreDataClass.swift ``` import Foundation import CoreData @objc(Photo) public class Photo: NSManagedObject { } ``` Photo+CoreDataProperties.swift ``` import Foundation import CoreData extension Photo { @nonobjc public class func fetchRequest() -> NSFetchRequest<Photo> { return NSFetchRequest<Photo>(entityName: "Photo") } @NSManaged public var datetaken: String? @NSManaged public var datetakengranularity: NSObject? @NSManaged public var datetakenunknow: String? @NSManaged public var farm: Int32 @NSManaged public var heightZ: Int32 @NSManaged public var photoID: String? @NSManaged public var isfamily: Int32 @NSManaged public var isfriend: Int32 @NSManaged public var ispublic: Int32 @NSManaged public var owner: String? @NSManaged public var secret: String? @NSManaged public var server: String? @NSManaged public var title: String? @NSManaged public var urlZ: String? @NSManaged public var widthZ: Int32 } extension Photo : Identifiable { } ``` FlickrPhoto.swift ``` import Foundation // MARK: - Photo struct FlickrPhoto: Codable { let photoID, owner, secret, server: String let farm: Int let title: String let ispublic, isfriend, isfamily: Int let datetaken: String let datetakengranularity: Datetakengranularity let datetakenunknown: String let urlZ: String? let heightZ, widthZ: Int? enum CodingKeys: String, CodingKey { case owner, secret, server, farm, title, ispublic, isfriend, isfamily, datetaken, datetakengranularity, datetakenunknown case photoID = "id" case urlZ = "url_z" case heightZ = "height_z" case widthZ = "width_z" } } enum Datetakengranularity: Codable { case integer(Int) case string(String) init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if let x = try? container.decode(Int.self) { self = .integer(x) return } if let x = try? container.decode(String.self) { self = .string(x) return } throw DecodingError.typeMismatch(Datetakengranularity.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for Datetakengranularity")) } func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() switch self { case .integer(let x): try container.encode(x) case .string(let x): try container.encode(x) } } } extension FlickrPhoto: Equatable { static func == (lhs: FlickrPhoto, rhs: FlickrPhoto) -> Bool { // Two Photos are the same if they have the same photoID return lhs.photoID == rhs.photoID } } ``` PhotoStore.swift ``` import UIKit import CoreData class PhotoStore { private let session: URLSession = { let config = URLSessionConfiguration.default return URLSession(configuration: config) }() let imageStore = ImageStore() let persistenContainer: NSPersistentContainer = { let container = NSPersistentContainer(name: "Photorama") container.loadPersistentStores { (description, error) in if let error = error { print("Error setting up Core Data (\(error))") } } return container }() private func processPhotosRequest (data: Data?, error: Error?) -> Result<[FlickrPhoto], Error> { guard let jsonData = data else { return .failure(error!) } //return FlickrAPI.photos(fromJSON: jsonData) let context = persistenContainer.viewContext switch FlickrAPI.photos(fromJSON: jsonData) { case let .success(flickrPhotos): let _ = flickrPhotos.map { flickrPhoto -> Photo in let fetchRequest: NSFetchRequest<Photo> = Photo.fetchRequest() let predicate = NSPredicate(format: "\(#keyPath(Photo.photoID)) == \(flickrPhoto.photoID)") fetchRequest.predicate = predicate var photo: Photo! context.performAndWait { photo = Photo(context: context) photo.photoID = flickrPhoto.photoID photo.owner = flickrPhoto.owner photo.secret = flickrPhoto.secret photo.server = flickrPhoto.server photo.farm = Int32(flickrPhoto.farm) photo.title = flickrPhoto.title photo.ispublic = Int32(flickrPhoto.ispublic) photo.isfriend = Int32(flickrPhoto.isfriend) photo.isfamily = Int32(flickrPhoto.isfamily) photo.datetaken = flickrPhoto.datetaken photo.datetakengranularity = flickrPhoto.datetakengranularity // The compiler reports error here: // Cannot assign value of type 'Datetakengranularity' to type 'NSObject?' photo.datetakenunknow = flickrPhoto.datetakenunknown photo.urlZ = flickrPhoto.urlZ photo.heightZ = Int32(flickrPhoto.heightZ!) photo.widthZ = Int32(flickrPhoto.widthZ!) } return photo } return .success(flickrPhotos) case let .failure(error): return .failure(error) } } func fetchAllPhotos (completion: @escaping (Result<[Photo], Error>) -> Void) -> Void { let fetchRequest: NSFetchRequest<Photo> = Photo.fetchRequest() let sortByDataTaken = NSSortDescriptor(key: #keyPath(Photo.datetaken), ascending: true) fetchRequest.sortDescriptors = [sortByDataTaken] let viewContext = persistenContainer.viewContext viewContext.perform { do { let allPhotos = try viewContext.fetch(fetchRequest) completion(.success(allPhotos)) } catch { completion(.failure(error)) } } } func fetchRecentPhotos (completion: @escaping (Result<[FlickrPhoto], Error>) -> Void) { let url = FlickrAPI.interestingPhotoURL let request = URLRequest(url: url) let task = session.dataTask(with: request) { (data, response, error) in var result = self.processPhotosRequest(data: data, error: error) if case .success = result { do { try self.persistenContainer.viewContext.save() } catch { result = .failure(error) } } OperationQueue.main.addOperation { completion(result) } } task.resume() } func fetchImage (for photo: Photo, completion: @escaping (Result<UIImage, Error>) -> Void) { let photoKey = photo.photoID if let image = imageStore.image(forKey: photoKey!) { OperationQueue.main.addOperation { completion(.success(image)) } return } guard let photoURL = photo.urlZ else { return } guard let requestURL = URL(string: photoURL) else { completion(.failure(PhotoError.missingImageURL)) return } let request = URLRequest(url: requestURL) let task = session.dataTask(with: request) { (data, response, error) in let result = self.processImageRequest(data: data, error: error) if case let .success(image) = result { self.imageStore.setImage(image, forKey: photoKey!) } OperationQueue.main.addOperation { completion(result) } } task.resume() } private func processImageRequest (data: Data?, error: Error?) -> Result<UIImage, Error> { guard let imageData = data, let image = UIImage(data: imageData) else { // Couldn't create an image if data == nil { return .failure(error!) } else { return .failure(PhotoError.imageCreationError) } } return .success(image) } } enum PhotoError: Error { case imageCreationError case missingImageURL } ``` A snapshot of the Photorama.xcdatamodeld interface is shown below: [![enter image description here](https://i.stack.imgur.com/0zBuq.png)](https://i.stack.imgur.com/0zBuq.png) More code will be provided if necessary. Thanks very much!
2021/05/24
[ "https://Stackoverflow.com/questions/67672278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6763591/" ]
You could do it using hacky `enum` byte serialization stored as `NSData` property in your `NSObject`. ``` enum Test { case testCase case testCase2 } func bytes<T>(of value: T) -> [UInt8]{ var value = value let size = MemoryLayout<T>.size return withUnsafePointer(to: &value, { $0.withMemoryRebound(to: UInt8.self, capacity: size, { Array(UnsafeBufferPointer(start: $0, count: size)) }) }) } let testCase: Test = .testCase let testCase2: Test = .testCase2 var testBytes = bytes(of: testCase) var testBytes2 = bytes(of: testCase2) let data = NSData(bytes: &testBytes, length: testBytes.count) let data2 = NSData(bytes: &testBytes2, length: testBytes2.count) let testCaseDeserialized = data.bytes.bindMemory(to: Test.self, capacity: 1).pointee let testCase2Deserialized = data2.bytes.bindMemory(to: Test.self, capacity: 1).pointee ```
I tried bridging the flickrPhoto.datatakengranularity variable to NSObject via AnyObject like this: ``` photo.datetakengranularity = (flickrPhoto.datetakengranularity as AnyObject as! NSObject) ``` And the compiler made no complaints. This may be because in essence AnyObject is equivalent to NSObject and flickrPhoto.datetakengranularity is convertible to AnyObject. I don't know what happened underneath but it worked anyway. I don't know why. Thanks to all for your concern and support!
12,956,641
I want to convert a String to Datetime. I'm getting an error `This is not a valid datetime`. The string I want to convert and code are as follows. ``` string date1 = "9/13/2012 5:26:06 PM"; TimePart = DateTime.ParseExact(date1, "M/d/yyyy HH:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture); ```
2012/10/18
[ "https://Stackoverflow.com/questions/12956641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1755805/" ]
You need to use the lowercase `h`: ``` DateTime TimePart = DateTime.ParseExact( date1, "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); Console.WriteLine(TimePart); // 09/13/2012 17:26:06 ``` Uppercase "H" is 24-hour time, lowercase "h" is 12-hour time with AM/PM.
It looks like the `HH` isn't matching the "5". Try `h`.
1,850,422
When running our program we get an exception of type java.lang.IllegalMonitorStateException. On Java6 API website, it says there is a constructor that gives a details about the exception: IllegalMonitorStateException(String s) How can we use this to get a better idea of where the bug is in our code? Is there anything else we can do (besides lots of debugging which we're currently doing) to pinpoint the function or line that failed?
2009/12/04
[ "https://Stackoverflow.com/questions/1850422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225182/" ]
> > How can we use this to get a better > idea of where the bug is in our code? > Is there anything else we can do > (besides lots of debugging which we're > currently doing) to pinpoint the > function or line that failed? > > > In this case, printing the message by itself probably won't help much. What you need is a stacktrace *with source file names and line numbers*. 1. Make sure that all relevant ".class" files / JARs were built with file and line number debug information included. This is the default, but compiling with "-g:none" will strip this ... as will most JAR file obfuscators. 2. Next, add a try / catch block to catch the `IllegalMonitorStateException` and either call `ex.printStackTrace()` or log the exception. From the stacktrace you should be able to see what line in the code threw the exception. The chances are that is was a call to `Object.wait(...)` or something like that. Check the javadoc for the offending method to find out what circumstances cause the exception to be thrown. (And once you are done, remember to move the try / catch block you added.)
You should print the stack trace, which will give you the exact location in the source. Unfortunately it's not uncommon for the JVM to throw exceptions which contain no detail message to assist in debugging.
15,000,913
Consider the following: ``` <a>a</a><a>b</a> ``` How can I align the second anchor (b) to the right? **PS:** float is an abuse in this situation. It's not made for this and it causes some problems, so I need other more reasonable solution.
2013/02/21
[ "https://Stackoverflow.com/questions/15000913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2080105/" ]
Maybe you can make something like this: `<a>a</a><a class="right">b</a>` And CSS like this: ```css a.right { position: absolute; right: 0; } ```
You may try the below code: ``` <a>a</a><a align="right">b</a> <a>a</a><a style="text-align:right">b</a> ```
37,807,636
Trying to create Web application based on Tomcat. Can't set Tomcat folder: [![enter image description here](https://i.stack.imgur.com/SH02Q.png)](https://i.stack.imgur.com/SH02Q.png) Error: ``` The specified Server Location (Catalina Home) folder is not valid. ``` [![enter image description here](https://i.stack.imgur.com/lJO0m.png)](https://i.stack.imgur.com/lJO0m.png) How to fix this problem?
2016/06/14
[ "https://Stackoverflow.com/questions/37807636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1501700/" ]
Open the folder and then you find the single folder with apache tomcat 9.0. Press open then, before you just selected the main folder didn't opened it. ![screenshot](https://i.stack.imgur.com/975D6.png)
Just download the appropriate tomcat file and unzip.[![enter image description here](https://i.stack.imgur.com/R8VGv.png)](https://i.stack.imgur.com/R8VGv.png)
26,984,038
At first I apologize for my English. Well, thats the deal <http://www.dotazoneapp.com/site/pt/> this site have a somekind of interesting scroll, when scroll down, the background-image is change his position, with the background-position (I check this on the source). But I don't even know HOW I CAN DO THIS, if is with Jquery or the own CSS. Well, please help me how do that effect And... ![](//i.stack.imgur.com/yHXwc.png) This button have a animation too scrolling up, it acelerate and not automatic to the top like the reference using id `<a href="#example"> Example2 </a>`
2014/11/17
[ "https://Stackoverflow.com/questions/26984038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4263274/" ]
One command will do this work: ``` git checkout -b <local_branch_name> origin/<remote_branch_name> ``` Edit: If an error occurred: fatal: 'origin/<branch\_name>' is not a commit and a branch '<branch\_name>' cannot be created from it. You may try: ``` git pull git checkout -b <local_branch_name> origin/<remote_branch_name> ```
As of Git version 2.37.2 you can now use `$ git switch -c` as shown in the steps below. #### Fetch everything from the remote repository. `$ git fetch <remote>` #### Checkout the remote branch `$ git checkout <remote>/<branch>` #### Create the new local branch `$ git switch -c <branch>`
56,563,644
I'm trying to create a code to check if an array has empty values between valid values or before them. At first I tried to use array\_filter to remove empty values and then check if the remaining indexes of the valid values are consecutives, but I think there might be a simple way. Here are examples These array are processed as VALID ``` Array => 0 => string '030208000000000' 1 => string '' 2 => string '' Array => 0 => string '030208000000000' 1 => string '030210700000000' 2 => string '' ``` These array are processed as NOT VALID ``` Array => 0 => string '030208000000000' 1 => string '' 2 => string '030210500000000' Array => 0 => string '' 1 => string '030208000000000' 2 => string '030210500000000' ```
2019/06/12
[ "https://Stackoverflow.com/questions/56563644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3421568/" ]
In MySql use IFNULL() function. For MsSql use ISNULL() function.
if you need all the rows and not the rows where goal is not null you could use count(\*) ``` select count(*) from fixtures where goal=1 and fixture='$fixture' ``` `count(goal)` return the number of rows where goal is not null `count(*)` return the total number rows selected otherwise in general when you need not null values in mysql you can ifnull(your\_column, value) or coalesce(your\_column, value) based on you comment seems you need sum(goal) ``` select sum(ifnull(goal,0)) from fixtures where goal=1 and fixture='$fixture' ```
12,172,997
I want to fetch all service\_name and its status without using any 3rd party tool. So far [SC](http://ss64.com/nt/sc.html) command was good enough to fetch one of the values, something like ``` sc query | findstr SERVICE_NAME ``` but I also need `STATUS` for each `SERVICE_NAME` listed.
2012/08/29
[ "https://Stackoverflow.com/questions/12172997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/707414/" ]
By the way ``` sc query | findstr SERVICE_NAME ``` will show only active (RUNNING) services, so there is no need to filter status (STATE). Try SC with findstr syntax that supports multiple filtered items: ``` sc query state= all | findstr "SERVICE_NAME STATE" ``` or ``` sc query state= all | findstr "DISPLAY_NAME STATE" ``` or both ``` sc query state= all | findstr "SERVICE_NAME DISPLAY_NAME STATE" ```
Thanks [@jon](https://stackoverflow.com/users/50079/jon) for the post, that was very helpful. I wanted a column aligned output, so I grabbed your example above and created the following batch file: ``` @ECHO OFF SETLOCAL ENABLEDELAYEDEXPANSION ECHO.Service State ECHO.------------------------------------------------------- ------------- FOR /F "TOKENS=2" %%S IN ('sc query state^= all ^| FIND "SERVICE_NAME" ^| FIND /I "myservice"') DO ( @(FOR /f "TOKENS=4" %%T IN ('sc query %%S ^| FIND "STATE "') DO ( SET OUTPUT="%%S -------------------------------------------------------------" @ECHO !OUTPUT:~1,55!^> %%T )) ) ENDLOCAL ``` That produces an output suitable for what I was looking for like this: ``` Service State ------------------------------------------------------- ------------- MyService.Test_1 --------------------------------------> STOPPED MyService.Test_2 --------------------------------------> RUNNING MyService.Test_3 --------------------------------------> STOPPED ``` Here's a breakdown of the relevant changes * added the additional find to filter to only the service names I wanted to see instead of the whole list, in this case looking for service names that contain "myservice" `FIND /I "myservice"` * Since it's in a batch file, changed `%s` and `%t` to `%%s` and `%%t` respectively (I like to use caps for vars) * Added the `OUTPUT` var for formatting (`SET OUTPUT="%%S -------------------------------------------------------------"`), the value is quoted since I initially intended to use spaces, but switched to a dash `-`, that can be changed to any character you like, I considered `*` as well. The value is set to the service name plus whatever padding character. * The output line `@ECHO !OUTPUT:~1,55!^> %%T` + The formatted output: `!OUTPUT:~1,55!` uses `!` because of the delayed expansion and takes 55 characters starting at the 2nd character (zero based index) in order to remove the leading `"` + `^>`: the `^` escapes the `>` so it does not attempt to redirect to... somewhere. All in order to just include the `>` in the output line (totally not necessary) + Finally, `%%T`, the state output Hope this helps someone! I can never remember this stuff!
36,707,383
Essentially, I want only the hour, minute, and seconds from a column of timestamps I have in R, because I want to view how often different data points occur throughout different times of day and day and date is irrelevant. However, this is how the timestamps are structured in the dataset: 2008-08-07T17:07:36Z And I'm unsure how to only get that time from this timestamp. Thank you for any help you can provide and please just let me know if I can provide more information!
2016/04/19
[ "https://Stackoverflow.com/questions/36707383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5522760/" ]
I think you are expecting this... ``` Sys.time() [1] "2016-04-19 11:09:30 IST" format(Sys.time(),format = '%T') [1] "11:09:30" ``` if you want to give your own timestamp, then use bellow code: ``` format(as.POSIXlt("2016-04-19 11:02:22 IST"),format = '%T') [1] "11:02:22" ```
A regular expression will probably be quite efficient for this: ``` x <- '2008-08-07T17:07:36Z' x ## [1] "2008-08-07T17:07:36Z" sub('.*T(.*)Z', '\\1', x) ## [1] "17:07:36" ```
8,900
Inspired by [this question](https://codegolf.stackexchange.com/questions/77117/tips-for-king-of-the-hill-bots), what are some tips you guys have for creating king of the hill challenges? What are some things to keep in mind in the planning and implementing of the rules and the controller, and advice on what makes for a good challenge?
2016/04/05
[ "https://codegolf.meta.stackexchange.com/questions/8900", "https://codegolf.meta.stackexchange.com", "https://codegolf.meta.stackexchange.com/users/30793/" ]
Allow as many bots as possible ------------------------------ Nobody wants to be disallowed from a contest right? Allow as many languages as you can. If someone posts a bot in a language you don't have, try as hard as you can to install it. If you can't? Ask for instructions. Allow people to post as many bots as they want. This means when they come up with a Super Amazing Idea™ they don't have to worry about changing/removing their other bot from the contest.
Opponent prediction =================== In general, a koth is better if there is some level of opponent prediction, rather than perfect info where the result tends to be based on whether someone wrote the ideal bot. Even if your koth doesn't have perfect info, it can still have an ideal bot. for example, a move with an expected value of 5 is better than one with an expected value of 4. hence there should be opponent variance and simultaneous turns or fog of war, so that you can take the guessing about how your opponent would behave to enrich the metagame.
60,551
I'm very new to GIMP and found that doing simple stuff in GIMP is much harder than it should be. All I want to do is add a simple black border around an image layer. I have added this image using the "Open as Layers" option (as I have many images in one document!), but can't seem to find an option to add a border around the image. Please help!
2015/09/14
[ "https://graphicdesign.stackexchange.com/questions/60551", "https://graphicdesign.stackexchange.com", "https://graphicdesign.stackexchange.com/users/47793/" ]
Go to Filters -> Decor -> Add Border... Then choose your border settings [![border settings](https://i.stack.imgur.com/DNqwf.png)](https://i.stack.imgur.com/DNqwf.png) [From the GIMP help files](http://docs.gimp.org/en/script-fu-addborder.html) > > Border X size, Border Y size Here you can select the thickness of the > added border, in pixels. X size (left an right) and Y size (top and > bottom) may be different. Maximum is 250 pixels. > > > Border color Clicking on this button brings up the color selector > dialog that allows you to choose an “average” border color (see below, > Delta value on color). > > > Delta value on color This option makes the border sides to be colored > in different shades and thus makes the image to appear raised. The > actual color of the respective border side is computed for every color > component red, green, and blue[15] from the “average” Border color as > follows (resulting values less than 0 are set to 0, values greater > than 255 are set to 255): > > > Top shade = Border color + Delta > > > Right shade = Border color - ½ Delta > > > Bottom shade = Border color - Delta > > > Left shade = Border color + ½ Delta > > >
Here's what worked for me in GIMP 2.10: 1. Select the layer with the image you want the border on (click on the layer itself in the list) 2. Using the menu: `Select` --> `All` 3. Using the menu: `Edit` --> `Stroke Selection` 4. In the dialogue box, leave everything selected as default, and set the line width and color. 5. Press Okay/Apply, and enjoy. :)
26,473,371
I am new to rails and haven't really done to much with data outside of the model. I have a form that references a table controller for files. I want to add an dropdown that will display a list of projects from a project table for the user to assign a the file to a project if they want too. Assigning a project is not a requirement. The file can be unassigned to a project. I do have a project\_id column in the file table for those projects assigned but it is allowed to be null and I did not build a relationship because I need to have cases where there are none. Can someone please tell me how to do this? When they evaluate the file, the screen posts back with a save or update button depending if it has already been saved in the database. At the same time as the save and update pop up on the right I want to display a list box of the projects with an assign project button. If new just a list, if update either just a list because not assigned or display the selected value in the list if already assigned, while allowing them to change it from the list if desired. In the file controller method that posts back to the UI I have this code: ``` @file_alias_filedata = FileAliasFiledata.all @projects = Project.all ``` for update ``` @projects = Project.find(params[:id]) ``` In the form I have this code: ``` <p> <label> Select Project to Assign:</label> <br /> <%= select_tag 'projects', (@projects.present? ? options_for_select(@projects, @selected_project) : []) %> </p> ``` The form runs but I get this in the dropdown box: ``` #<Project:0x))7ff531ab4518> ``` Can someone please help me figure out how to accomplish my task and why I see the strange box value? What am I doing wrong? Thank you for your help!
2014/10/20
[ "https://Stackoverflow.com/questions/26473371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4099784/" ]
Adding sub views like this ``` [self.v addSubview:button]; ``` Access subviews like this ``` UIScrollView *scrollview = (UIScrollView *) _scroll; UIView *View = (UIView *) scrollview.subviews[0]; ```
I found the answer. In the ViewDidLoad method of my view controller's custom class I used the following: ``` NSArray *sv = self.view.subviews; UIScrollView *sc = sv[0]; sv = sc.subviews; UIView *v = sv[0]; ``` I stepped through execution to confirm the ScrollView was the first subview of the view, and to confirm the UIView was the first subview of the ScrollView. If I needed to access this view beyond the ViewDidLoad method, I would create the variable in the header file.
57,301,412
I am trying to avoid the nested subscription in request to the backend. I need to login, then get a service token based on the response of the login, then get a encryption token based on the service token. I have seen about concatMap but i am not sure how to use the first response in the second request or third ``` this.rest.CallLogin(this.data).pipe( concatMap(serviceToken => this.rest.GetServiceTicket(1stresponse.headers.get('Location'))),// dont know how to get the 1st response from CallLogin concatMap(tokenResponse => this.rest.getEncryptToken(serviceToken)), ); ```
2019/08/01
[ "https://Stackoverflow.com/questions/57301412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2837056/" ]
I ended up using SwitchMap ``` this.rest.CallLogin(this.data).pipe( switchMap((response: any) => { this.data.requestUrl = response.headers.get('Location'); return this.rest.GetServiceTicket(this.data) // serviceticket }), switchMap((serviceticket) => { return this.rest.getEncryptToken(serviceticket.body) // tokenResponse }), //continue doing requests or stuff switchMap((tokenResponse) => { encryptToken = tokenResponse; ///... }), ```
If i understood correctly then you only want to chain the calls and use the response header from the first response. For that you need to use observe on response in your first call: ``` this.rest.CallLogin(this.data, {observe: 'response'}).pipe( concatMap(loginResponse => this.rest.GetServiceTicket(loginResponse.headers.get('Location'))), concatMap(serviceTicket => this.rest.getEncryptToken(serviceTicket)), ); ```
55,479,887
I'am using a firebird 2.5 server to write in a Database file(BD.fbd). My delphi XE8 project has a Data module(DMDados) with: * `SQLConnection (conexao)` * `TSQLQUery1 (QueryBDPortico_Inicial) + TDataSetProvider1 (DSP_BDPortico_Inicial) + TClientDataSet1 (cdsBDPortico_Inicial)` * `TSQLQUery2 (QueryConsulta)` (just for use SQL strings) My database file has this table: * `PORTICO_INICIAL` The table has these fields (all integer): * `NPORTICO` * `ELEMENTO` * `ID` None of those fields are primary keys because I will have repeated values in some cases. The connection with the file is ok. The client data set is open when I run the code. The `TSQLQUery2 (QueryConsulta)` is open when needed. My code, when triggered by a button, has to delete all tables' records (if exist) then full the table with integer numbers created by a LOOP. In the first try the code just work fine, but when I press the button the second time i get the error 'Unable to find record. No key specified' then when I check the records the table is empty. I tried to change the `ProviderFlags` of my query but this make no difference. I checked the field names, the table name or some SQL text error but find nothing. My suspect is that when my code delete the records the old values stay in memory then when try apply updates with the new values the database use the old values to find the new record's place therefore causing this error. ``` procedure monta_portico (); var I,K,L,M, : integer; begin with DMDados do begin QUeryCOnsulta.SQL.Text := 'DELETE FROM PORTICO_INICIAL;'; QueryConsulta.ExecSQL(); K := 1; for I := 1 to 10 do begin L := I*100; for M := 1 to 3 do begin cdsBDPortico_Inicial.Insert; cdsBDPortico_Inicial.FieldbyName('NPORTICO').AsInteger := M+L; cdsBDPortico_Inicial.FieldbyName('ELEMENTO').AsInteger := M; cdsBDPortico_Inicial.ApplyUpdates(0); K := K +1; end; end; end; end; ``` I want that every time I use the code above it first delete all records in the table then fill it again with the loop. When I use the code for the first time it do what I want but in the second time it just delete the records and can not fill the table with the values.
2019/04/02
[ "https://Stackoverflow.com/questions/55479887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10940927/" ]
Splite the problem into small parties using functions and procedures create an instance of TSqlQuery Execute the SQL statment's and destroy the instance when you finish with it... ``` procedure DeleteAll; var Qry: TSqlQuery; begin Qry := TSqlQuery.Create(nil); try Qry.SqlConnection := DMDados.conexao; Qry.Sql.Text := 'DELETE FROM PORTICO_INICIAL;'; Qry.ExecSql; finally Qry.Free; end; end; ``` your can even execute directly from TSQlConnection with one line... --- ``` DMDados.conexao.ExecuteDirect('DELETE FROM PORTICO_INICIAL;') ``` --- ``` procedure monta_portico (); var I,K,L,M, : integer; begin with DMDados do begin DeleteAll; K := 1; for I := 1 to 10 do begin L := I*100; for M := 1 to 3 do begin cdsBDPortico_Inicial.Insert; cdsBDPortico_Inicial.FieldbyName('NPORTICO').AsInteger := M+L; cdsBDPortico_Inicial.FieldbyName('ELEMENTO').AsInteger := M; cdsBDPortico_Inicial.ApplyUpdates(0); K := K +1; end; end; end; end; ```
Just few obvervations, cause the primary answers were given, but they not deal with the secondary problems. ``` cdsBDPortico_Inicial.FieldbyName('NPORTICO').AsInteger := ``` `FieldByName` is slow function - it is linear search over objects array with uppercased string comparison over each one. You better only call it once for every field, not do it again in again in the loop. ``` cdsBDPortico_Inicial.ApplyUpdates(0); ``` Again, applying updates is relatively slow - it requires roundtrip to the server all through internal guts of DataSnap library, why so often? BTW, you delete rows from SQL table - but where do you delete rows from `cdsBDPortico_Inicial` ??? I do not see that code. Was I in your shows I would write something like that (granted I am not big fan of Datasnap and CDS): ``` procedure monta_portico (); var Qry: TSqlQuery; _p_EL, _p_NP: TParam; Tra: TDBXTransaction; var I,K,L,M, : integer; begin Tra := nil; Qry := TSqlQuery.Create(DMDados.conexao); // this way the query would have owner try // thus even if I screw and forget to free it - someone eventually would Qry.SqlConnection := DMDados.conexao; Tra := Qry.SqlConnection.BeginTransaction; // think about making a special function that would create query // and set some its properties - like connection, transaction, preparation, etc // so you would not repeat yourself again and again, risking mistyping Qry.Sql.Text := 'DELETE FROM PORTICO_INICIAL'; // you do not need ';' for one statement, it is not script, not a PSQL block here Qry.ExecSql; Qry.Sql.Text := 'INSERT INTO PORTICO_INICIAL(NPORTICO,ELEMENTO) ' + 'VALUES (:NP,:EL)'; Qry.Prepared := True; _p_EL := Qry.ParamByName('EL'); // cache objects, do not repeat linear searches _p_NP := Qry.ParamByName('NP'); // for simple queries you can even do ... := Qry.Params[0] K := 1; for I := 1 to 10 do begin L := I*100; for M := 1 to 3 do begin _p_NP.AsInteger := M+L; _p_EL.AsInteger := M; Qry.ExecSQL; Inc(K); // why? you seem to never use it end; end; Qry.SqlConnection.CommitFreeAndNil(tra); finally if nil <> tra then Qry.SqlConnection.RollbackFreeAndNil(tra); Qry.Destroy; end; end; ``` This procedure does not populate `cdsBDPortico_Inicial` - but do you really need it? If you do - maybe you can re-read it from the database: there could be other programs that added rows into the table too. Or you can insert many rows and then apply them all in one command, before committing the transaction (often abreviated tx), but even then, do not call `FieldByName` more than once. Also, think about logical blocks of your program work in advance, those very transactions, temporary `TSQLQuery` objects etc. However boring and tedious it is now, you would bring yourself many more spaghetti trouble if you don't. Adding this logic retroactively after you have many small functions calling one another in unpredictable order is very hard. Also, if you make Firebird server auto-assigning the `ID` field (and your program does not need any special values in `ID` and will be ok with Firebird-made values) then the following command might server yet better for you: `INSERT INTO PORTICO_INICIAL(NPORTICO,ELEMENTO) VALUES (:NP,:EL) RETURNING ID`
6,798,665
I am parsing the data it gets all the data in dictionary but when i check value using NSLog it showa nil value ``` SBJsonParser *parser = [[SBJsonParser alloc] init]; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.krsconnect.no/community/api.html?method=bareListEventsByCategory&appid=620&category-selected=350&counties-selected=Vest-Agder,Aust-Agder"]]; NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; NSDictionary *object = [parser objectWithString:json_string error:nil]; //appDelegate.books = [[NSMutableArray alloc] initWithCapacity:0]; appDelegate.books1 = [[NSMutableArray alloc] init]; NSArray *results = [parser objectWithString:json_string error:nil]; for (int i=0; i<[results count]; i++) { Book1 *aBook = [[Book1 alloc] initWithDictionary:[results objectAtIndex:i]]; [appDelegate.books1 addObject:aBook]; Book1 *mybook=[appDelegate.books1 objectAtIndex:i]; NSString*test=mybook.location; NSLog(test); } ``` Dicionary parsing ``` - (id)initWithDictionary:(NSDictionary*) dict { self.date = [dict valueForKey:@"date"]; self.location = [dict valueForKey:@"location"]; self.municipality = [dict valueForKey:@"municipality"]; self.title = [dict valueForKey:@"title"]; return self; } ```
2011/07/23
[ "https://Stackoverflow.com/questions/6798665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/838384/" ]
I'm guessing that your dictionary doesn't contain a "location", and that's consistent with what I see coming back from that web site. It sends back an array of dictionaries which contain arrays of dictionaries. You need to extract one of those inner dictionaries to find a "location". ``` [ { "date":1320883200000, "events":[ { "affectedDate":1320883200000, "event":{ "appId":620, "eventId":20672, "location":"Samsen Kulturhus", "municipality":"Kristiansand", "title":"AKKS kurs høsten 2011" } }, .... ```
Try: ``` - (id)initWithDictionary:(NSDictionary*) dict { self = [super init]; if(self) { self.date = [dict valueForKey:@"date"]; self.location = [dict valueForKey:@"location"]; self.municipality = [dict valueForKey:@"municipality"]; self.title = [dict valueForKey:@"title"]; } return self; } ```
3,206,574
I'm looking for a way in SQL Server without using the .NET framework to find out the time in a given time zone, paying attention to daylight savings. However, this method also needs to take account for states (e.g. Arizona) that do NOT follow DST. There is a workaround if the server is located somewhere that does follow DST - subtract your current time from GMT to get the offset - but I am looking for a more general-purpose solution. I know the .NET framework has ways to do this, but it would be great to avoid having this kind of dependency within this stored procedure. Thanks!
2010/07/08
[ "https://Stackoverflow.com/questions/3206574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/387007/" ]
Divide `rand()` by the maximum random numer, multiply it by the range and add the starting number: ``` <?php // rand()/getrandmax() gives a float number between 0 and 1 // if you multiply it by 0.002 you'll get a number between 0 and 0.002 // add the starting number -0.001 and you'll get a number between -0.001 and 0.001 echo rand()/getrandmax()*0.002-0.001; ?> ```
This will return any **possible** number between `-0.001` and `+0.001` ``` $random = ((rand()*(0.002/getrandmax()))-0.001) // or without paranthesis: $random = rand()*0.002/getrandmax()-0.001 ```
10,263,017
I realize similar questions have been asked before, but I read a couple of those and still don't see where I'm going wrong. When I simply write my class without separating the prototype from the definition, everything works fine. The problem happens when I separate the prototype and definition as shown below: ``` template<class T> class VisitedSet { public: VisitedSet(); int getSize(); void addSolution(const T& soln); void evaluate(); private: vector<T> vec; int iteration; }; ``` And as an example of a definition that gives me this error: ``` int VisitedSet::getSize() { return vec.size(); ``` I've never made a templated class before, so please pardon me if the problem here is trivial.
2012/04/21
[ "https://Stackoverflow.com/questions/10263017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1325279/" ]
You have to state the template parameter in the definition as well ``` template<class T> int VisitedSet<T>::getSize() { return vec.size(); } ``` otherwise the compiler cannot match it to the declaration. For example, there could be specializations for some parameter types.
Try putting ``` template <typename T> ``` above the implementation of VisitedSet::getSize() -- but beware that, in general, templated classes and functions should all be inlined. See the c++ faq [here](http://www.parashift.com/c++-faq-lite/templates.html) for more information.
218,185
I'm reading a proof and I'm struggling with basic calculus here. Given the equation, $F[x, F(y, z)] = F[F(x, y), z] $ set $u = F(x, y)$ and $v = F(y, z)$ so you have $$F(x, v) = F(u, z)$$ Now differentiate with respect to $x$ and $y$ leads to the following 1. $F\_{x}(x,v) = F\_{x}(u,z)F\_{x}(x,y)$ 2. $F\_{y}(x,v)F\_{x}(y,z) = F\_{x}(u,z)F\_{y}(x,y)$ I think, according to the chain rule, the derivative of $F[x, F(y, z)]$ or $F[x, u]$ with respect to x should equal $F\_{x}(u,z)F\_{x}(x,y)$. So number 1 makes sense. But when you differentiate that with respect to $y$, I don't understand how you get 2.
2012/10/21
[ "https://math.stackexchange.com/questions/218185", "https://math.stackexchange.com", "https://math.stackexchange.com/users/45521/" ]
$9\cos^2(B)-9\sin^2(B)=9\cos^2(B)-9(1-\cos^2(B))=18\cos^2(B)-9$
Since $\cos^2 B$ appears in two places, you could start by bringing everything to one side of the equation to see whether you get something nicer. In this case you get $$9\cos^2 B+9\sin^2 B-9=0\;,$$ which is true if and only if $\cos^2B+\sin^2B-1=0$, i.e., if and only if $\cos^2B+\sin^2B=1$, which you know is true. Now start with the known $\cos^2B+\sin^2B=1$ and work back through the calculations to prove the identity. This is not the most efficient approach, but it’s a good way to discover a proof if you don’t happen to see one of the more efficient calculations right away.
53,697,814
It seems that I cannot get pip to install Cartopy on my computer. I work straight from the windows command line (no Anaconda or other proxy programs). When I try "pip install cartopy" I get the expected: ``` C:\Users\Justin\Documents\Python Programs>pip install cartopy Collecting cartopy Using cached https://files.pythonhosted.org/packages/e5/92/fe8838fa8158931906dfc4f16c5c1436b3dd2daf83592645b179581403ad/Cartopy-0.17.0.tar.gz Installing build dependencies ... done Complete output from command python setup.py egg_info: C:\Users\Justin\AppData\Local\Temp\pip-install-cetb0vj7\cartopy\setup.py:171: UserWarning: Unable to determine GEOS version. Ensure you have 3.3.3 or later installed, or installation may fail. '.'.join(str(v) for v in GEOS_MIN_VERSION), )) Proj 4.9.0 must be installed. ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\Users\Justin\AppData\Local\Temp\pip-install-cetb0vj7\cartopy\ ``` I know that "pip install proj" does not actually get the correct module version so I went to <https://proj4.org/install.html> to download and install the OSGeo4W which I thought would solve my problem but has appeared not to (for reference I do still have this on my computer though). So then I tried install the cartopy .whl directly from this <https://www.lfd.uci.edu/~gohlke/pythonlibs/#cartopy> website and tried using "pip install Cartopy-0.17.0-cp37-cp37m-win32.whl" (I use the the 32 bit version of Python3.7 so I am fairly certain this is the correct file). But I then get the error: ``` C:\Users\Justin\Documents\Python Programs>pip install Cartopy-0.17.0-cp37-cp37m-win32.whl Processing c:\users\justin\documents\python programs\cartopy-0.17.0-cp37-cp37m-win32.whl Requirement already satisfied: numpy>=1.10 in c:\users\justin\appdata\local\programs\python\python37\lib\site-packages (from Cartopy==0.17.0) (1.15.1) Requirement already satisfied: setuptools>=0.7.2 in c:\users\justin\appdata\local\programs\python\python37\lib\site-packages (from Cartopy==0.17.0) (40.6.2) Requirement already satisfied: six>=1.3.0 in c:\users\justin\appdata\local\programs\python\python37\lib\site-packages (from Cartopy==0.17.0) (1.11.0) Collecting pyshp>=1.1.4 (from Cartopy==0.17.0) Downloading https://files.pythonhosted.org/packages/08/3e/3bda7dfdbee0d7a22d38443f5cc8d154ff6d4701e615f4c07bf1ed003563/pyshp-2.0.1.tar.gz (214kB) 100% |████████████████████████████████| 215kB 1.4MB/s Collecting shapely>=1.5.6 (from Cartopy==0.17.0) Using cached https://files.pythonhosted.org/packages/a2/fb/7a7af9ef7a35d16fa23b127abee272cfc483ca89029b73e92e93cdf36e6b/Shapely-1.6.4.post2.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\Justin\AppData\Local\Temp\pip-install-sb4uyliy\shapely\setup.py", line 80, in <module> from shapely._buildcfg import geos_version_string, geos_version, \ File "C:\Users\Justin\AppData\Local\Temp\pip-install-sb4uyliy\shapely\shapely\_buildcfg.py", line 200, in <module> lgeos = CDLL("geos_c.dll") File "c:\users\justin\appdata\local\programs\python\python37\lib\ctypes\__init__.py", line 356, in __init__ self._handle = _dlopen(self._name, mode) OSError: [WinError 126] The specified module could not be found ``` So then I tried to download something called a tar.gz file, but this is where I lose myself. I am not familiar with tar.gz and I saw there you have to "./configure" the file path, but I was not sure how to do this nor was I sure where I should store said file. Any guidance around this issue would be so incredibly appreciated thank you.
2018/12/09
[ "https://Stackoverflow.com/questions/53697814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8205368/" ]
If any problem arises while installing cartopy: Downlaod Cartopy, shapely and pyprof from this website [https://www.lfd.uci.edu/~gohlke/pythonlibs/](https://www.lfd.uci.edu/%7Egohlke/pythonlibs/) and install these using this commands in cmd terminal. For example installing Cartopy pip install "C:\Users\USER\Downloads\Cartopy-0.20.2-cp310-cp310-win\_amd64.whl" Surely it will work. Cheers!!
I made good experiences using the osdeo/gdal image when encountering docker issues with cartopy (and other geo libraries): ``` # select latest osgeo container FROM osgeo/gdal:ubuntu-full-3.5.1 RUN apt-get update && \ apt-get install -y \ libgeos++-dev \ libproj-dev \ bash \ build-essential \ cmake \ python3-pip \ git-lfs \ libeigen3-dev \ libpq-dev \ libhdf5-serial-dev \ libnetcdf-dev \ libomp-dev \ libpng-dev \ netcdf-bin \ wget && \ rm -rf /var/lib/apt/lists/* # set up your working directory WORKDIR /app # Download and install dependencies with pip COPY requirements.txt requirements.txt RUN pip3 install --no-cache-dir --upgrade -r requirements.txt # copy application COPY . . # run app CMD <appname>.py ```
14,377,140
When I load my frontend my browser returns those weird errors: ``` Uncaught ReferenceError: Mage is not defined Uncaught ReferenceError: Varien is not defined Uncaught ReferenceError: decorateGeneric is not defined Uncaught ReferenceError: VarienForm is not defined Uncaught ReferenceError: VarienForm is not defined ``` And when I try to access my backend via /admin I'm being redirected to the frontend (home). Tried a million things to detect whats going on but nothing seems to work. My Apache error.log is full of entries like: ``` File does not exist: /var/www/skin script '/var/www/index.php' not found or unable to stat script '/var/www/cron.php' not found or unable to stat ``` **By the way, my magento install isn't on /var/www, it's placed on /var/www/magento** What am I doing wrong? Can I get some help pretty pretty please?
2013/01/17
[ "https://Stackoverflow.com/questions/14377140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
open "CATALOG.XML" file into your theme add this code ``` <default> <reference name="head"> <action method="addJs"><script>varien/product.js</script></action> <action method="addJs"><script>varien/configurable.js</script></action> <action method="addItem"><type>js_css</type><name>calendar/calendar-win2k-1.css</name><params/><!--<if/><condition>can_load_calendar_js</condition>--></action> <action method="addItem"><type>js</type><name>calendar/calendar.js</name><!--<params/><if/><condition>can_load_calendar_js</condition>--></action> <action method="addItem"><type>js</type><name>calendar/calendar-setup.js</name><!--<params/><if/><condition>can_load_calendar_js</condition>--></action> </reference> </default> ``` Under "default" tag i hope it works...
Have a look into the .htaccess and set the RewriteBase correct to /magento Next try: I didn't know "Uncaught Reference Error" (http://stackoverflow.com/questions/2075337/uncaught-referenceerror-is-not-defined) But obviously it is something with JavaScript. Are you sure, that your PHP code is executed? What looks the "HTML" sourcecode like?
70,831,457
For [repositories](https://jalsti.github.io/cov19de/pages/Deutschland.html) with daily updated data plots (including slightly changing background color gradients), I asked myself if there is some preferred format (or compression algorithm) to use, so that git can store them more efficiently, instead of having to re-write about 90% of them, all the time. Is there any kind of image format which is more 'git-friendly' then others?
2022/01/24
[ "https://Stackoverflow.com/questions/70831457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1783801/" ]
#### The theory Formats that are "Git friendly" will be formats that share long identical byte sequences, whether they are binary or text. Now, a lossy binary format will probably change most bytes when you change even just the background colour gradients, whereas a more descriptive text-based format might not. #### Testing things with your own files I recommend this test to calculate the compressed size of different file formats in your actual use case. 0. Before you start, take a sandbox or a clone, and aggressively compress it so we know further compression in later steps is not due to the images being added: run `git gc --aggressive` a few times, until `du .git` yields the same answer twice. Now, for each file format you want to test, copy that sandbox into a new directory and do the following steps: 1. Add one set of images and aggressively compress the repo again by running `git gc --aggressive` a few times, until `du .git` yields the same answer twice. 2. Write down what `du .git` tells you: that's your baseline size. 3. Add and commit a new set of files, slightly changed in the way you describe in your question. 4. Now `du .git` tells you the size of just adding those files into the repo. On commit, Git does not (normally) try to apply delta compression or packing, it just add a new blob for each file being committed, unless an identical blob already existed. 5. Again, run `git gc --aggressive` until the size is stable. 6. Now `du .git` tells you how much Git was able to compress those files, by whatever means it found, possibly delta compression. The size here minus the size at step 2 is your space cost for adding one new set of files. By running the above procedure for different file formats for your images, you'll get an answer specific to your use case. #### Git LFS is probably your friend PS: All that being said, I stand by @Nicolas Voron's answer: unless the size cost above is actually small for the file format you end up choosing, use Git LFS to avoid creating problems in the future when your repo gets too large to clone.
OK, so there seems to be no general answer, respective the answer by the SOF community seems to be: * try it out blindly * do not store images like you want to store them …never mind, probability to meet one who has really good expert knowledge about the compression types playing together would have been real luck. Thanks for trying nevertheless.
48,078,637
Im trying to link a list of ID to a list of date in SQL. This is the data i have both in different table. ``` | Date | ID | |2017-12-25| 1 | |2017-12-26| 2 | |2017-12-27| 3 | ``` I will like to merge this into ``` | Date | ID | |2017-12-25| 1 | |2017-12-25| 2 | |2017-12-25| 3 | |2017-12-26| 1 | |2017-12-26| 2 | |2017-12-26| 3 | |2017-12-27| 1 | |2017-12-27| 2 | |2017-12-27| 3 | ```
2018/01/03
[ "https://Stackoverflow.com/questions/48078637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9168368/" ]
You can write your own: ``` HAS_ATTR_MESSAGE = '{} should have an attribute {}' class BaseTestCase(TestCase): def assertHasAttr(self, obj, attrname, message=None): if not hasattr(obj, attrname): if message is not None: self.fail(message) else: self.fail(HAS_ATTR_MESSAGE.format(obj, attrname)) ``` Then you can subclass `BaseTestCase` insteadof `TestCase` with tests. For example: ``` class TestDict(BaseTestCase): def test_dictionary_attributes(self): self.assertHasAttr({}, 'pop') # will succeed self.assertHasAttr({}, 'blablablablabla') # will fail ```
Going for the most succint answer so far: ``` self.assertTrue(hasattr(myInstance, "myAttribute")) ``` altough Dan's hint in a comment to the OP is also a valid answer: ``` assert hasattr(myInstance, "myAttribute")) ``` just not quite as syntactically aligned with the typical assertions from the unittest package.
115,974
A few months ago I had a gallon of milk in the back of the fridge that stayed fresh for over a month - maybe even two; I lost track. Our house is only me and my wife. We don't drink milk often. I use it more for recipes, and maybe an occasional iced coffee. Since I couldn't repeat this feat I have gone to half-gallons. What I noticed about this gallon in particular is that its plastic container was more opaque than what we normally had been getting. Previously I was getting the supermarket brand with the semi-opaque plastic container. I had gotten this one, white, 100% opaque at another store. I also thought maybe it had something to do with it being in the back of the fridge. Also, being packed in by other fridge mates. But this is something I have always tried to do. Are there steps to try to get milk to last this long? Especially since I don't use it that often. *Further Clarification:* There seems to be some question about how spoilage was determined. I have always and forever smelled my liquid dairy before using. I stand by my nose to let me know when such a product has gone too far. In some cases I have chosen to go a day or two beyond the onset of spoilage. This onset can be detected by a sweet-sour smell. In the instance of this gallon I have posed above, there was no such indication in smelling the milk for at least a month beyond the Best By date. Of that I am sure. There was a period when I hadn't used it. After which I smelled it and it became obvious it was too far gone.
2021/06/08
[ "https://cooking.stackexchange.com/questions/115974", "https://cooking.stackexchange.com", "https://cooking.stackexchange.com/users/28767/" ]
Something to be aware of is where the milk is from and how it's pasteurized. My store brand milk is local and pasteurized only, but some other brands are ultra pasteurized and expected to last much longer. I've experienced similar flukes in the past, generally with ultra-pasteurized milk.
Your experience doesn't surprise me. FuzzyChef went into most of it but I would like to add one more bit of information: Locally, those opaque plastic containers are used for milk that they must be doing something different with the pasteurization as I have seen milk on the store shelf with a date more than a month out. And stored carefully the odds are high that they'll still be good two weeks past the date on the carton. The store fridges seem to be better at keeping them the right temperature than a home fridge--I suspect it has to do with the cooled volume. The store fridge has a huge volume of cold air and air jets by the door--when someone opens the door to take something the warm air they let in is very rapidly replaced with cold air. A home fridge can't cool itself that fast after being opened.
6,066,487
Is there a way to tell that a pointer's memory assignment has been deallocated? I am just starting out in C and I think I am *finally* starting to understand the intricacies of memory management in C. So for example: ``` char* pointer; pointer = malloc(1024); /* do stuff */ free(pointer); /* test memory allocation after this point */ ``` I know that the pointer will still store the memory address until I set `pointer = NULL` - but is there a way to test that the pointer no longer references memory I can use, without having to set it to NULL first? The reason I want to do this is that I have a bunch of unit tests for my C program, and one of them ensures that there are no orphaned pointers after I call a special function which performs a cleanup of a couple of linked lists. Looking at the debugger I can see that my cleanup function is working, but I would like a way to test the pointers so I can wrap them in a unit test assertion.
2011/05/20
[ "https://Stackoverflow.com/questions/6066487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11194/" ]
You could always link against an instrumented version of the libraries (say [electric fence](http://en.wikipedia.org/wiki/Electric_Fence)) for the purposes of unit testing. Not ideal because you introduce a difference in the production and testing environments. And some systems may provide sufficient instrumentation in their version of the standard library. For instance the Mac OS 10.5 library supports calling `abort (3)` on double frees, so if your unit tester can trap signals you are home free. --- Shameless and pointless self promotion: my [little toy c unit testing framework](http://dut.sourceforge.net/) *can* trap signals.
Use good c practices. Example: ``` char* pointer = NULL; /* do stuff */ pointer = malloc(1024);/* malloc does not always work, check it. */ if(pointer == NULL) { /*Help me, warn or exit*/ } /* do stuff */ if(pointer) { free(pointer); pointer = NULL; } /* do stuff */ if(pointer) { /* tested memory allocation stuff */ } ``` Longer, yes, but if you always set a freed pointer to NULL, it's easy to test.
49,643
I want to hide/remove the Personal Options in the **Your Profile** (`wp-admin/profile.php`) admin page. I am aware that solutions for this exist, but I they use jQuery to do hide this section. This works, but when a user has JavaScript disabled in their browser, it will show up again. Therefore it is not a proper way to remove Personal Options. Is there a way to remove the Personal Options section from the HTML source of the page? This means no jQuery or CSS hacks, or core file modification.
2012/04/20
[ "https://wordpress.stackexchange.com/questions/49643", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/14728/" ]
Thanks to the comment from @Per I got it working for 4.5.2 ``` // removes admin color scheme options remove_action( 'admin_color_scheme_picker', 'admin_color_scheme_picker' ); if ( ! function_exists( 'cor_remove_personal_options' ) ) { /** * Removes the leftover 'Visual Editor', 'Keyboard Shortcuts' and 'Toolbar' options. */ function cor_remove_personal_options( $subject ) { $subject = preg_replace( '#<h2>Personal Options</h2>.+?/table>#s', '', $subject, 1 ); return $subject; } function cor_profile_subject_start() { ob_start( 'cor_remove_personal_options' ); } function cor_profile_subject_end() { ob_end_flush(); } } add_action( 'admin_head', 'cor_profile_subject_start' ); add_action( 'admin_footer', 'cor_profile_subject_end' );` ```
I´ve found this solution on: <https://premium.wpmudev.org/blog/how-to-simplify-wordpress-profiles-by-removing-personal-options/?ptm=c&utm_expid=3606929-108.O6f5ypXuTg-XPCV9sY1yrw.2> ``` function hide_personal_options(){ echo "\n" . '<script type="text/javascript">jQuery(document).ready(function($) { $(\'form#your-profile > h3:first\').hide(); $(\'form#your-profile > table:first\').hide(); $(\'form#your-profile\').show(); });</script>' . "\n"; } add_action('admin_head','hide_personal_options'); ``` If you want to be more specific or remove more you should have a look over here: <https://isabelcastillo.com/hide-personal-options-wordpress-admin-profile> You can just add those lines into the function.
32,620,099
Everytime I try to add padding around the outside of an input, it just adds padding between the placeholder and the inside of the input. Does anyone know how to fix this? ``` #ask { padding: 10px 10px 10px 6px; font-size:45px; background-color:#F2F2F2; } <input id="ask" type="text" placeholder = "Ex: How tall is the Gateway Arch" autocomplete="on"/> ```
2015/09/16
[ "https://Stackoverflow.com/questions/32620099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5302703/" ]
Padding it's the space between the element and it's content. Maybe you should try margin. ``` #ask { margin: 10px 10px 10px 6px; font-size:45px; background-color:#F2F2F2; } ```
Try adding a `margin` instead of `padding`. <https://jsfiddle.net/Lw4d1ghs/> Margins change the space outside an element, padding change the space within it. These rules are governed by the CSS **Box Model**: <https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model> [![CSS Box Model](https://i.stack.imgur.com/8jZx6.png)](https://i.stack.imgur.com/8jZx6.png)
25,132,499
How please works following generic casting? ``` private <T, N> N send(final T request) { final String serviceUrl = "someUri" try { return (N) webServiceTemplate.marshalSendAndReceive(serviceUrl, request); } catch (final SoapFaultClientException e) { } } ``` When I call this private method like this: ``` MyReq request = new MyReq(); MyResp response = send(req); ``` How this method casting this object into MyResp object? What mean this in return type: > > < T, N> > > >
2014/08/05
[ "https://Stackoverflow.com/questions/25132499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1089362/" ]
> > < T, N> > > > Is not a return type. N is. ``` private <T, N> N send(final T request) ↑ ``` You have "choosen" type T by passing MyReq argument. Before returning value of marshalSendAndReceive it is being casted to N type. In your case MyResp. ``` <T,N> ``` just declares that this class/method is generic and you may specify generic input type as well ans output.
The method is parameterized with the generic parameters `T` and `N`. It takes an argument of type `T` and returns a reference of type `N`. The return type is not `<T,N>`, it is just `N`.
31,879,390
I need to replace the NA's of each row with non NA's values of different row for a given column for each group let say sample data like: ``` id name 1 a 1 NA 2 b 3 NA 3 c 3 NA ``` desired output: ``` id name 1 a 1 a 2 b 3 c 3 c 3 c ``` Is there a way to perform this in r ?
2015/08/07
[ "https://Stackoverflow.com/questions/31879390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4946087/" ]
We can use `data.table` to do this. Convert the 'data.frame' to 'data.table' (`setDT(df1)`). Grouped by 'id', we replace the 'name' with the non-NA value in 'name'. ``` library(data.table)#v1.9.5+ setDT(df1)[, name:= name[!is.na(name)][1L] , by = id] df1 # id name #1: 1 a #2: 1 a #3: 2 b #4: 3 c #5: 3 c #6: 3 c ``` NOTE: Here I assumed that there is only a single unique non-NA value within each 'id' group. Or another option would be to join the dataset with the `unique` rows of the data after we `order` by 'id' and 'name'. ``` setDT(df1) df1[unique(df1[order(id, name)], by='id'), on='id', name:= i.name][] # id name #1: 1 a #2: 1 a #3: 2 b #4: 3 c #5: 3 c #6: 3 c ``` NOTE: The `on` is only available with the devel version of `data.table`. Instructions to install the devel version are [`here`](https://github.com/Rdatatable/data.table/wiki/Installation) ### data ``` df1 <- structure(list(id = c(1L, 1L, 2L, 3L, 3L, 3L), name = c("a", NA, "b", NA, "c", NA)), .Names = c("id", "name"), class = "data.frame", row.names = c(NA, -6L)) ```
Base R ``` d<-na.omit(df) transform(df,name=d$name[match(id,d$id)]) ``` again assuming one unique value of name per id (forces it)
54,363,139
I am using `sqflite` database to save user list. I have user list screen, which shows list of user and it has a fab button, on click of fab button, user is redirected to next screen where he can add new user to database. The new user is properly inserted to the database but when user presses back button and go backs to user list screen, the newly added user is not visible on the screen. I have to close the app and reopen it,then the newly added user is visible on the screen. I am using `bloc` pattern and following is my code to show user list ``` class _UserListState extends State<UserList> { UserBloc userBloc; @override void initState() { super.initState(); userBloc = BlocProvider.of<UserBloc>(context); userBloc.fetchUser(); } @override void dispose() { userBloc?.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( floatingActionButton: FloatingActionButton( onPressed: () { Navigator.of(context).pushNamed("/detail"); }, child: Icon(Icons.add), ), body: StreamBuilder( stream: userBloc.users, builder: (context, AsyncSnapshot<List<User>> snapshot) { if (!snapshot.hasData) { return Center( child: CircularProgressIndicator(), ); } if (snapshot.data != null) { return ListView.builder( itemBuilder: (context, index) { return Dismissible( key: Key(snapshot.data[index].id.toString()), direction: DismissDirection.endToStart, onDismissed: (direction) { userBloc.deleteParticularUser(snapshot.data[index]); }, child: ListTile( onTap: () { Navigator.of(context).push(MaterialPageRoute( builder: (context) => UserDetail( user: snapshot.data[index], ))); }, title: Text(snapshot.data[index].name), subtitle: Text("Mobile Number ${snapshot.data[index].userId}"), trailing: Text("User Id ${snapshot.data[index].mobileNumber}"), ), ); }, itemCount: snapshot.data.length, ); } }, ), ); } } ``` Following is my bloc code ``` class UserBloc implements BlocBase { final _users = BehaviorSubject<List<User>>(); Observable<List<User>> get users => _users.stream; fetchUser() async { await userRepository.initializeDatabase(); final users = await userRepository.getUserList(); _users.sink.add(users); } insertUser(String name,int id,int phoneNumber) async { userRepository.insertUser(User(id, name, phoneNumber)); fetchUser(); } updateUser(User user) async { userRepository.updateUser(user); } deleteParticularUser(User user) async { userRepository.deleteParticularUser(user); } deleteAllUser() { return userRepository.deleteAllUsers(); } @override void dispose() { _users.close(); } } ``` As Remi posted answer saying i should try `BehaviorSubject` and `ReplaySubject` which i tried but it does not help. I have also called `fetchUser();` inside `insertUser()` as pointed in comments Following is the link of the full example <https://github.com/pritsawa/sqflite_example>
2019/01/25
[ "https://Stackoverflow.com/questions/54363139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Follow up from the comments, it seems you don't have a single instance of your UsersBloc in those two pages. Both the HomePage and UserDetails return a BlocProvider which instantiate a UsersBloc instance. Because you have two blocs instances(which you shouldn't have) you don't update the streams properly. The solution is to remove the BlocProvider from those two pages(HomePage and UserDetail) and wrap the MaterialApp widget in it to make the same instance available to both pages. ``` class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return BlocProvider( bloc: UserBloc(), child:MaterialApp(... ``` The HomePage will be: ``` class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return UserList(), ); } } ``` Remove the BlocProvider from UserDetail as well. In the UsersBloc then call fetchUser() inside the insertUser() method after the user insertion, to requery the database and update the users stream. Also as Rémi Rousselet said, use one of the subjects that return previous values.
The issue is that you're using a `PublishSubject`. When a new listener subscribes to a `PublishSubject`, it does not receive the previously sent value and will only receive the next events. The easiest solution is to use a `BehaviorSubject` or a `ReplaySubject` instead. These two will directly call their listener with the latest values.
13,851,629
In Java, I have been asked to store integer values in a singly-linked list and then print the elements stored in the list. Here is what I came up with: ``` int max = 10; List<Integer> list = new ArrayList<Integer>(); for (int num = 0; i < max; i++){ list.add(num); } System.out.print(list); ``` I was wondering, is ArrayList the same thing as a singly-linked list? I want to make sure that I'm answering the question correctly. Does this make sense? Thanks!
2012/12/13
[ "https://Stackoverflow.com/questions/13851629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1735089/" ]
No - `ArrayList` is not a linked list at all - it's an array list. `ArrayList` stores its elements in an array, whereas linked lists store them in arbitrary memory by linking objects together. `LinkedList` is a doubly-linked list, and I'm sure that there are various singly linked list implementations you could grab, but given that this is an assignment you'll either be marked down or fail outright if you try to hand in code using someone else's implementation. Instead, find an [article](http://en.wikipedia.org/wiki/Linked_list) etc. which describes linked lists and try to implement one yourself. Generally these are built in java by having a class `SomeClass` containing a forward link of type `SomeClass` and a value. You build the list by linking each `SomeClass` instance to the next through the forward link.
No `ArrayList` is definitely *not* the same as a singly linked list. In fact, it is not a *linked* list at all: it is a list that uses an array for its backing storage. This lets you access `ArrayList` in arbitrary order, as opposed to linked lists, that must be accessed sequentially. Java library has a doubly-linked list, but no singly-linked one; you need to write it yourself. There are several good implementations available on the internet; take a look at [this answer on the codereview site](https://codereview.stackexchange.com/a/7193/16837) to gain some ideas on how to implement a singly linked list of your own.
56,275,023
So, I have the main div (modal-container) which taking a full page and inside the main div and having another div (modal-inner) with two buttons. The main DIV was set to full height/width of the page and inside DIV (modal-inner) having calc(100% - 40px) width of screen. Through Jquery I have added two functions on each button click event, like jq-button-ok & jq-button-cancel. Now when I try to add a click event into a modal-container but its call two buttons click function too at the same time. What would be the solution? HTML: ``` <div class="modal-container" role="dialog"> <div class="modal-inner" role="document"> <div class="modal-content"> <div class="modal-body"> <button class="button jq-button-ok">OK</button> <button class="button jq-button-cancel">Cancel</button> </div> </div> </div> </div> ``` CSS: ``` .modal-container { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 102; background: rgba(216,216,216,.25); transition: 0.3s opacity ease-in; opacity: 1; } .modal-inner { position: static; width: 500px; height: auto; max-width: calc(100% - 20px); transition: none; transform: none; } ``` Jquery: ``` $(document).ready(function () { $("body").on("click", ".jq-button-ok", function (e) { e.preventDefault(); callfunstionone(); }); $("body").on("click", ".jq-button-cancel", function (e) { e.preventDefault(); callfunstiontwo(); }); $("body").on("click", ".modal-container:not(.modal-inner)", function (e) { callfunstionfour(); }); }); ```
2019/05/23
[ "https://Stackoverflow.com/questions/56275023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2479903/" ]
Instead of using `e​.prevent​Default()`, you should use [`e.stop​Propagation()`](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation): > > The `stopPropagation()` method of the Event interface prevents further propagation of the current event in the ***capturing*** and ***bubbling*** phases. > > > ```js $(document).ready(function () { $("body").on("click", ".jq-button-ok", function (e) { e.stopPropagation(); //callfunstionone(); alert('You have clicked button-ok') }); $("body").on("click", ".jq-button-cancel", function (e) { e.stopPropagation(); //callfunstiontwo(); alert('You have clicked cancel') }); $("body").on("click", ".modal-container:not(.modal-inner)", function (e) { //callfunstionfour(); alert('You have clicked modal-container but not modal-inner') }); }); ``` ```css .modal-container { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 102; background: rgba(216,216,216,.25); transition: 0.3s opacity ease-in; opacity: 1; } .modal-inner { position: static; width: 500px; height: auto; max-width: calc(100% - 20px); transition: none; transform: none; } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="modal-container" role="dialog"> <div class="modal-inner" role="document"> <div class="modal-content"> <div class="modal-body"> <button class="button jq-button-ok">OK</button> <button class="button jq-button-cancel">Cancel</button> </div> </div> </div> </div> ```
The click event is propagating up the dom from the button to the div so both elements event handler gets triggered. You can stop the propagation with `Event.stopImmediatePropagation` ```js $(document).ready(function () { $("body").on("click", ".jq-button-ok", function (e) { e.preventDefault(); console.log('callfunstionone()'); e.stopImmediatePropagation(); }); $("body").on("click", ".jq-button-cancel", function (e) { e.preventDefault(); console.log('callfunstiontwo()'); e.stopImmediatePropagation(); }); $("body").on("click", ".modal-container", function (e) { console.log('callfunstionfour()'); }); }); ``` ```css .modal-container { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 102; background: rgba(216,216,216,.25); transition: 0.3s opacity ease-in; opacity: 1; } .modal-inner { position: static; width: 500px; height: auto; max-width: calc(100% - 20px); transition: none; transform: none; } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script> <div class="modal-container" role="dialog"> <div class="modal-inner" role="document"> <div class="modal-content"> <div class="modal-body"> <button class="button jq-button-ok">OK</button> <button class="button jq-button-cancel">Cancel</button> </div> </div> </div> </div> ```
80,062
So the desired result is a compound that can be left in relatively isolated area, isolated such that weather has no direct affect on the area, and that will ignite/explode when touched, even after sitting in this area for a few thousand years. I am aware of things like touch powder that will explode violently when touched but that is a little too volatile. Simply grazing the compound should not be enough to set it off but resting a hand or something similar should. Is such a compound scientifically realistic? If there is no chemical that can achieve this under the long time constraint then what would be a simple alternative? The lower the amount of developed science that it would take to achieve this affect, the better.
2017/05/04
[ "https://worldbuilding.stackexchange.com/questions/80062", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/37850/" ]
No. You can't both have isolated a material for 1000's of years from everything\* in its environment that will degrade/contaminate it and have it be exposed for human touch. (\* pollutants (SO2, NOx, CO2, Ozone), oxygen, humidity, UV light, visible light, dust, dirt, bacteria, mold, insects, mice, etc. etc. Not to mention the random rat droppings, bat droppings, fallen leaves, pebbles, etc. Not to mention natural temperature variations.) You misuse the term "volatile", I believe. You mean unstable? "Lowest tech" presumes that technology is linear. It. is. not. (Which is lower tech: black powder or penicillin?) The most realistic approach has been mentioned: a trap, perhaps a pressure plate connected to a mechanism that mixes two components. If I were going to build a trap which would work after 1000's of years, and which would explode or ignite after such a long time, I'd use hypergolics (see: <https://en.wikipedia.org/wiki/Hypergolic_propellant>). For instance, kerosene in one sealed bottle, aniline in a second, and nitric acid (fuming or "white" preferably) in a 3rd. Designing and building such a trap would include (imho) the *intention* that it be operational for 1000's of years, and that's a problem. At that time scale, seismic motions have to be considered. There would have to be assumptions made about climate and geography. Components would have to be very stable. There's nothing particularly "high tech" as far as aniline or nitric acid. Aniline is a component of coal tar, which itself was "discovered" in 1665 C.E. (after that date physical separation of aniline would have been possible, if needed.) Nitric acid in the 13th Century, although the concentrated form I'm referring to may not have been available until the 1700's. The problem I see is the trap's mechanism. I think it would be difficult to build one which you could be relatively sure would work after 1000's of years, unless kept in a very stable environment. And I know of no realistic way to keep an environment stable for 1000's of years.
A single drop of antimatter kept inside of a magnetic suspension chamber with a charge that lasts 1,000 years might do it. But making it sensitive enough to be set off would be an issue. Also the degradation of the materials used to construct the canister would be questionable.
53,534,397
I have to say who is the scientist who have been the most in mission. I tried this code but it wasn't successful: ``` select name from scientist, mission where mission.nums = chercheur.nums having count(*) = (select max(count(numis)) from mission, scientist where mission.nums = chercheur.nums group by name) ``` I have done several modifications for this request but I only obtain errors (ora-0095 and ora-0096 if I remember correctly). Also, I create my tables with: ``` CREATE TABLE Scientist (NUMS NUMBER(8), NAME VARCHAR2 (15), CONSTRAINT CP_CHER PRIMARY KEY (NUMS)); CREATE TABLE MISSION (NUMIS NUMBER(8), Country VARCHAR2 (15), NUMS NUMBER(8), CONSTRAINT CP_MIS PRIMARY KEY (NUMIS), CONSTRAINT CE_MIS FOREIGN KEY (NUMS) REFERENCES SCIENTIST (NUMC)); ```
2018/11/29
[ "https://Stackoverflow.com/questions/53534397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10721089/" ]
Step 0 : Format your code :-) It would make it much easier to visualize Step 1 : Get the count of Numis by Nums in the Mission table. This will tell you how many missions were done by each Nums This is done in the cte block cnt\_by\_nums Next to get the name of the scientist by joining cnt\_by\_nums with scientist table. After that you want to get only those scientists who have the cnt\_by\_missions as the max available value from cnt\_by\_num ``` with cnt_by_nums as (select Nums,count(Numis) as cnt_missions from mission group by Nums ) select a.Nums,max(b.Name) as name from cnt_by_nums a join scientist b on a.Nums=b.Nums group by a.Nums having count(a.cnt_missions)=(select max(a1.cnt_missions) from cnt_by_nums a1) ```
As you don't select the name of your scientist (only count their missions) you don't need to join those tables within the subquery. Grouping over the foreign key would be sufficient: ``` select count(numis) from mission group by nums ``` You column names are a bit weird but that's your choice ;-) Selecting only the scientist with the most mission references could be achieved in two ways. One way would be your approach where you may get multiple scientists if they have the same max missions. The first problem you have in your query is that you are checking an aggregation (HAVING COUNT(\*) = ) without grouping. You are only grouping your subselect. Second, you could not aggregate an aggregation (MAX(COUNT)) but you may select only the first row of that subselect ordered by it's size or select the max of it by subquerying the subquery. Approach with only one line: ``` select s.name from scientist s, mission m where m.nums = s.nums group by name having count(*) = (select count(numis) from mission group by nums order by 1 desc fetch first 1 row only) ``` Approach with double subquery: ``` select s.name from scientist s, mission m where m.nums = s.nums group by name having count(*) = (select max(numis) from (select count(numis) numis from mission group by nums) ) ``` Second approach would be doing the FETCH FIRST on yur final result but this would give you exactly 1 scientist even if there are multiple with the same max missions: ``` select s.name from scientist s, mission m where m.nums = s.nums group by name order by count(*) desc fetch first 1 row only ``` Doing a cartisian product is not state of the art but the optimizer would make it a "good join" with the given reference in the where clause. Made these with IBM Db2 but should also work on Oracle.
9,974,392
I'm building a mvc application which will communicate with flash via AMF, anybody knows if there is any **AMF ActionResult** available on the web ? **EDIT**: using @mizi\_sk answer (but without using IExternalizable) I did this ActionResult: ``` public class AmfResult : ActionResult { private readonly object _o; public AmfResult(object o) { _o = o; } public override void ExecuteResult(ControllerContext context) { context.HttpContext.Response.ContentType = "application/x-amf"; using (var ms = new MemoryStream()) { // write object var writer = new AMFWriter(ms); writer.WriteData(FluorineFx.ObjectEncoding.AMF3, _o); context.HttpContext.Response.BinaryWrite(ms.ToArray()); } } } ``` but the response handler on the flash side doesn't get hit. in [Charles](http://www.charlesproxy.com/) at the Response->Amf tab I see this error: > > Failed to parse data (com.xk72.amf.AMFException: Unsupported AMF3 packet type 17 at 1) > > > this is the raw tab: ``` HTTP/1.1 200 OK Server: ASP.NET Development Server/10.0.0.0 Date: Mon, 14 May 2012 15:22:58 GMT X-AspNet-Version: 4.0.30319 X-AspNetMvc-Version: 3.0 Cache-Control: private Content-Type:application/x-amf Content-Length: 52 Connection: Close 3/bingo.model.TestRequest param1coins name ``` and the Hex tab: ``` 00000000 11 0a 33 2f 62 69 6e 67 6f 2e 6d 6f 64 65 6c 2e 3/bingo.model. 00000010 54 65 73 74 52 65 71 75 65 73 74 0d 70 61 72 61 TestRequest para 00000020 6d 31 0b 63 6f 69 6e 73 09 6e 61 6d 65 01 04 00 m1 coins name 00000030 06 05 6a 6f jo ```
2012/04/02
[ "https://Stackoverflow.com/questions/9974392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/112100/" ]
The trick is to use `FluorineFx.IO.AMFMessage` with AMFBody as a result object and set a `Content` property. You can see this in Charles proxy with other working examples (I've used great [WebORB examples](http://www.themidnightcoders.com/examples), specifically [Flash remoting Basic Invocation AS3](http://www.themidnightcoders.com/examples?eid=1305140498614)) I've updated AMFFilter to support `Response` parameter that AMFBody needs. Maybe it could be solved more elegantly by some current context cache, don't know. Code follows: ``` public class AmfResult : ActionResult { private readonly object _o; private readonly string _response; public AmfResult(string response, object o) { _response = response; _o = o; } public override void ExecuteResult(ControllerContext context) { context.HttpContext.Response.ContentType = "application/x-amf"; var serializer = new AMFSerializer(context.HttpContext.Response.OutputStream); var amfMessage = new AMFMessage(); var amfBody = new AMFBody(); amfBody.Target = _response + "/onResult"; amfBody.Content = _o; amfBody.Response = ""; amfMessage.AddBody(amfBody); serializer.WriteMessage(amfMessage); } } ``` For this to work, you need to decorate method on the controller with AMFFilter ``` public class AMFFilterAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { if (filterContext.HttpContext.Request.ContentType == "application/x-amf") { var stream = filterContext.HttpContext.Request.InputStream; var deserializer = new AMFDeserializer(stream); var message = deserializer.ReadAMFMessage(); var body = message.Bodies.First(); filterContext.ActionParameters["target"] = body.Target; filterContext.ActionParameters["args"] = body.Content; filterContext.ActionParameters["response"] = body.Response; base.OnActionExecuting(filterContext); } } } ``` which would look something like this ``` [AMFFilter] [HttpPost] public ActionResult Index(string target, string response, object[] args) { // assume target == "TestMethod" and args[0] is a String var message = Convert.ToString(args[0]); return new AmfResult(response, "Echo " + message); } ``` Client side code for reference ``` //Connect the NetConnection object var netConnection: NetConnection = new NetConnection(); netConnection.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus); netConnection.connect("http://localhost:27165/Home/Index"); //Invoke a call var responder : Responder = new Responder( handleRemoteCallResult, handleRemoteCallFault); netConnection.call('TestMethod', responder, "Test"); private function onNetStatus(event:NetStatusEvent):void { log(ObjectUtil.toString(event.info)); } private function handleRemoteCallFault(...args):void { log(ObjectUtil.toString(args)); } private function handleRemoteCallResult(message:String):void { log(message); } private static function log(s:String):void { trace(s); } ``` If you would like to return fault, just change this line in AMFResult ``` amfBody.Target = _response + "/onFault"; ``` *I like ObjectUtil.toString() formatting, but just remove it if you don't have Flex linked.* *BTW, do you really need this in ASP.NET MVC? Maybe simple ASHX handler would suffice and performance would be better, I don't know. The MVC architecture is a plus I presume.*
I haven't seen an ActionResult implemented on the web but there's [FluorineFX.NET](http://www.fluorinefx.com/) which supports AMF.
37,827,375
In Eclipse, how to debug only a part of the code (Not from the starting). In the below code, the debugging is getting stuck at LINE 1 forever, no matter how many times I press F6 . I want to skip the first FOR loop , and start debugging from LINE 2. NOTE : LINE 1 runs a query which takes about 20 mins time. I already ran once . Can we use the previous output only, instead of the query running again. ``` ExecutorService es = Executors.newFixedThreadPool(2); Future<ResultSet> f1; Future<ResultSet> f2; for(int i=0;i<futures.size();i++){ feed_rs.add(futures.get(i).get()); // <=== LINE 1 } for(int i=0;i<feed_rs.size();i++){ // More code // <=== LINE 2 } ```
2016/06/15
[ "https://Stackoverflow.com/questions/37827375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3254725/" ]
I solved it by adding this in the model. ``` ng-model-options="{timezone: 'UTC'}" ``` See the updated plunkr here. <http://plnkr.co/edit/x0WLHNG7l5VBRU5tN8Q1?p=preview>
I think, time zone is causing this issue. Please refer the below URL: <https://gist.github.com/weberste/354a3f0a9ea58e0ea0de>
50,684,578
I have the following dictionary representing `id:parent. {1: 2, 3: 1}`. I need to loop and check if `id == parent` then it is a child. For example here: `1=1` so `3` is the child of `1`. I will append it to the dictionary accordingly. Any ideas? ``` d={1:2, 3:1} for node in d: ```
2018/06/04
[ "https://Stackoverflow.com/questions/50684578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3057109/" ]
Do as follows. See comments within the code and remarks at the end. ``` const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); exports.sendNotif = functions.database.ref('/customers/{id}/chats/{chatId}').onUpdate((change, context) => { //const afterData = change.after.val(); //I don't think you need this data (i.e. newMessage: true) const chatId = context.params.chatId; //the value of {chatId} in '/customers/{id}/chats/{chatId}/' that you passed as parameter of the ref //You query the database at the messages/chatID location and return the promise returned by the once() method return admin.database().ref('/messages/' + chatId).once('value').then(snapshot => { //You get here the result of the query to messagges/chatId in the DataSnapshot const messageContent = snapshot.val().lastMessage; var myoptions = { priority: "high", timeToLive: 60 * 60 * 24 }; // Notification data which supposed to be filled via last message. const notifData = { "notification": { "body" : messageContent, //I guess you want to use the message content here?? "title" : "Portugal vs. Denmark", "sound": "default" } }; return admin.messaging().sendToDevice(user.fcm.token, notifData, myoptions); ) .catch(function(error) { console.log('Error sending message:', error); }); }); ``` Note that I have changed the code from ``` exports.sendNotif = functions.database.ref('/customers/{id}/chats/{id}/').onUpdate((event) => { ``` to ``` exports.sendNotif = functions.database.ref('/customers/{id}/chats/{chatId}/').onUpdate((change, context) => { ``` The latter is the new syntax for Cloud Functions v1.+ which have been released some weeks ago. You should update your Cloud Function version, as follows: ``` npm install firebase-functions@latest --save npm install firebase-admin@5.11.0 --save ``` See this documentation item for more info: <https://firebase.google.com/docs/functions/beta-v1-diff#realtime-database>
The fact that you are successfully updating the "customers/uid/chats/chat" branch says that you have the chat id/uid. All you do is fetch the "messages/chat" and read it. Since you have the chat id, a `.Promise.all` approach works here. Something like: ``` var promises = [writeChat(),readChat()]; Promise.all(promises).then(function (result) { chat = result[1]; //result[1].val() }).catch(function (error) { console.error("Error adding document: ", error); }); function readChat() { return new Promise(function (resolve, reject) { var userId = firebase.auth().currentUser.uid; return firebase.database().ref('/users/' + userId).once('value').then(function(snap) { resolve (snap) // ... }).catch(function (error) { reject(error); }); }); } ```
569
Is there some algorithm out there that can return some value indicating a level of randomness? I believe it's called [Data Entropy](http://en.wikipedia.org/wiki/Entropy_%28information_theory%29). I recently read this article: <http://faculty.rhodes.edu/wetzel/random/mainbody.html> Would his approach of analyzing coin flips apply for bytes? Should I drop down to the bit level where it's true/false again or is there a way to determine based on the full byte value? Are their better analyses than this article?
2010/08/25
[ "https://cstheory.stackexchange.com/questions/569", "https://cstheory.stackexchange.com", "https://cstheory.stackexchange.com/users/499/" ]
From random.org: > > Oddly enough, it is theoretically impossible to prove that a random number generator is really random. Rather, you analyse an increasing amount of numbers produced by a given generator, and depending on the results, your confidence in the generator increases (or decreases, as the case may be) > > > More information [can be found here](http://www.random.org/analysis/)
As other answers mentioned, the decision version of this problem (like the Halting problem and a number of other problems like the Tiling Problem) is undecidable. However, I believe you are asking about practical ways to measure the randomness of a collection of bits. Standard practice here is to run the data through a series of randomness tests, like the Chi-Square test.
2,246,940
I have a problem accessing a database through a JDBC connection. ``` End of stream was detected on a read ``` The error occurs at several different points at random. I appreciate any help.
2010/02/11
[ "https://Stackoverflow.com/questions/2246940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/229882/" ]
Use `Ctrl+F5` to start running without the debugger. This can also be accessed from the Debug menu, as "Start without debugging". You can also change the project configuration from Debug to Release, as explained [here](http://msdn.microsoft.com/en-us/library/wx0123s5.aspx).
`[Debug - Start without Debugging] or Ctrl F5`. Or launch your app outside Visual Studio.
3,892,042
I need to post data to a URL (https://somesite.com) to download file in responseStrem based on the parameters I posted. How can I do that using a C# console application? Parameters: filename, userid, password, type
2010/10/08
[ "https://Stackoverflow.com/questions/3892042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/470310/" ]
Take a look at the `System.Net.WebClient` class, it can be used to issue requests and handle their responses, as well as to download files: <http://www.hanselman.com/blog/HTTPPOSTsAndHTTPGETsWithWebClientAndCAndFakingAPostBack.aspx> <http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.90).aspx>
Insted of using System.Net.WebClient I would recommend to have a look on System.Net.Http.HttpClient which was introduced with net 4.5 and makes your life much easier. Also microsoft recommends to use the HttpClient on this article <http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.90).aspx> An example could look like this: ``` var client = new HttpClient(); var content = new MultipartFormDataContent { { new StringContent("myUserId"), "userid"}, { new StringContent("myFileName"), "filename"}, { new StringContent("myPassword"), "password"}, { new StringContent("myType"), "type"} }; var responseMessage = await client.PostAsync("some url", content); var stream = await responseMessage.Content.ReadAsStreamAsync(); ```
72,116
I understand about race conditions and how with multiple threads accessing the same variable, updates made by one can be ignored and overwritten by others, but what if each thread is writing the same value (not different values) to the same variable; can even this cause problems? Could this code: GlobalVar.property = 11; (assuming that property will never be assigned anything other than 11), cause problems if multiple threads execute it at the same time?
2008/09/16
[ "https://Stackoverflow.com/questions/72116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The problem comes when you read that state back, and do something about it. Writing is a red herring - it is true that as long as this is a single word most environments guarantee the write will be atomic, but that doesn't mean that a larger piece of code that includes this fragment is thread-safe. Firstly, presumably your global variable contained a different value to begin with - otherwise if you know it's always the same, why is it a variable? Second, presumably you eventually **read** this value back again? The issue is that presumably, you are writing to this bit of shared state for a reason - to signal that something has occurred? This is where it falls down: when you have no locking constructs, there is no implied order of memory accesses at all. It's hard to point to what's wrong here because your example doesn't actually contain the **use** of the variable, so here's a trivialish example in neutral C-like syntax: ``` int x = 0, y = 0; //thread A does: x = 1; y = 2; if (y == 2) print(x); //thread B does, at the same time: if (y == 2) print(x); ``` Thread A will always print 1, but it's completely valid for thread B to print 0. The order of operations in thread A is only required to be observable from code executing in thread A - thread B is allowed to see any combination of the state. The writes to x and y may not actually happen in order. This can happen even on single-processor systems, where most people do not expect this kind of reordering - your compiler may reorder it for you. On SMP even if the compiler doesn't reorder things, the memory writes may be reordered between the caches of the separate processors. If that doesn't seem to answer it for you, include more detail of your example in the question. Without the use of the variable it's impossible to definitively say whether such a usage is safe or not.
I would expect the result to be undetermined. As in it would vary from compiler to complier, langauge to language and OS to OS etc. So no, it is not safe WHy would you want to do this though - adding in a line to obtain a mutex lock is only one or two lines of code (in most languages), and would remove any possibility of problem. If this is going to be two expensive then you need to find an alternate way of solving the problem
22,170,944
I have a string: `[1, 2, 3, 4]`. I need to get only integers `1 2 3 4`. I tried the following splits: ``` str.split(","); str.split("\\D\\s"); ``` Both splits return four elements: [1 2 3 4], but I don't need these brackets `[ ]`. What is wrong with split regexp? **updated** I had to mention that the case when each number is wrapped with `[ ]` can occur.
2014/03/04
[ "https://Stackoverflow.com/questions/22170944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1049521/" ]
You could try filtering out unwanted elements first and then split: ``` String filtered = str.replaceAll("[^0-9,]",""); String[] numbers = filtered.split(","); ```
replace the brackets `[ ]`and then split ``` str.replaceAll("\\[", "").replaceAll("\\]", "").split(","); ```
81,724
While looking up my most favorite in-rem case (["US vs. approximately 64k Pounds of Shark Fins"](https://en.wikipedia.org/wiki/United_States_v._Approximately_64,695_Pounds_of_Shark_Fins)), I stumbled over a few quite strange ones: * [Pensylvania was sued **by** a car](https://en.wikipedia.org/wiki/One_1958_Plymouth_Sedan_v._Pennsylvania) * [Kansas was sued **by** some books](https://en.wikipedia.org/wiki/Quantity_of_Books_v._Kansas) * [Massachusetts was sued **by** a single book](https://en.wikipedia.org/wiki/Memoirs_v._Massachusetts) * [The US tops ridiculousness: they **were** sued by a truck full of jam](https://en.wikipedia.org/wiki/62_Cases_of_Jam_v._United_States) All of these are named "Item v State" and technically, it was a representative for the items' owners that sued, but **how come we name these cases "Item vs. State"** and not "Representative for Item vs. State" or "Owner v State"?
2022/07/02
[ "https://law.stackexchange.com/questions/81724", "https://law.stackexchange.com", "https://law.stackexchange.com/users/10334/" ]
The original filed case *would* have been "Government v. Item", with the government (plaintiff) suing the item (defendant), not the other way around. But these are appellate cases, and the title convention there is "Appellant v. Respondent", regardless of who was the original plaintiff or defendant. So in each case, the item presumably lost in some lower court and is now appealing to SCOTUS. Taking *62 Cases of Jam* as an example and chasing the citations, the original case in US District Court for the District of New Mexico was [*United States v. 62 Cases*, 87 F. Supp. 735 (D.N.M. 1949)](https://casetext.com/case/united-states-v-62-cases-etc). The government sought to condemn the jam on the grounds that it was only 25% fruit, where federal standards for jam required that it must contain at least 45% (or more depending on the type of fruit). The District Court dismissed the "libel" on the grounds that the product was clearly labeled "imitation". The government [appealed to the Tenth Circuit](https://law.justia.com/cases/federal/appellate-courts/F2/183/1014/266864/) (183 F.2d 1014 (10th Cir. 1950)); here the case was still titled "US v. 62 Cases" since the United States was the appellant; appeals cases are always titled "Appellant v. Respondent". The circuit court reversed, ruling that since it looks and tastes like jam, it has to meet the standards for jam, its label notwithstanding, and ordered the jam to be condemned. The jam [petitioned for certiorari to the US Supreme Court](https://supreme.justia.com/cases/federal/us/340/593/), (340 U.S. 593 (1951)), and now for the first time the title of the case is "62 Cases of Jam v. US" since the jam is now the petitioner. Again, "Petitioner v. Respondent" is the norm. As the defendant party was "62 Cases of Jam" throughout the lower courts, it wouldn't make sense to change it to "Fred Smith, Owner of 62 Cases of Jam" at this point. SCOTUS reversed, and the jam was finally exonerated, free to resume its ordinary jammy activities.
The reason is that the item "did" a wrong, therefore the police are seizing the item. A [civil forfeiture case](https://www.law.cornell.edu/wex/forfeiture) – against the item – will be filed by the government. The item is not protected by the Constitution, and in case the owner finds out and sues, the government's case rests on whether the item has the "result of" relation to a crime, and they just have to prove that it is "more likely than not" (the owner does not have to be even allegedly culpable). As that article says, > > Civil forfeiture rests on the idea (a legal fiction) that the > property itself, not the owner, has violated the law. Thus, the > proceeding is directed against the res, or the thing involved in some > illegal activity specified by statute. Unlike criminal forfeiture, in > rem forfeiture does not require a conviction or even an official > criminal charge against the owner. > > > In the [case decided by SCOTUS](https://supreme.justia.com/cases/federal/us/380/693/), the car appealed a PA Supreme court ruling [Commonwealth v. One 1958 Plymouth Sedan](https://casetext.com/case/com-v-one-1958-ply-sdn-mcgonigle-1), because the car complained about that ruling where the Commonwealth complained about the car: this explains the order of parties being different.
144
Mount Hood in Oregon is a dormant volcano, and in Washington Mount St. Helens and Mt. Ranier are both active volcanoes. What causes this line of volcanoes running parallel to the coastline along the northwest coast of North America?
2014/04/16
[ "https://earthscience.stackexchange.com/questions/144", "https://earthscience.stackexchange.com", "https://earthscience.stackexchange.com/users/53/" ]
The Cascades (the volcanic range that Mt. St. Helens and Mt. Ranier are a part of) are "arc volcanoes" (a.k.a. "a volcanic arc", etc). Volcanic arcs form at a regular distance (and fairly regular spacing) behind subduction zones. Subduction zones are areas where dense oceanic crust dives beneath more buoyant crust (either younger oceanic crust or continental crust). The down-going oceanic plate begins to generate fluids due to metamorphic reactions that occur at a particular pressure and temperature. These fluids cause partial melting of the mantle above the down-going slab. (Contrary to what's often taught, the oceanic crust itself doesn't melt at this point - it's the mantle above it that does.) This causes arc volcanoes to form at the surface at approximately where the down-going oceanic slab reaches ~100km depth (I may be mis-remembering the exact number). However, there's an interesting story with the Cascades, the San Andreas Fault, and the Sierra Nevada. Basically, Sierras are the old volcanic arc before an oceanic spreading ridge tried to subduct off the coast of California. (Search for the Farallon plate.) The ridge was too buoyant to subduct, so subduction stopped, shutting off the supply of magma to the volcanic arc. Because the motion of the Pacific Plate (on the other side of the spreading ridge that tried to subduct) was roughly parallel to the margin of North America, a strike slip boundary formed instead: The San Andreas Fault. Northward, there's still a remnant of the Farallon plate that's subducting beneath Northern CA, OR, WA, and BC. Therefore, the Cascades are still active arc volcanoes, while the Sierras are just the "roots" of the old arc.
It's because in this place two tectonic plates meet. Most volcanoes are in such place - where there is border between tectonic plates.
2,326,741
I've got a string like this: ``` &lt;block trace="true" name="AssignResources: Append Resources"&gt; ``` I need to get the word (or the characters to next whitespace) after `&lt;` (in this case *block*) and the words before `=` (here *trace* and *name*). I tried several regex patterns, but all my attempts return the word with the "delimiters" characters included... like `;block`. I'm sure it's not that hard, but I've not found the solution yet. Anybody's got a hint? Thanks. Btw: I want to replace the pattern matches with `gsub`. EDIT: Solved it with following regexes: 1) `/\s(\w+)="(.*?)"/` matches all attr and their values in $1 and $2. 2) `/&lt;!--.*--&gt;/` matches comments 3) `/&lt;([\/|!|\?]?)([A-Za-z0-9]+)[^\s|&gt;|\/]*/` matches all tag names, wheter they're in a closing tag, self closing tag, `<?xml>`-tag or DTD-tag. `$1` includes optional prefixed `/ ! or ?` or nothing and `$2` contains the tagname
2010/02/24
[ "https://Stackoverflow.com/questions/2326741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/273433/" ]
Its looks so much like [parsing HTML with regex](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) to me Ruby has very good html parser called [Nokogiri](http://nokogiri.org/) And Here is howto for that ``` require 'nokogiri' html=Nokogiri::HTML('<block trace="true" name="AssignResources: Append Resources">') html.xpath("//*").each do |s| puts s.node_name #block puts s.keys #trace, name puts s.values #true, AssignResources: Append Resources end ```
Most probably you should go with Nokigiri or something similar. I couldn't fit it in one gsub but in two: ``` >> m,r=0,["&lt;blockie ", " tracie=", " namie="] >> s.gsub(/&lt;.*?([^\s]+)\s/, r[0]).gsub(/\s([^=]+)=/) {|ma| m+=1; r[m]} => "&lt;blockie tracie="true" namie="AssignResources: Append Resources"&gt;" ```
252,286
This sounds dumb, but I can't get it to work. I think i just dont' understand the difference between `%%v, %v% and %v` Here's what I'm trying to do: ``` for %%v in (*.flv) do ffmpeg.exe -i "%%v" -y -f mjpeg -ss 0.001 -vframes 1 -an "%%v.jpg" ``` This successfully generates a thumbnail for each of the movies, but the problem is: ``` movie.flv -> movie.flv.jpg ``` So what I would like to do is pull the last 4 characters off `%%v` and use that for the second variable. I've been trying things like this: ``` %%v:~0,-3% ``` But it's not working, nor are any of the iterations of that that I could think of. Any ideas?
2008/10/31
[ "https://Stackoverflow.com/questions/252286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10680/" ]
For people who found this thread looking for how to actually perform string operations on for-loop variables (uses [delayed expansion](http://ss64.com/nt/delayedexpansion.html)): ``` setlocal enabledelayedexpansion ... ::Replace "12345" with "abcde" for %%i in (*.txt) do ( set temp=%%i echo !temp:12345=abcde! ) ```
``` for %%v in (*.flv) do ffmpeg.exe -i "%%v" -y -f mjpeg -ss 0.001 -vframes 1 -an "%%~nv.jpg" ``` From "help for": ``` %~I - expands %I removing any surrounding quotes (") %~fI - expands %I to a fully qualified path name %~dI - expands %I to a drive letter only %~pI - expands %I to a path only %~nI - expands %I to a file name only %~xI - expands %I to a file extension only %~sI - expanded path contains short names only %~aI - expands %I to file attributes of file %~tI - expands %I to date/time of file %~zI - expands %I to size of file %~$PATH:I - searches the directories listed in the PATH environment variable and expands %I to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, then this modifier expands to the empty string ```
161,082
I would like to install a monitoring services (Monit or others) on my web server and am looking for recommendation. I have no idea which is good, and what parameters which I should evaluate on, and which is a good for for my needs. Some which I saw and am evaluating are Monit <http://mmonit.com/monit/> God <http://god.rubyforge.com> Daemontools <http://cr.yp.to/daemontools.html> About my server Ubuntu/Apache/Nginx/Mysql Serving Django application. Some other services I need to be monitoring. Openoffice running headless. Custom python daemons. Xvfb. Parameters which are important are, (in order). Reliable. Easy to install and monitor. Not too resource heavy. Unixy. Send email when a service goes down. Has webpage with status of services. Which of the above or other tools is best for my needs.
2010/07/16
[ "https://serverfault.com/questions/161082", "https://serverfault.com", "https://serverfault.com/users/28709/" ]
Monit satisfies all you requirements. It is easy to install, setup, add services, send emails and has a builtin http server. We've been running monit for over a year now without downtime. I've not tried the others.
easy to install = may be you are not going to receive all the info you want. May be you can install munin, its easy and as a munin-node you'll be able to monitorize mysql,cpu, ram and other stuff. <http://www.howtoforge.com/server_monitoring_monit_munin> It's very easy to install but it will not send any mail to alert you. If you would like to receive some mails, you can just install postfix as internetmail and mutt or mailx as mailer. So you can launch cron scripts checking whatever you would like to check, even fix it if its a process eating all the ram, and then send a mail. On the other hand, nagios+cacti, nagios as monitor and cacti as mail and checkers. It's hard to install and configure on the first time, so may be you can go and check Groundwork, a fork from nagios which is not so free but it can be free as beer. You can try it as an vmware appliance for test purposes. Also if you have money, you can get support and is nagios with stuff on top of it, so it will just work. Finally if you would like to monitor your apache service at the level of from where and what the people are visiting I will suggest awstats, or google analytics. All this is based on my experience, so I can be wrong and I'll accept opinions and corrections. :)
22,781,754
I would like to print out the content of an associative array. For this I'm using Data::dumper. So, for exemple, if the associative array is called "%w", I write : ``` print OUT Dumper(\%w); ``` Here's the problem: there are some words like "récente" that are printed out as "r\x{e9}cente". If I write just : ``` print OUT %w; ``` I've no problems, so "récente" it will be printed out as "récente". All text files used for the script are in utf8. Moreover I use the module "utf8" and I specify always the character encoding system. For ex. : ``` open( IN, '<', $file_in); binmode(IN,":utf8"); ``` I'm pretty sure that the problem is related to Data::dumper. Is there a way to solve this or another way to print out the content of an associative array? Thank you.
2014/04/01
[ "https://Stackoverflow.com/questions/22781754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3025314/" ]
You can also use *Data::Dumper::AutoEncode*. ``` use utf8; use Data::Dumper::AutoEncode; warn eDumper($hash_ref); ``` [cpan Data::Dumper::AutoEncode](http://search.cpan.org/~bayashi/Data-Dumper-AutoEncode-0.103/lib/Data/Dumper/AutoEncode.pm)
This works for me: ``` use strict; use warnings; use Data::Dumper; $Data::Dumper::Useperl = 1; binmode STDOUT, ":utf8"; { no warnings 'redefine'; sub Data::Dumper::qquote { my $s = shift; return "'$s'"; } } my $s = "rcente\x{3a3}"; my %w = ($s=>12); print Dumper(\%w), "\n"; ```
4,364,458
i always in inserting data into a mysql table i use a select for that data before inserting to avoid duplicate records and if the query return null then i insert record. but i think maybe it is not a professional way to do this job. would you let me the ways you do?
2010/12/06
[ "https://Stackoverflow.com/questions/4364458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/313389/" ]
``` You can try the following example. I would suggest you to try this first in your testing environment then you can implement this in your actual scenario. Follow the below steps: Step 1: create a table CREATE TABLE IF NOT EXISTS `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(30) NOT NULL, `email` varchar(50) NOT NULL, `password` varchar(20) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; Step 2: Run this query multiple times and check that only one row is inserted INSERT INTO `student` ( `name`, `age`) SELECT `name`, `age` FROM `student` WHERE NOT EXISTS (SELECT 1 FROM `student` WHERE `name` = 'manish' AND `age` = '23' ); ```
The "professional" way to do this will be using a primary key constraint.
26,802,189
Say like we have in Spring Framework a lot of variations to set compile/run/test time environment, and use it to bind a different properties files with settings. It is made for us not to change anything except this one environment/profile variable to be able to have proper settings for app. More particularly: I have two files: settings.dev.js and settings.prod.js **settings.prod.js:** ``` var API_PATH = "http://example.com/api" var OTHER_INPORTANT_SETTINGS = {....} ``` **settings.dev.js:** ``` var API_PATH = "http://localhost.com/api" var OTHER_INPORTANT_SETTINGS = {....} ``` and an Ionic Framework app where services are using this settings. E.g. ``` me: $resource(API_PATH + '/my/profile', {}, {...} ``` And so on in many services and controllers and maybe directives... Is there some way to use * settings.dev.js while in development and * settings.prod.js for deployment a release app.
2014/11/07
[ "https://Stackoverflow.com/questions/26802189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2782135/" ]
I just develop a solution for the issue. 1. Create a grunt task (or the equivalent build tools) to copy the `settings.<env>.js` file to `settings.js` file. ``` copy: { dev: { src: 'settings.dev.js', dest: 'settings.js' }, prod: { src: 'settings.prod.js', dest: 'settings.js' } }, grunt.registerTask('dev', [ 'copy:development' ]); grunt.registerTask('prod', [ 'copy:prod' ]); ``` 2. Include `settings.js` in your html or js file. 3. Add `settings.js` to your `.gitignore` file so that your environment specific file won't affect others.
For loading config files you can just ad script tag with the script URL in the HTML. ``` <script src="/your/path/settings.prod.js"></script> ``` or ``` <script src="/your/path/settings.dev.js"></script> ``` Then you can defined variables as usual.
214,688
Apparently, they're "confusing". Is that seriously the reason? Can you think of any others?
2008/10/18
[ "https://Stackoverflow.com/questions/214688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18658/" ]
Have you seen how many developers don't really understand ref/out? I use them where they're really necessary, but not otherwise. They're usually only useful if you want to effectively return two or more values - in which case it's worth at least *thinking* about whether there's a way of making the method only do one thing instead. Sometimes using ref/out *is* the most appropriate approach - the various TryParse methods etc.
You should be returning objects is probably the most likely reason that they suggest not using ref or out. "ref" really only needs to be used when passing scalar values but I see people use it often for objects that are being passed by reference anyways.
5,687,764
I'm doing some redirects using PHP, e.g.: ``` header('Location: '.$url); ``` But now I need to do some redirects with some other statuscodes. Should I http1.0 or http1.1 for this. Or are we already at http2.0 or greater? And are the status code the same for both? So let's say I want to redirect using statuscode 404 (Not Found). Can I just do: ``` header('HTTP/1.1 404 Not Found'); header('Location: '.$url); ``` Or is there a: ``` header('HTTP/2.0 404 Not Found'); header('Location: '.$url); ```
2011/04/16
[ "https://Stackoverflow.com/questions/5687764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/508666/" ]
Generally speaking, browsers are using HTTP 1.1 *(HTTP 1.0 is quite old ; and doesn't support several interesting features which are pretty much required nowadays)* HTTP 2.0 ? There is no such thing ;-) Don't hesitate to take a look at [Hypertext Transfer Protocol][1] -- and going through [\*\*RFC 2616 - Hypertext Transfer Protocol -- HTTP/1.1\*\*][2] can be a good idea. Yes, it can take some time to read this -- but if you are working every day with HTTP, knowing a bit about it can be a good idea ;-)
Its up to you, if you send `HTTP/1.0` or `HTTP/1.1`, because for your purposes nothing changed.
15,604,290
Writing Haskell programs I found myself in need of an operator like this. ``` (|>) :: a -> (a -> b) -> b (|>) = flip ($) infixl 0 |> ``` I think it is useful when glueing many functions together. ``` tText cs = someFun cs |> lines |> map (drop 4) |> reverse ``` I prefer it over `.` because with `|>` the order in which the functions are applied is the same as the order in which the functions are written. ``` tText' cs = reverse . map (drop 4) . lines . someFun $ cs ``` Question is: is this (`|>`) something that already exists in the `Prelude` / some other basic library? Reimplementing simple stuff is something silly which I would like to avoid. A Hoogle search did not help. Closest thing I found was `>>>` (Arrows), but it seems an overkill.
2013/03/24
[ "https://Stackoverflow.com/questions/15604290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2205541/" ]
The [`lens` library](http://hackage.haskell.org/package/lens) defines [this operator as `&`](http://hackage.haskell.org/packages/archive/lens/3.8.7.3/doc/html/Control-Lens-Combinators.html).
As far as my experience goes, I don't know any such library. And if such a library exists, I'd advise against using it. --- Unless you are using the lens package, I'd suggest not to use externally defined operators of that kind. (In case of that lens package, you really need and already have such an operator.) In my experience, IMHO and such ... In cases where the readability enhances with a forward composition in contrast to the usual composition (not only when dealing with lenses), it is beneficial to define a special operator in that module or locally via `let` or `where`. For that, I tend to use single unicode symbols rather than ascii combos. ``` (·) = flip (.) infixl 1 (·) (§) = ($) -- left associative, no flip infixl 0 (§) ``` Some years ago(, when there were no lenses), I thought of defining my own module for these, too. But then I grow to use that module sooo infrequent that I tended to reinvent the wheel anyway. To have these operators in a library may even *increase* the effort of reading the code: The reader has to look those rarely used operators up. In that case, locally defined operators are way better.
6,943,787
``` array( array('codcentrocustos' => 1, 'codparent' => null, 'name' => 'lorem ipsum'), array('codcentrocustos' => 2, 'codparent' => 1, 'name' => 'lorem ipsum1'), array('codcentrocustos' => 3, 'codparent' => 1, 'name' => 'lorem ipsum2'), array('codcentrocustos' => 4, 'codparent' => 2, 'name' => 'lorem ipsum3'), array('codcentrocustos' => 5, 'codparent' => 3, 'name' => 'lorem ipsum4'), array('codcentrocustos' => 6, 'codparent' => null, 'name' => 'lorem ipsum5'), ); ``` Hey guys, i have this array, i need to transform it into an json, but i didnt have anyproblem at this point. The problem its related to what the php its making with it when its needed. if i try to do an var\_dump on he, he return it to me: ``` array 0 => array 'codcentrocustos' => int 1 'codparent' => null 'name' => string 'lorem ipsum' (length=11) 1 => array 'codcentrocustos' => int 2 'codparent' => int 1 'name' => string 'lorem ipsum1' (length=12) 2 => array 'codcentrocustos' => int 3 'codparent' => int 1 'name' => string 'lorem ipsum2' (length=12) 3 => array 'codcentrocustos' => int 4 'codparent' => int 2 'name' => string 'lorem ipsum3' (length=12) 4 => array 'codcentrocustos' => int 5 'codparent' => int 3 'name' => string 'lorem ipsum4' (length=12) 5 => array 'codcentrocustos' => int 6 'codparent' => null 'name' => string 'lorem ipsum5' (length=12) ``` The problem its that i need my array without these refference numbers as ``` array **0 =>** array 'codcentrocustos' => int 1 'codparent' => null 'name' => string 'lorem ipsum' (length=11) **1 =>** ```
2011/08/04
[ "https://Stackoverflow.com/questions/6943787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/878866/" ]
To convert your array to JSON just use [json\_encode](http://php.net/manual/en/function.json-encode.php). You don't need any sort of conversion. ``` $test = array( array('codcentrocustos' => 1, 'codparent' => null, 'name' => 'lorem ipsum'), array('codcentrocustos' => 2, 'codparent' => 1, 'name' => 'lorem ipsum1'), array('codcentrocustos' => 3, 'codparent' => 1, 'name' => 'lorem ipsum2'), array('codcentrocustos' => 4, 'codparent' => 2, 'name' => 'lorem ipsum3'), array('codcentrocustos' => 5, 'codparent' => 3, 'name' => 'lorem ipsum4'), array('codcentrocustos' => 6, 'codparent' => null, 'name' => 'lorem ipsum5'), ); print json_encode($test); ``` **Output** ``` [{"codcentrocustos":1, "codparent":null, "name":"lorem ipsum"}, {"codcentrocustos":2, "codparent":1, "name":"lorem ipsum1"}, {"codcentrocustos":3, "codparent":1, "name":"lorem ipsum2"}, {"codcentrocustos":4, "codparent":2, "name":"lorem ipsum3"}, {"codcentrocustos":5, "codparent":3, "name":"lorem ipsum4"}, {"codcentrocustos":6, "codparent":null, "name":"lorem ipsum5"}] ```
You can't get away from from those indexes. Every element in an array MUST have a key. It's utterly unavoidable.
3,358,203
Let's assume i'm given a Probability Distribution as follows: $$Bin(n; N, p)=\binom{N}{n}p^n(1-p)^{(N-n)}$$ We know that the mean of this distribution is: $$E[n]=Np$$ However, we want to prove its true using the derivative of the normalized condition of the distribution: $$\sum\_{n=0}^{N}\binom{N}{n}p^n(1-p)^{(N-n)}=1$$ The textbook says that we can derive $E[n]$, the expectation of n, by differentiating both sides of the normalized condition with respect to p, and then rearranging to obtain the expression for the mean of n, aka: $E[n]$. Ok, So I try to do this by differentiate both sides as follows: $$\frac{d}{dp}\Bigg( \sum\_{n=0}^{N}\binom{N}{n}p^n(1-p)^{(N-n)}\Bigg) = \frac{d}{dp} 1$$ $$\sum\_{n=0}^{N}\binom{N}{n} \frac{d}{dp}\Bigg( p^n(1-p)^{(N-n)}\Bigg) = 0$$ Differentiating LHS sub-expression: $$\frac{d}{dp}\Bigg( p^n(1-p)^{(N-n)}\Bigg)$$ applying product rule of diff: $$= D\{p^n\}\ (1-p)^{(N-n)} + (p^n)\ D \{(1-p)^{(N-n)}\}$$ $$= n p^{(n-1)} (1-p)^{(N-n)} + (p^n)\ (N-n) (1-p)^{(N-n-1)}(-1)$$ $$= n p^{(n-1)} (1-p)^{(N-n)} - (p^n)\ (N-n) (1-p)^{(N-n-1)}$$ Substituting this result back into Summation: $$\sum\_{n=0}^{N}\binom{N}{n} \frac{d}{dp}\Bigg( n p^{(n-1)} (1-p)^{(N-n)} - (p^n)\ (N-n) (1-p)^{(N-n-1)}\Bigg) = 0$$ Now I'm wondering how do you rearrange this expression to obtain the Expectation of the Binomial Distribution, $E[p]$? (The Textbook in question is "Pattern Recognition and Machine Learning", 8th printing, 2006, Christoper M. Bishop, page 128, exercise 2.4.)
2019/09/16
[ "https://math.stackexchange.com/questions/3358203", "https://math.stackexchange.com", "https://math.stackexchange.com/users/666807/" ]
Instead say that $$B(k,n,p,q)= {n \choose k} p^k q^{n-k}~~~~~(1)$$ Now write the binomial expansion $$(p+q)^n = \sum\_{k=0}^{n} {n \choose k} p^k q ^{n-k}~~~~(2)$$ paretially differentiate both sides $(\frac{\partial}{\partial p}),$ to get $$\sum\_{k=0}^{n} k {n \choose k} p^{k}{q^{n-k}}=np (p+q)^{n-1}~~~~(3)$$ $$<k>=\frac{\sum\_{k=0}^{n} k B(k,n,p,q)}{\sum\_{k=0}^{n} B(k,n,p,q)}=\frac{np}{p+q}.$$ Finally using $p+q=1$, \you get the required result.
Differntiation of $$\sum\_{n=0}^{N}\binom{N}{n}p^n(1-p)^{(N-n)}=1$$ gives $$\sum\_{n=0}^{N}\binom{N}{n} [np^{n-1}(1-p)^{(N-n)}-(N-n)p^{n}(1-p)^{N-n-1}]=0$$ You can write this as $$\sum\_{n=0}^{N}\binom{N}{n} p^n(1-p)^{(N-n)}[\frac n p -\frac {N-n} {1-p}]=0$$ After multiplying by $p(1-p)$ this becomes $$\sum\_{n=0}^{N}\binom{N}{n} p^n(1-p)^{(N-n)}[n -Np]=0$$ Can you finish the proof (by splitting the sum into two parts)?
64,763,791
I want to design a Bottom app bar, First i implemented a dependency named as implementation 'com.google.android.material:material:1.2.0-alpha02' After that with the help of co-ordinate layout I started the project The xml file is: ``` <?xml version="1.0" encoding="utf-8"?> <androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <com.google.android.material.bottomappbar.BottomAppBar android:id="@+id/bottomAppBar" style="@style/Widget.MaterialComponents.BottomAppBar.Colored" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" app:menu="@menu/menu"> </com.google.android.material.bottomappbar.BottomAppBar> </androidx.coordinatorlayout.widget.CoordinatorLayout> ``` My style.xml is ``` <resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.MaterialComponents"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> <style name="AppTheme.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style> <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" /> <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" /> </resources> ``` And my menu resource file is ``` <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="Profile" android:icon="@drawable/ic_baseline_account_circle_24" android:title="Profile"> </item> <item android:id="@+id/Book" android:title="Courses" android:icon="@drawable/ic_baseline_menu_book_24" > </item> <item android:id="@+id/Search" android:title="Search" android:icon="@drawable/ic_baseline_search_24" > </item> <item android:id="@+id/Settings" android:icon="@drawable/ic_baseline_settings_24" android:title="Settings" > </item> </menu> ``` And default the overlap menu control also viewed on the activityscreen!I need to remove that[This is the activity\_image,I need to remove the bottom right three dots on the bottomAppBar](https://i.stack.imgur.com/0Wgkc.png)
2020/11/10
[ "https://Stackoverflow.com/questions/64763791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14589996/" ]
You just need to add `GROUP BY` clause along with `COUNT` aggregation ``` CREATE OR REPLACE VIEW ViewTest AS SELECT First_Name || ' ' || last_Name As EMP_NAME, TO_CHAR(READ_DATE, 'YYYY-MON') As MONTH, COUNT(*) FROM EMPLOYEE E INNER JOIN EMPLOYEE_READ ER ON E.EMP_ID = ER.EMP_ID WHERE TO_CHAR(READ_DATE, 'YYYY-MON') = TO_CHAR(sysdate, 'YYYY-MON') GROUP BY First_Name || ' ' || last_Name, TO_CHAR(READ_DATE, 'YYYY-MON') ```
You can use the following query using `GROUP BY`: ``` CREATE VIEW ViewTest AS SELECT EMP_ID AS ID, First_Name ||' '||last_Name As EMP_NAME, to_char(SYSDATE,'YYYY-MON') As MONTH, -- you can use SYSDATE here. No need to include it in GROUP BY Count(1) as "COUNT" FROM EMPLOYEE E INNER JOIN EMPLOYEE_READ ER ON E.EMP_ID = ER.EMP_ID WHERE to_char(READ_DATE,'YYYY-MON') = to_char(sysdate,'YYYY-MON') GROUP BY EMP_ID, First_Name, Last_name ```
49,580,725
Here is my code ``` async getAll(): Promise<GetAllUserData[]> { return await dbQuery(); // dbQuery returns User[] } class User { id: number; name: string; } class GetAllUserData{ id: number; } ``` `getAll` function returns `User[]`, and each element of array has the `name` property, even if its return type is `GetAllUserData[]`. I want to know if it is possible "out of the box" in TypeScript to restrict an object only to properties specified by its type.
2018/03/30
[ "https://Stackoverflow.com/questions/49580725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7750163/" ]
I don't think it's possible with the code structure you have. Typescript *does* have [excess property checks](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks), which sounds like what you're after, but they only work for object literals. From those docs: > > Object literals get special treatment and undergo excess property checking when assigning them to other variables, or passing them as arguments. > > > But returned variables will not undergo that check. So while ``` function returnUserData(): GetAllUserData { return {id: 1, name: "John Doe"}; } ``` Will produce an error "Object literal may only specify known properties", the code: ``` function returnUserData(): GetAllUserData { const user = {id: 1, name: "John Doe"}; return user; } ``` Will not produce any errors, since it returns a variable and not the object literal itself. So for your case, since `getAll` isn't returning a literal, typescript won't do the excess property check. *Final Note: There is an [issue for "Exact Types"](https://github.com/Microsoft/TypeScript/issues/12936) which if ever implemented would allow for the kind of check you want here.*
As an option, you can go with a hack: ``` const dbQuery = () => [ { name: '', id: 1}]; async function getAll(): Promise<GetAllUserData[]> { return await dbQuery(); // dbQuery returns User[] } type Exact<T> = {[k: string | number | symbol]: never} & T type User = { id: number; name: string; } type GetAllUserData = Exact<{ id: number; }> ``` Error this produces: ``` Type '{ name: string; id: number; }[]' is not assignable to type '({ [k: string]: never; [k: number]: never; [k: symbol]: never; } & { id: number; })[]'. Type '{ name: string; id: number; }' is not assignable to type '{ [k: string]: never; [k: number]: never; [k: symbol]: never; } & { id: number; }'. Type '{ name: string; id: number; }' is not assignable to type '{ [k: string]: never; [k: number]: never; [k: symbol]: never; }'. Property 'name' is incompatible with index signature. Type 'string' is not assignable to type 'never'. ```
29,362
I work in an office and we have a server with a lot of music on it. I am looking for software that would allow anyone in the office to queue up songs to a playlist, sort of like an office radio station where people choose the songs. Are there any programs like this already written? I am considering writing software like this but I'm not sure if it already exists.
2009/08/25
[ "https://superuser.com/questions/29362", "https://superuser.com", "https://superuser.com/users/7698/" ]
[Ampache](http://ampache.org/) is a web-based A/V streaming application. It can be configured to play via embedded flash or stream to a local media player on a per-user basis, or it can be configured for democratic playlists to allow many users to vote on what they want to hear. It's done in PHP with a basic LAMP stack and isn't too difficult to modify.
Would each person connect separately, or is there one player connected to speakers? My personal favourite is Squeezecenter. If you are all using PCs you can use the Jive UI to connect to it. An alternative some people use in our office is Spotify. You can have a group playlist that people add music to and take away.
13,202,797
I know that we cannot change the reference passed to a function such as ``` void fun(dog a){ a=null; } ``` After executing the function ``` main(String[] args){ dog a=new dog(); fun(a); } ``` the dog a is not changed. So I was wondering how can we change the reference a to null inside a function
2012/11/02
[ "https://Stackoverflow.com/questions/13202797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1698248/" ]
Java is Pass by Value, where the *value of the reference* is passed, so new reference value will be passed as parameter. When this reference points to new Object inside the method, changes on reference won't reflect on the object outside of the method. You may need to do something like below to make your outer reference to `null`. ``` Object fun(){ return null; } main(String[] args){ dog a=new dog(); a=fun(); } ```
Java is strictly a pass by value language (see [this for great info](http://javadude.com/articles/passbyvalue.htm)). In short, this means that, when you pass an object reference to a method, a copy of the reference is created for the method. Therefore, any thing you do to nullify the reference in the function is only nullifying the LOCAL copy of the reference variable, while the object to which it was pointing remains in memory, safe and sound. I guess a simple analogy would be something like having two parallel streets that lead to the same building. You can destroy one of the roads, but that has no effect on the building, or the other road.
1,864,267
I have a list of strings whose values come from a fixed set. I need to sort this list in an arbitrary order. The order of the set is specified by another list of all possible strings, sorted in order in an array. Here is an example: ``` my @all_possible_strings_in_order = ('name', 'street', 'city','state', 'postalcode'); my @list_that_needs_to_be_sorted = ('city', 'state', 'name'); ``` I am working in perl. I figure my best bet is to automatically create a hash that associates strings with ordinal numbers, and then sort by reference to those ordinal numbers. There are about 300 possible strings in the set. Typical lists will have 30 strings that need to be sorted. This isn't going to be called in a tight loop, but it can't be slow either. Automatically building the ordinal hash can't be done ahead of time due to the structure of the program. I'm open for suggestions on better ways to do this. Thanks! **Edit:** You guys are awesome. I can't hold my head up any more tonight, but tomorrow morning I'm going to take the time to really understand your suggestions... It's about time I became proficient with map() and grep().
2009/12/08
[ "https://Stackoverflow.com/questions/1864267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/144680/" ]
You can just go over the master list and push any element that occurs in the unsorted list onto the result list, while removing it from the unsorted list. If your unsorted list is short (from your example, I reckon about 5 elements), this should be faster and smaller than building hash tables each time (you said you couldn't do it once beforehand). An optimization might be to make a trie from the unsorted list, but whether this is better is dependent on the size of each list.
The most naive way to do this would be to sort based on a comparison function, where the comparison function comp(a,b) = "which of a and b comes first in the master list?", if I understand correctly. So yeah, your idea looks about right. If you have to do a lot of sorts between changes to `@all_possible_strings_in_order`, then you should build the whole map once. If the order list changes every sort, you may be able to gain some speed with some clever lazy search, but maybe not. ``` my %order; my $i = 0; foreach my $s (@all_possible_strings_in_order) { $order{$s} = $i++; } my @sorted = sort {$order{$a} <=> $order{$b}} @list_that_needs_to_be_sorted; ``` I imagine this should be quite fast.
2,387,316
I'm having a textbox and assigned the following function (it's the only function assigned): ``` txt.bind("keyup",function(event){ if(event.keyCode==13) { var nu = $("#debug").html(); nu+="<br>enter"; $("#debug").html(nu); } }); ``` The strange thing is that it's actually firing twice, thus displaying "enter" twice in my debug window. Does anyone know what is causing this?
2010/03/05
[ "https://Stackoverflow.com/questions/2387316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/202862/" ]
I'm embarrassed to even mention this, but I was typing a capital letter into my textbox and so the release of my shift key was causing the supposed "second firing" of the keyup event. Turns out it wasn't a second firing at all, but it just fooled me into thinking it was for while. At first I thought the unbind trick mentioned above simply wasn't working for me, but it was. I hope this helps others like me that might have done the same thing. Now I simply make sure I always check that its not just the shift key being released in the handling of my event and all is well again.
could it be possible that your html-element is contained twice within txt? it would be helpful if you would provide the html and the assigning javascript-code.
59,494,598
I'm currently trying to loop running a function. Can't figure it out and here's what I tried: ``` do { queryLastCursor(lastCursor).then(lastCursorResults => { if (lastCursorResults.hasNext = false) { hasNextPage = false; } console.log(hasNextPage); }) } while (hasNextPage); ``` `queryLastCursor` is a method with a call to an API. When it returns the data it would have a value of `hasNext` if it returns false then I'd like to set `hasNextPage` to `false`. The expected behavior would be that it runs the function again and again until we get the result `hasNext = false`. Any idea of what am I doing wrong?
2019/12/26
[ "https://Stackoverflow.com/questions/59494598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2690257/" ]
If you want to do an async process in a loop, I suggest doing it recursively: ``` const runQuery = () => { queryLastCursor(lastCursor) .then(result => { if (result.hasNext) { // recursively call itself if hasNext is true runQuery(); } }); } runQuery(); ``` Assuming you'd want to return some data, you can do: ``` const runQuery = async (data) => { return queryLastCursor(lastCursor) .then(result => { if (!data) { data = []; } // assuming you are returning the data on result.data data.push(result.data); if (result.hasNext) { // recursively call itself if hasNext is true return runQuery(data); } retun data; }); } runQuery() .then(data => { // data should be an array of all the data now }); ```
I would do something like that: ``` const callApi = async () => { let result = await someMagic(); while (result.hasNext) { doSomethingwith(result); result = await someMagic(); } return result; }; const myResult = await callApi(); ``` Though this seems risky, what is we always get a hastNext = true ? Some security seems good, like a limit of loops in the while loop.
71,318,723
I've been searching around for a while now, but I can't seem to find the answer to this small problem. how to convert string 06-JUL-89 to datetime 06/07/1989? I've tried with code like the following: ``` TO_CHAR(TO_DATE(BORN,'DD-MON-YY'),'DD/MM/YYYY') ``` however, the result shows wrong: to be 06/07/2089? how do i solve the problem?
2022/03/02
[ "https://Stackoverflow.com/questions/71318723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14388578/" ]
With `RR` format model. ``` SQL> select to_char(to_date('06-jul-89', 'dd-mon-rr'), 'dd/mm/yyyy') result from dual; -- RESULT here ---------- 06/07/1989 SQL> ``` --- By the way, it looks as if you store date values as strings. If so, don't do that - switch to `DATE` datatype (as soon as possible).
It seem that you have the problem of year 2k : * `TO_DATE('06-jul-89', 'dd-mon-yy')` => 06/07/2089 * You must use `TO_DATE('06-jul-89', 'dd-mon-rr')` => 06/07/1989
5,450,596
This question appear when I worked with partial view (MVC3/Razor), but I am sure - it's clear Razor Syntax question, not related direct to partial view. So - I have partial view Menu.cshtml with full markup as: ``` @model IEnumerable<SportsStore.WebUI.Models.NavLink> @foreach(var link in Model) { @Html.RouteLink(link.Text, link.RouteValues); } ``` No problem - "parent" view call it @{Html.RenderAction("Menu", "Nav");} and all work as magic. But, if I will edit the Menu.cshtml as: ``` @model IEnumerable<SportsStore.WebUI.Models.NavLink> @foreach(var link in Model) { Html.RouteLink(link.Text, link.RouteValues); } ``` (see - NO '@' before Html.RouteLink!) all just broke: now @{Html.RenderAction("Menu", "Nav");} output is totally empty, no one HTML tag. Want to know - what is the difference between two piece of code? I assume **@** before **foreach** also automatically "drop into" and apply to **Html.RouteLink** as well? So - am I wrong?
2011/03/27
[ "https://Stackoverflow.com/questions/5450596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/335149/" ]
Just use ls? ``` ls /path/to/directory ``` Alternatively, use `opendir()` and `readdir()`, see `man 3 opendir` and `man 3 readdir`
The other answers are suitable if you are at the terminal, but you would probably like a C API, rather than an expensive call to fork the process and list a directory. For a C API, you'll want to take a look at `opendir`, `readdir` and `closedir` - [this is a perfectly good reference](http://pubs.opengroup.org/onlinepubs/007908799/xsh/opendir.html).
23,764,812
I setup google developer console enabling *Google Cloud Messaging for Android*. In the credential side I create the browser API key typing 0.0.0.0 in the refers. Actually I create both the types of key because I found different indication in different tutorial. [browser-key picture](http://imgur.com/m6149WQ) [server-key picture](http://imgur.com/5KjpDWM) I tested the key with this PHP script ``` <? /** * The following function will send a GCM notification using curl. * * @param $apiKey [string] The Browser API key string for your GCM account * @param $registrationIdsArray [array] An array of registration ids to send this notification to * @param $messageData [array] An named array of data to send as the notification payload */ function sendNotification( $apiKey, $registrationIdsArray, $messageData ) { $headers = array("Content-Type:" . "application/json", "Authorization:" . "key=" . $apiKey); $data = array( 'data' => $messageData, 'registration_ids' => $registrationIdsArray ); $ch = curl_init(); curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers ); curl_setopt( $ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send" ); curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 ); curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($data) ); $response = curl_exec($ch); curl_close($ch); return $response; } ?> <? // Message to send $message = "the test message"; $tickerText = "ticker text message"; $contentTitle = "content title"; $contentText = "content body"; $registrationId = '372CBFD0C4BFE728'; $apiKey = "AIzaSyDeNN1XJBFGE_lJ_35VMUmx5cUbRCUGkjo"; $response = sendNotification( $apiKey, array($registrationId), array('message' => $message, 'tickerText' => $tickerText, 'contentTitle' => $contentTitle, "contentText" => $contentText) ); echo $response; ?> ``` I expect to obtain something like that ``` {"multicast_id":6782339717028231855,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]} ``` But I obtain (with both keys) *Unauthorized 401 Error*. Thanks for the help.
2014/05/20
[ "https://Stackoverflow.com/questions/23764812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3631494/" ]
Instead of entering `0.0.0.0` as allowed referrers or allowed IPs, don't enter anything. That should work.
Don't enter anything in the IP address field.It works like a charm. Also make sure you are using the Server key in server side and proper sender id android client.
6,659,322
How to read all contents of a column from excel file in 1-d array and in C#? Not using ADO.net approach or excel reader. Also there can be any number of rows in the excel file(how to determine number of rows in the column)..some cells may have blank value in the column...need the most basic approach using Microsoft.Office.Interop.Excel
2011/07/12
[ "https://Stackoverflow.com/questions/6659322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/830873/" ]
Just a thought - Do you have any outstanding migrations that you have not performed on Heroku? That's something I always forget - Just run `heroku run rake db:migrate` and see if that helps. Might not be an error in your code after all. Hope this helps!
Had the same issue. Running heroku run rake db:migrate worked for me
6,941,924
For example: ``` s1="my_foo" s2="not_my_bar" ``` the desired result would be `my_o`. How do I do this in bash?
2011/08/04
[ "https://Stackoverflow.com/questions/6941924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/603625/" ]
a late entry, I've just found this page: ``` echo "$str2" | awk 'BEGIN{FS=""} { n=0; while(n<=NF) { if ($n == substr(test,n,1)) { if(!found[$n]) printf("%c",$n); found[$n]=1;} n++; } print ""}' test="$str1" ``` and another one, this one builds a regexp for matching (note: doesn't work with special characters, but that's not that hard to fix with anonther sed) ``` echo "$str1" | grep -E -o ^`echo -n "$str2" | sed 's/\(.\)/(|\1/g'; echo "$str2" | sed 's/./)/g'` ```
A solution using a single sed execution: ``` echo -e "$s1\n$s2" | sed -e 'N;s/^/\n/;:begin;s/\n\(.\)\(.*\)\n\(.*\)\1\(.*\)/\1\n\2\n\3\4/;t begin;s/\n.\(.*\)\n\(.*\)/\n\1\n\2/;t begin;s/\n\n.*//' ``` As all cryptic sed script, it needs explanation in the form of a sed script file that can be run by `echo -e "$s1\n$s2" | sed -f script`: ``` # Read the next line so s1 and s2 are in the pattern space only separated by a \n. N # Put a \n at the beginning of the pattern space. s/^/\n/ # During the script execution, the pattern space will contain <result so far>\n<what left of s1>\n<what left of s2>. :begin # If the 1st char of s1 is found in s2, remove it from s1 and s2, append it to the result and do this again until it fails. s/\n\(.\)\(.*\)\n\(.*\)\1\(.*\)/\1\n\2\n\3\4/ t begin # When previous substitution fails, remove 1st char of s1 and try again to find 1st char of S1 in s2. s/\n.\(.*\)\n\(.*\)/\n\1\n\2/ t begin # When previous substitution fails, s1 is empty so remove the \n and what is left of s2. s/\n\n.*// ``` If you want to remove duplicate, add the following at the end of the script: ``` :end;s/\(.\)\(.*\)\1/\1\2/;t end ``` **Edit:** I realize that dogbane's pure shell solution has the same algorithm, and is probably more efficient.
15,363,360
In a database, there is a string of +10000 chars that is in XML format. The XML is not well formed and I need to fix it. I have to convert the string (no CRLF's in it) into a file that I can edit sensibly and correct the tags. I am able to extract the string to an editor, it is the conversion to multiline, indented XML that is tricky. Any help on how to tackle that kind of task? Thanks in advance.
2013/03/12
[ "https://Stackoverflow.com/questions/15363360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/653966/" ]
A good solution is to run : ``` xmllint --format file.xml ``` `xmllint` is a part of `libxml2-utils` on debian, see <http://www.xmlsoft.org/> (also available for windows)
use "Xml formatter" package in Atom text editor. <https://atom.io/packages/xml-formatter> Its offline and you don't risk data privacy
83,352
Inspired by the very nice problem solutions of [the problem of coinciding clock hands](https://mathematica.stackexchange.com/questions/573/figuring-when-the-minute-and-hour-hand-coincide-on-a-clock), I'd like to extend the question including a "second" hand. While it is obvious that all three hand can coincide only at midnight, the questions are (i) where is the "second" hand after midnight when minute and hour hands conincide, and in which case the angular difference is minimal. (ii) Create a nice picture of the situation. (iii) Study the coincidence combinations hour-second and minute-second and exhibit the position of the missing hand in each case
2015/05/13
[ "https://mathematica.stackexchange.com/questions/83352", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/16361/" ]
The coincidences of the hour and minute hand occur when the number of hours since midnight $h$ satisfies $\frac{1}{12}h = h - n$ for some integer $n$. (The left-hand side corresponds to the number of revolutions the hour hand has made; the right-hand side corresponds to the number of of revolutions the minute hand has made.) This can be rearranged to $h = 12 n/11$, or $s = 43200 n/11$ (where $s$ is the number of seconds since midnight. Using the `ClockGauge` command (thanks to @ubpdqn), we can do this pretty easily: ``` Table[ClockGauge[43200 n/11], {n, 0, 10}] ``` ![enter image description here](https://i.stack.imgur.com/8tQJQ.jpg) The coincidences of the hour & second hands, and of the hour & minute hands, are a little harder to show, simply because there are so many of them (719 hour-second coincidences in a 12-hour period, and 708 minute-second coincidences.) The following bits of code do the trick, though: ``` Manipulate[ClockGauge[43200 n/719], {n, 0, 719, 1}] (*hour-second*) Manipulate[ClockGauge[3600 n/59], {n, 0, 708, 1}] (*minute-second*) ``` The equations here were found by much the same logic as above. **EDIT:** If you want to display the precise times of the coincidences, insert the option ``` GaugeLabels -> {"Hour12", ":", "Minute", ":", "SecondExact"} ``` into the `ClockGauge` command above.
I have not spent sufficient time but perhaps. In the following, starting clock at 12:00 with red second hand, blue minute hand and green hour hand. "SM" animates first coincidence second and minute hand, "MH", minute and hour hands, "SH" second and hour hands. First number after after graphic is time to first coincidence in seconds and second is clock time. Adapt/modify...very bland but time poor. ``` Manipulate[ Column[{Animate[ Graphics[{Circle[], Red, pp[ts, time], Blue, pp[tm, time], Green, pp[th, time]}], {time, 0, p}, AnimationRepetitions -> 1, AnimationRate -> tim[p]], Row[{N@p, " seconds"}], DateString[ DatePlus[{2015, 5, 13, 12, 0, 0}, {N@p, "Second"}], {"Hour24", ":", "Minute", ":", "Second"}]}], {{p, ci[ts, tm]}, {ci[ts, tm] -> "SM", ci[tm, th] -> "MH", ci[ts, th] -> "SH"}}, Initialization :> (ts = 60; tm = 60 60; th = 12 60 60; pp[u_, t_] := Arrow[{{0, 0}, {Sin[2 Pi t/u], Cos[2 Pi t/u]}}]; ppm[u_, t_] := Line[{{0, 0}, {Sin[2 Pi t/u], Cos[2 Pi t/u]}}]; ci[t1_, t2_] := 1/(1/t1 - 1/t2); tim[ci[ts, tm]] := 0.1; tim[ci[tm, th]] := 0.02; tim[ci[ts, th]] := 0.1)] ``` ![enter image description here](https://i.stack.imgur.com/4BGtv.gif) Obviously could be better with `ClockGauge` or annotations... or perhaps prettier: ``` Manipulate[ Animate[ClockGauge[ DatePlus[{2015, 5, 13, 12, 0, 0}, {j, "Second"}],GaugeLabels->Automatic], {j, 0, p}, AnimationRepetitions -> 1], {{p, ci[ts, tm]}, {ci[ts, tm] -> "SM", ci[tm, th] -> "MH", ci[ts, th] -> "SH"}}] ``` ![enter image description here](https://i.stack.imgur.com/pthn0.gif)
20,042,102
rubygems/dependency.rb:296:in `to\_specs': Could not find 'cocoapods' (>= 0) among 35 total gem(s) (Gem::LoadError) from /Users/divyam.shukla/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/rubygems/dependency.rb:307:in `to\_spec' ``` from /Users/user/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/rubygems/core_ext/kernel_gem.rb:47:in `gem' from /Users/user/.rvm/gems/ruby-2.0.0-p247/bin/pod:22:in `<main>' ``` I am getting this error.
2013/11/18
[ "https://Stackoverflow.com/questions/20042102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768020/" ]
Hey I had the same problem that you have, I solve it following the next steps: (I strongly recommend to use rvm to manage ruby versions) 1. Remove cocoapods using `gem uninstall cocoapods` 2. Install **rvm**, to do this I followed this steps <https://rvm.io/rvm/install> 3. After that reinstall cocoapods using `gem install cocoapods` 4. run `pod setup` And after that everything works like a charm!. You could notice that **I didn't use** `sudo`. Hope it could helps you. **EDIT:** If you have a slow internet connection it could take several minutes, to check the progress or steps use `pod setup --verbose`
do this : sudo gem install -n /usr/local/bin cocoapods
70,104,211
The code works but its weird , when i run it and give the quantity 375 this is the result: Quantity: 375 2 notes of 100 2 notes of 50 2 notes of 20 2 notes of 10 2 notes of 5 2 notes of 2 1 notes of 1 It should give me 3 notes of 100 , one note of 50 , one note of 20 and one note of 5. Im really new to coding so this might be really easy. ``` int main(void) { int quantity = get_int("Quantity: "); int hundred = 0; int fifty = 0; int twenty = 0; int ten = 0; int five = 0; int two = 0; int one = 0; while ( quantity > 0 ) { if ( quantity >= 100 ) { quantity -= 100; hundred++; } if ( quantity >= 50 ) { quantity -= 50; fifty++; } if ( quantity >= 20 ) { quantity -= 20; twenty++; } if ( quantity >= 10 ) { quantity -= 10; ten++; } if ( quantity >= 5) { quantity -= 5; five++; } if ( quantity >= 2) { quantity -= 2; two++; } if ( quantity >= 1 ) { quantity -= 1; one++; } } printf("%d notes of 100\n", hundred); printf("%d notes of 50\n", fifty); printf("%d notes of 20\n", twenty); printf("%d notes of 10\n", ten); printf("%d notes of 5\n", five); printf("%d notes of 2\n", two); printf("%d notes of 1\n", one); ```
2021/11/24
[ "https://Stackoverflow.com/questions/70104211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17502805/" ]
I fixed this problem by removing the following line in my `build.gradle` file: ``` implementation 'androidx.test:core-ktx:1.4.0' ```
Espresso are not unit tests and you're probably lacking a dependency: ``` testImplementation "androidx.test:monitor:1.4.0" ```
8,300,108
I've been working with Xcode for about 5 months now and I just recently ran across a problem when I add a new class. If I add a new class, say for example "CustomCell" and I try to import '#import CustomCell.h' into a different .m file it will give me an error saying 'CustomCell.h file not found' even though it's right there on the list. I've had no problem with this in the past and I know what I'm doing when it comes to importing (at least I haven't changed the way I previously went about it when it worked). I've had this problem more than once recently and sometimes if I just close out XCode and restart it it will recognize the class. Has anyone else had this problem? Is there a quick way to just refresh the project to see if Xcode can recognize the new class?
2011/11/28
[ "https://Stackoverflow.com/questions/8300108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/975592/" ]
**Multiple Targets:** Make sure your file belongs to the necessary targets! --- For a new file, make sure the appropriate targets are checked. [![xCode Screenshot](https://i.stack.imgur.com/PNhDI.png)](https://i.stack.imgur.com/PNhDI.png) --- For an existing file, check the file inspector to verify target membership. [![xCode Screenshot](https://i.stack.imgur.com/FSyUW.png)](https://i.stack.imgur.com/FSyUW.png)
For those dealing with the same issue and the above solution failed to solve it, make sure you don't have the > > [circular import](https://stackoverflow.com/questions/7767811/circular-import-issues-in-objective-c-cocoa-touch) > > > issue like i had. It happened with me as i had complex code and i failed to realize my mistake.
57,724,231
I understand that we want to use `assert` when we want to check for impossible case. In a book I have, I saw the following two examples: ``` void foo(char* str) { assert ((str+strlen(str)) != NULL); } void bar(char* str) { assert (str[strlen(str)] != NULL); } ``` I'm trying to figure out if they are valid checks. As I understand the first example is not valid because we check if the address is `NULL` and that is not right. But I'm not sure what we are checking in the second example. I'm having hard time understanding when its the right time to use `assert`. I understand the explanation of "checking impossible cases" but it a bit different for each case. **EDIT**: Is there a diffrence between the functions I showed before and those?: ``` void foo(char* str) { assert (!(str+strlen(str))} void bar(char* str) { assert (! str[strlen(str)]); } ```
2019/08/30
[ "https://Stackoverflow.com/questions/57724231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9808098/" ]
Neither expression makes sense. In the first expression ``` assert ((str+strlen(str)) != NULL); ``` there is a check whether the address of the terminating zero character `'\0'` of a string is equal to NULL. It is evident that it is always unequal to NULL. From the C Standard (6.5.6 Additive operators) > > 8. ... In other words, if the expression P points to the i-th element of an array > object, the expressions (P)+N (equivalently, N+(P)) and > (P)-N (where N has the value n) point to, respectively, the i+n-th and > i−n-th elements of the array object, provided they exist. > > > In the second expression ``` assert (str[strlen(str)] != NULL) ``` there is a check whether the terminating zero character `'\0'` is equal to a null-pointer. This also does not make sense. Pay attention to that the above expression is equivalent to the following expression ``` assert (*(str+strlen(str)) != NULL); ``` and hence also does not make sense.
``` void foo(char* str) { assert ((str+strlen(str)) != NULL); } ``` is legal C-code but the expression `(str+strlen(str)) != NULL` will always be true so there is no point in making an assert. ``` void bar(char* str) { assert (str[strlen(str)] != NULL); } ``` is comparing a pointer with a char (aka interger type). That makes no sense. ``` void foo(char* str) { assert (!(str+strlen(str)));} ``` is the same as the first `foo` (notice that I fixed the syntax error) ``` void bar(char* str) { assert (! str[strlen(str)]); } ``` is different from the first `bar`. This is legal code. It is the same as `assert (str[strlen(str)] == 0);`. However, it makes no sense to have this assert as it can never fail. Notice that asserts are **not** for checking something that are impossible! Asserts are for checking something that are possible but invalid/illegal.
44,352,657
I am working with a question for that we need to get n string inputs how to store then in n string variables. I tried with array storing the string in each elements Is there any other way in java ?
2017/06/04
[ "https://Stackoverflow.com/questions/44352657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7963754/" ]
I would use streams for this. It doens’t turn out to be very much shorter, but once you get comfortable with streams, it will be conceptually simpler. ``` Map<Integer, Long> frequencies = Arrays.stream(data) .boxed() .collect(Collectors.groupingBy(i -> i, Collectors.counting())); if (frequencies.isEmpty()) { System.out.println("No data"); } else { long topFrequency = frequencies.values() .stream() .max(Long::compareTo) .get(); int[] topNumbers = frequencies.entrySet() .stream() .filter(e -> e.getValue() == topFrequency) .mapToInt(Map.Entry::getKey) .toArray(); for (int number : topNumbers) { System.out.println("" + number + " => " + topFrequency); } } ``` With the example data from the question it prints the desired (only in another unpredictable order): ``` 1 => 2 8 => 2 9 => 2 ``` Edit: tucuxi asked: why not use the stream to print with too? You may do that of course, for shorter and yet simpler code: ``` frequencies.entrySet() .stream() .filter(e -> e.getValue() == topFrequency) .mapToInt(Map.Entry::getKey) .forEach(n -> System.out.println("" + n + " => " + topFrequency)); ``` What to choose depends on both requirements and taste. I was expecting that the OP would need to store the top frequency numbers, so I demonstrated how to do that, and just printed them to show the result. Also some hold the ideal that streams should be free from side effects, where I would consider printing to standard output a side effect. But use it if you like.
I would use Java8 stream for it. In some cases you can even use parallel stream to improve performance. Here is how I would do that: ``` public static void main(String[] args) { List<Integer> integers = Arrays.asList(1, 8, 7, 8, 9, 2, 1, 9, 6, 4, 3, 5); //Here we have statistics of frequency for all numbers LinkedHashMap<Integer, Integer> statistics = integers.stream().distinct() .collect(Collectors.toMap(Function.identity(), number -> Collections.frequency(integers, number))) .entrySet().stream().sorted(Collections.reverseOrder(Comparator.comparing(Map.Entry::getValue))) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (o1, o2) -> o1, LinkedHashMap::new)); //Calculate max frequency Integer maxFrequency = statistics.entrySet().stream() .max(Comparator.comparingInt(Map.Entry::getValue)) .map(Map.Entry::getValue).orElse(null); //Collect max frequent numbers to a map Map<Integer, Integer> topFrequentNumbers = statistics.entrySet().stream() .filter(o -> o.getValue().equals(maxFrequency)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); //Print topFrequentNumbers.forEach((number, frequency) -> System.out.println(number + " => " + frequency)); } ``` Output: ``` 1 => 2 8 => 2 9 => 2 ``` As I mentioned, you can play with parallel streams and extracting some pieces to improve performance.
60,382,563
``` public class A2 { protected virtual void f() {Console.WriteLine("from A2");} protected virtual void g() {Console.WriteLine("From A2");} protected virtual void h1() {Console.WriteLine("from A2");} } public class B2 { protected virtual void f() {Console.WriteLine("B2");} protected virtual void g() {Console.WriteLine("B2");} protected virtual void h2() {Console.WriteLine("B2");} } ``` giving this code above, I am trying to inherit all the functionality of the 2 classes by creating a new class as following: ``` public class C2 { private A2 a2 = new A2(); private B2 b2 = new B2(); public void f() { a2.f(); } public void h1() { a2.h1(); } public void g() { b2.g(); } public void h2() { b2.h2(); } static public void Main() { C2 n = new C2(); n.f(); n.g(); n.h1(); n.h2(); } } ``` However, when I'm trying to compile the program I'm getting an error that is I can't access the protected methods. How would I inherit all the functionality without modifying the class `A2`, and `B2`?
2020/02/24
[ "https://Stackoverflow.com/questions/60382563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12270056/" ]
It's very difficult to center elements using VFL. It's also difficult to center two elements unless they are embedded in a `UIView` or a `UIStackView`. Here is one option by embedding the labels in a "container" `UIView`: ``` class MyVC: UIViewController { lazy var titleLabel: UILabel = { let l = UILabel(frame: .zero) l.translatesAutoresizingMaskIntoConstraints = false l.text = "Hello World" l.font = .systemFont(ofSize: 50) l.textColor = .black // center the text in the label - change to .left if desired l.textAlignment = .center return l }() lazy var descLabel: UILabel = { let l = UILabel(frame: .zero) l.translatesAutoresizingMaskIntoConstraints = false l.text = "description" l.font = .systemFont(ofSize: 35) l.textColor = .gray // center the text in the label - change to .left if desired l.textAlignment = .center return l }() lazy var containerView: UIView = { let v = UIView() v.translatesAutoresizingMaskIntoConstraints = false return v }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .yellow // give the labels and containerView background colors to make it easy to see the layout titleLabel.backgroundColor = .green descLabel.backgroundColor = .cyan containerView.backgroundColor = .blue // add containerView to view view.addSubview(containerView) // add labels to containerView containerView.addSubview(titleLabel) containerView.addSubview(descLabel) NSLayoutConstraint.activate([ // constrain titleLabel Top to containerView Top titleLabel.topAnchor.constraint(equalTo: containerView.topAnchor), // constrain titleLabel Leading and Trailing to containerView Leading and Trailing titleLabel.leadingAnchor.constraint(equalTo: containerView.leadingAnchor), titleLabel.trailingAnchor.constraint(equalTo: containerView.trailingAnchor), // constrain descLabel Leading and Trailing to containerView Leading and Trailing descLabel.leadingAnchor.constraint(equalTo: containerView.leadingAnchor), descLabel.trailingAnchor.constraint(equalTo: containerView.trailingAnchor), // constrain descLabel Bottom to containerView Bottom descLabel.bottomAnchor.constraint(equalTo: containerView.bottomAnchor), // constrain descLabel Top 10-pts from titleLabel Bottom descLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 10.0), // constrain containerView centered horizontally and vertically containerView.centerXAnchor.constraint(equalTo: view.centerXAnchor), containerView.centerYAnchor.constraint(equalTo: view.centerYAnchor), ]) } } ``` Result: [![enter image description here](https://i.stack.imgur.com/aAsVB.png)](https://i.stack.imgur.com/aAsVB.png)
This can be achieved easily by using stackview. Add both the labels in stackview and center it vertically in the superview with all other constraints(top, leading, bottom, trailing). Here is the sample code of view controller for your use-case. ``` class ViewController: UIViewController { lazy var titleLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "Hello \nWorld" label.font = .systemFont(ofSize: 50) label.backgroundColor = .orange label.numberOfLines = 0 label.textColor = .black return label }() lazy var descLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "a\n b\n c\n" label.font = .systemFont(ofSize: 35) label.backgroundColor = .green label.numberOfLines = 0 label.textColor = .gray return label }() lazy var contentView: UIStackView = { let stackView = UIStackView() stackView.axis = .vertical stackView.translatesAutoresizingMaskIntoConstraints = false stackView.spacing = 10 stackView.distribution = .fill return stackView }() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white contentView.addArrangedSubview(titleLabel) contentView.addArrangedSubview(descLabel) self.view.addSubview(contentView) let constraints = [ contentView.topAnchor.constraint(greaterThanOrEqualTo: view.safeAreaLayoutGuide.topAnchor), contentView.centerYAnchor.constraint(equalTo: view.centerYAnchor), contentView.leadingAnchor.constraint(equalTo: view.leadingAnchor), contentView.trailingAnchor.constraint(equalTo: view.trailingAnchor), contentView.bottomAnchor.constraint(lessThanOrEqualTo: view.safeAreaLayoutGuide.bottomAnchor) ] NSLayoutConstraint.activate(constraints) } } ``` The above code will result this view and it goes on to take the top and buttom space until it meets the safeArea. Moreover you can set the vertical content hugging and compression resistance priority to control which label to expand or shrink. [![](https://i.stack.imgur.com/B5nhW.png)](https://i.stack.imgur.com/B5nhW.png)
12,234,204
In Jenkins, is there a way to give different timeouts to each or selected build step? Build-time plugin out gives functionality of timeout "Abort the build if it's stuck" on complete project, what I need is to give different timeouts for each step. This way I can make my process more efficient.
2012/09/02
[ "https://Stackoverflow.com/questions/12234204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/458034/" ]
Build-timeout Plugin isn't applicable to pipelines. refer to [wiki](https://wiki.jenkins.io/display/JENKINS/Build-timeout+Plugin) For pipeline time out, try something like: ``` timeout(time: 30, unit: 'MINUTES') { node { sh 'foo' } } ``` Similar answer from another thread: [How to add a timeout step to Jenkins Pipeline](https://stackoverflow.com/questions/38096004/how-to-add-a-timeout-step-to-jenkins-pipeline)
Please install Build Timeout plugin for your Jenkins. Jenkins> Manage Jenkins> Manage Plugins search for Build Timeout in available tab.. Install it. You would be finding it in Build environment as "Abort the build if it's stuck". Set the Timeout strategy and time. Absolute Deadline Elastic Likely Stuck No Activity in my case i have used No Activity. Hope it Helps.
3,479,916
I was wondering what would be a good way to accomplish the following using mysql: Lets say I have a table that contains these fields: ``` MyTable --------- Country [string] Region/Province/State [string] City [string] ``` And I have the following data rows in the database ``` Entry 1: Canada, Ontario, Toronto Entry 2: Canada, Ontario, Hamilton Entry 3: Canada, Alberta, Calgary ``` Now I want to be able to search that table based on user supplied information, However, if there are no results found with the user's supplied information I want the program to try and make it less specific. For example, if the user supplies: ``` Canada, Ontario, Kingston ``` I would like the search query to search for all 3 fields (which would produce 0 rows), then just for the country/region (which would produce 2 rows), and then just for the country (which should produce only 1 extra row on top of the previous two). Is that possible and, if it is, would it be fairly efficient ? Can this be done with 1 query or would it require multiple queries and then some cross-referencing to eliminate identical rows (I imagine that wouldn't be very efficient) ? Thank you very much! **Edit** By cross-referencing/multiple queries I was thinking about using UNION with several selects. But I was wondering if there is a better/more logical way to do this.
2010/08/13
[ "https://Stackoverflow.com/questions/3479916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/387302/" ]
**I would go with the 3 queries.** Normalize the table so you can check on small tables for `country`, `region/province/state` and `city` and then link them to the actual entries on a 1 -> N (one to many relationship). ``` SELECT * FROM cities LEFT JOIN actual_locations ON actual_locations.city = cities.id WHERE cities = 'NYC' ``` Hope it helps!
You can create a query that selects rows that match any of the three possibilities (matching Country, Region and City, matching Country and Region, matching Country). In that query you can use IF statements to assign a value and rank based on that value. It's simpler to run a query to see if a record matches all three inputs. If it returns no rows, run a query to match two. If that one returns no rows, match only the Country input.
9,243,221
Question: Are the result that i'm getting reasonable? Is there anything which could have such an impact in reducing the number of requests per second? ------------------------------------------------------------------------------------------------------------------------------------------------------ **Edit:** A friend of mine has just benchmarked the same application on Linux and the average r/s was approx 7000. **Edit #2:** I've checked the CPU usage of Node.exe, and it's only using 5-6% of the cpu. Surely this figure should be 12% on a quad core machine, 8 thread CPU when running on a single thread if truly under load? I've written a Node.js application (running Node v0.6.10) and benchmarked it with apachebench: `ab -c 256 -n 50000 http://localhost:3000/`. I'm getting a request per second rate of **roughly 650 requests per second**. There's too much code to put here, however this is the basic structure: **Application Settings:** ``` /** * Module dependencies. */ var util = require('util'), //Useful for inspecting JSON objects express = require('express'), //Express framework, similar to sinatra for ruby connect = require('connect'), //An integral part of the express framework app = module.exports = express.createServer(), //Create the server io = require('socket.io').listen(app), //Make Socket.io listen on the server parseCookie = require('connect').utils.parseCookie, //Parse cookies to retrieve session id MemoryStore = require('connect').session.MemoryStore, //Session memory store sessionStore = new MemoryStore(), Session = require('connect').middleware.session.Session, mongodb = require('mongodb'), //MongoDB Database BSON = mongodb.BSONPure, //Used to serialize JSON into BSON [binary] sanitize = require('validator').sanitize; // Configuration app.configure(function() { app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser()); app.use(express.session({ store: sessionStore, secret: '...', key: 'express.sid'})); app.use(app.router); app.use(express.static(__dirname + '/public')); }); app.configure('development', function(){ //app.use(express.errorHandler({dumpExceptions: true, showStack: true})); }); app.listen(3000); console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env); io.configure('development', function() { io.set('transports', ['websocket']); //io.set('heartbeats', false); //io.set('heartbeat timeout', 200); //io.set('heartbeat interval', 220); }); //MongoDB Database port and ip var DATABASE_PORT = 27017; var DATABASE_IP = "127.0.0.1"; //Localhost /* setInterval(function(){ console.log("BROWSING:\n" + util.inspect(browsing)); }, 1000); */ //Connected users var validUsers = {}; var clients = {}; var browsing = {}; //Database handles var users; var projects; //Connect to the database server db = new mongodb.Db('nimble', new mongodb.Server(DATABASE_IP, DATABASE_PORT, {}, {})); db.open(function (error, client) { if (error) { console.error("Database is currently not running"); throw error; } users = new mongodb.Collection(client, 'users'); //Handle to users projects = new mongodb.Collection(client, 'projects'); //Handle to projects }); app.get('/', function(req, res) { //users.insert("test", {safe:true}); //users.findOne("test", function(result){}) if(req.session.auth) { if(req.session.account == "client") { //Redirect to the client dash res.redirect('/dash'); } else if (req.session.account == "developer") { res.redirect('/projects'); } } else { res.redirect('/login'); } }); ``` Apart from the above code the only notable remaining code is a series of Express `app.get` and `app.post` event handlers. I have performed the same test on a basic Express set up web server, and the basic node.js http web server. **Node.js with Express server** ``` var express = require('express'); var app = express.createServer(); app.get('/', function(req, res){ res.send(); }); app.listen(3000); ``` **Node.js HTTP** ``` var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end(); }).listen(3000, "127.0.0.1"); ``` **The results being:** 2000 requests per second on Express 2200 requests per second on Node.js I've performed the same test against a static file hosted on an Apache web server: 6000 requests per second Now this benchmark shows Node.js beating Apache hands down! <http://zgadzaj.com/benchmarking-nodejs-basic-performance-tests-against-apache-php> **My relevant hardware spec:** Intel i7 2630qm 6 GB RAM
2012/02/11
[ "https://Stackoverflow.com/questions/9243221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/882993/" ]
I've found that node works really really slowly if you refer to it as "localhost", but very quickly if you refer to it by "127.0.0.1". I think the dns lookup on Windows is really what's slowing the requests down.
Do you realize that Apache uses multiple processes or threads to serve the requests, whereas there's a single Node.js process? Either configure Apache for a single worker process or thread, or run as many Node.js processes as you have CPU cores, and loadbalance among them.
72,475,806
How can we get data from an array of objects in angular. I have provided the typescript & service file & the consoled image. How can we able to get datas inside results object in the image?? Ts File ```html this.commonService.fetchVersionValue().subscribe((data) => { console.warn(data); }); ``` Service File ```html fetchVersionValue(): Observable<IVersionDetails[]> { return this.http.get<IVersionDetails[]>( `${this.PHP_API_SERVER}/api/get/versions` ); } ``` Image [![enter image description here](https://i.stack.imgur.com/s4qpv.png)](https://i.stack.imgur.com/s4qpv.png) while looking the console I got the error [![enter image description here](https://i.stack.imgur.com/kh0Kh.png)](https://i.stack.imgur.com/kh0Kh.png) The Api from php Server Help Me to Sort this Problem . Thanks in Advance
2022/06/02
[ "https://Stackoverflow.com/questions/72475806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18948657/" ]
```html this.commonService.fetchVersionValue().subscribe((response: any) => { console.warn(response.results.data); }); ``` This Works !!!
Your version details values are stored in the `data` property in the returned response. So you need to iterate over that property values. ``` this.commonService.fetchVersionValue().subscribe((response) => { console.warn(response.data); // Renaming to response for clarity }); ```
48,602,865
I have done this and it works. ``` CREATE TABLE Employee ( Employee_ID varchar2(10) PRIMARY KEY NOT NULL, Office_ID varchar2(7) NOT NULL, Emp_FirstName varchar2(20) NOT NULL, Emp_LastName varchar2(20) NOT NULL, Emp_Gender varchar2(1) NOT NULL, Emp_DateOfBirth Date NOT NULL, Hire_Date date NOT NULL, Emp_CurrentDate date default sysdate, Emp_Telephone varchar2(11) NOT NULL, Emp_Email varchar2(30) NOT NULL, Emp_AddressLine varchar2(50) NOT NULL, Emp_PostCode varchar2(8) NOT NULL, Emp_Speciality varchar2(20) NOT NULL, Emp_Qualification varchar2(20) NOT NULL, Emp_AwardingBody varchar2(30) NOT NULL, Emp_Salary number(6) NOT NULL, Emp_Supervised_By varchar2(10) NOT NULL, Employment_History1 varchar2(50), Employment_History2 varchar2(50), Employment_History3 varchar2(50) , CONSTRAINT fk_staff_office FOREIGN KEY (Office_ID) REFERENCES office (Office_ID), CONSTRAINT Hire_Date_CK check (Hire_Date < Emp_CurrentDate AND (Hire_Date - Emp_DateOfBirth)/365 > 18), CONSTRAINT Emp_DateOfBirth_CK check (Emp_DateOfBirth > TO_DATE('1900-01-01', 'YYYY-MM-DD')), CONSTRAINT Emp_Salary_CK check (Emp_Salary > 0 AND Emp_Salary < 150000), CONSTRAINT Emp_Gender_CK CHECK (Emp_Gender in ('M','F')), CONSTRAINT Emp_Email_CK CHECK ( Emp_Email like '%_@__%._%'), CONSTRAINT Emp_Telephone_CK CHECK (regexp_like(Emp_Telephone, '^[0123456789]{11}$') AND Emp_Telephone like '0%'), CONSTRAINT Emp_FirstName_CK CHECK (regexp_like(Emp_FirstName, '^[ABCDEFGHIJKLMNOPQRSTUVWXYZ]{1,20}$')), CONSTRAINT Emp_LastName_CK CHECK (regexp_like(Emp_LastName, '^[ABCDEFGHIJKLMNOPQRSTUVWXYZ]{1,20}$')), CONSTRAINT Emp_PostCode_CK CHECK (regexp_like ( Emp_PostCode , '([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))\s?[0-9][A-Za-z]{2})')), CONSTRAINT Emp_Speciality_CK CHECK (regexp_like(Emp_Speciality, '^[ABCDEFGHIJKLMNOPQRSTUVWXYZ ]{1,20}$')), CONSTRAINT Emp_Qualification_CK CHECK (regexp_like(Emp_Qualification, '^[ABCDEFGHIJKLMNOPQRSTUVWXYZ ]{1,20}$')), CONSTRAINT Emp_AwardingBody_CK CHECK (regexp_like(Emp_AwardingBody, '^[ABCDEFGHIJKLMNOPQRSTUVWXYZ ]{1,30}$')) ); ``` What I want to do now is to create a constraint that enables me to set the value of the attribute `Emp_Supervised_By` automatically as the same value of the `Employee_ID` attribute when the `Emp_Speciality` is 'Manager'. I tried to do it like this but it doesn't work: `CONSTRAINT Emp_Supervised_By_CK check (CASE WHEN Emp_Speciality = 'MANAGER' THEN Emp_Supervised_By = Employee_ID)` **Is a requirement to use CONSTRAINTS NOT TRIGGERS**.
2018/02/03
[ "https://Stackoverflow.com/questions/48602865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9289017/" ]
Because you mentioned computed columns, maybe your business requirement can be satisfied with the below instead of a constraint. ``` CREATE TABLE Employee ( ... Employee_ID varchar2(10) PRIMARY KEY NOT NULL, Emp_Speciality varchar2(20) NOT NULL, Emp_Supervised_By AS (CASE WHEN Emp_Speciality = 'Manager' THEN Employee_ID ELSE NULL END) .... ); ```
I did this and it works: `CREATE TABLE OrderLine ( Invoice_ID varchar2(10) PRIMARY KEY NOT NULL, Item_ID varchar2(10) NOT NULL, Unit_Price number(6,2) NOT NULL, Quantity number(6) NOT NULL, Total_Price number(38,2) AS (CASE WHEN Quantity >= 50 THEN ((Unit_Price*Quantity)-((Unit_Price*Quantity)*0.80)) ELSE Unit_Price*Quantity END) NOT NULL, CONSTRAINT fk_item_invoice FOREIGN KEY(Invoice_ID) REFERENCES Invoice (Invoice_ID), CONSTRAINT fk_item_item FOREIGN KEY(Item_ID) REFERENCES Item (Item_ID), CONSTRAINT Unit_Price_CK CHECK (Unit_Price > 0), CONSTRAINT Quantity_CK CHECK (Quantity > 0), CONSTRAINT Total_Price_CK CHECK (Total_Price > 0) );` `CREATE TABLE Invoice ( Invoice_ID varchar2(10) PRIMARY KEY NOT NULL, Office_ID varchar2(7) NOT NULL, Invoice_Date Date NOT NULL, Total_Cost number (9) NOT NULL, CONSTRAINT fk_order_Office FOREIGN KEY(Office_ID) REFERENCES Office (Office_ID), CONSTRAINT Total_Cost_CK CHECK (Total_Cost > 0) );` I want to calculate The TotalCost like the sum of TotalPrice(s). Is there a way to use the same approach ass before ?
17,820,460
I have a large mysql table - basically a slightly altered LDAP dump. 120K employees. The table is needed for lots of things but I have one task that is pegging the server - recursive queries. Each employee has the empl. id and supervisor id on their row. Easy parent child relationship. However one of the applications we have is a mass email app. And we use the LDAP table to search for all employees under a given manager. Well this may go 6-10 levels deep and include 10-20K rows. It is intense. My current system is not working for large queries. So how can I automate the parent child relationship into a nested set? This is really beyond what I have done in mysql so any help is appreciated. Also how has this not been asked 100 times?
2013/07/23
[ "https://Stackoverflow.com/questions/17820460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1766389/" ]
Data.getData() is not null when requesting a thumbnail. When recording a picture to any location it will always be null.
EDIT It's probably wrong but i did this to get uri after ACTION\_IMAGE\_CAPTURE and it works for me. ``` Bitmap picture = (Bitmap) data.getExtras().get("data"); ByteArrayOutputStream stream = new ByteArrayOutputStream(); picture.compress(Bitmap.CompressFormat.JPEG, 100, stream); String path = Images.Media.insertImage(getContentResolver(), picture, "title" , null); Uri uriPhoto = Uri.parse(path); ```
3,962,545
i've been imagining that in the base 16 the number 10 is A and 11 is B so in the base 37, 35 will be Z so how we can write 36 ?
2020/12/26
[ "https://math.stackexchange.com/questions/3962545", "https://math.stackexchange.com", "https://math.stackexchange.com/users/784946/" ]
You could use a different symbol. Or you could use commas to separate place values in this base. Something like $5,22,36$ could represent the three-digit base thirty-seven numeral whose value in decimal would be $5\cdot 37^2+22\cdot 37 +36$.
You can use underscore `_` as symbol nr 36 (as the last symbol in your alphabet). Then you can have nice looking test IDs, if you have unit tests or end-to-end tests, e.g.: ``` 123abczxy_for_widget_a 456uvwxyz_user_b23 456uvwxyz_user_b23_copy ``` So, your 37 symbols could be: `0...9abc...xyz_`.
32,633,920
I tend to use a lot of line breaks in my code like the following: ``` # Data ========================================================================= ``` Where the entire comment is always 80 characters long (including the hashtag). What I would like to do is write a code snippet for Rstudio that will insert the hashtag, then a space, then allow the user to type out a series of words, then insert another space, and finally fill in a bunch of "=" until the 80 character limit is reached. I'm not familiar with how snippets work at all so I'm not sure how difficult this is. I have this much: ``` snippet lb # ${1:name} ``` but I have no idea how to add a dynamic number of "=" signs. Also, lb = linebreak.
2015/09/17
[ "https://Stackoverflow.com/questions/32633920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4379461/" ]
You can't do this with snippets, unfortunately; a snippet is a text template that contains fixed text with slots for user-inserted text. There is a command built into RStudio to do something very similar, however; from the Code menu, choose Insert Section (or `Ctrl`+`Shift`+`R`). This will do exactly what you're describing, with two small differences: 1. The line will extend to 5 characters before the print margin (you can adjust the print margin in Tools -> Global Options -> Code. 2. The line is composed of `-` rather than `=` characters. One advantage to sections marked in this way is that you can use them to fold and navigate inside the file (look at the editor status bar after adding one).
Inspired by nick's answer above I designed two snippets that allow the user to choose what level section to insert. The first will fill-in the rest of the line with `#`, `=`, or `-`. ``` snippet end `r strrep(ifelse(substr("$$", 1, 1) %in% c("-", "="), substr("$$", 1, 1), "#"), 84 - rstudioapi::primary_selection(rstudioapi::getActiveDocumentContext())$range$start[2])` ``` Just specify the character you want to use after `end` (will default to `#` if nothing or any other character is given). For example: ``` ## Level 1 Header end<shift+tab> ## Level 2 Header end=<shift+tab> ## Level 3 Header end-<shift+tab> end<shift+tab> end=<shift+tab> end-<shift+tab> ``` Produces the following lines: ``` ## Level 1 Header ############################################################## ## Level 2 Header ============================================================= ## Level 3 Header ------------------------------------------------------------- ################################################################################ =============================================================================== ------------------------------------------------------------------------------- ```
9,264
There is an [old question on Christianity.SE](https://christianity.stackexchange.com/questions/2038/why-are-thighs-important) which I suggested that it should also be asked here - since we don't migrate OLD questions. In doing so, I noticed that the OP hasn't been really active and I suspect that it will never be asked here. With that said: **Genesis 24:2 NIV** > > One day Abraham said to his oldest servant, the man in charge of his household, “Take an oath by putting your hand under my **thigh**. > > > **Genesis 47:29 NIV** > > As the time of his death drew near, Jacob called for his son Joseph and said to him, “Please do me this favor. Put your hand under my **thigh** and swear that you will treat me with unfailing love by honoring this last request: Do not bury me in Egypt. > > > **Leviticus 7:33 NIV** > > The right **thigh** must always be given to the priest who offers the blood and the fat of the peace offering. > > > Is this a translation concern? What do they REALLY mean?
2014/05/22
[ "https://hermeneutics.stackexchange.com/questions/9264", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/444/" ]
Copied and pasted from <http://www.gotquestions.org/hand-under-thigh.html> > > The thigh was considered the source of posterity in the ancient world. > Or, more properly, the “loins” or the testicles. The phrase “under the > thigh” could be a euphemism for “on the loins.” There are two reasons > why someone would take an oath in this manner: 1) Abraham had been > promised a “seed” by God, and this covenantal blessing was passed on > to his son and grandson. Abraham made his trusted servant swear “on > the seed of Abraham” that he would find a wife for Isaac. 2) Abraham > had received circumcision as the sign of the covenant (Genesis 17:10). > Our custom is to swear on a Bible; the Hebrew custom was to swear on > circumcision, the mark of God’s covenant. The idea of swearing on > one’s loins is found in other cultures, as well. The English word > testify is directly related to the word testicles. > > > Read more: <http://www.gotquestions.org/hand-under-thigh.html#ixzz32TlIHdjn>
The concept/s behind this focus on the male organ becomes moot when it is set amid the land they had come to occupy, Canaan, which was the epitome of matriarchy from before history. When fatherhood, the ultimate dubious concept, is confronted with its irrelevance it is emasculating. The crucial aspect is the circumcision which instantly sets them as aliens, self selected and thereby encumbered. This did not inhibit Judah with Tamar (Gen38:10-30) but, hey double standards, wotcha gonna do? As their monotheism was incompatible with worship of the Great Mother so their flocks from the high country, sheep & goats, were supremely deleterious to the long settled land of agriculture. (They adopted *bovis* & *bos* post invasion, long afterwards.) Apart from the botanical damage & grazing (both short & long term, ie sapling regrowth) the effect trampling hooves, small & sharp, on irrigation channels was dire & total. In a flat land without rain, crops can only be grown with great care of water resources. The "torrent valleys" away SE in Moab were created by denuding the hillsides.
39,985,917
Here's the link to the page I made: <https://thawing-savannah-89995.herokuapp.com/> This is my first webpage I've made without help using only a PSD. Here's a SS of the area I'm having issues with and keeps breaking when I shrink the browser size. This layout was very difficult for me to think through and I don't think it should've been. How can I better design the html and CSS for that part? [![enter image description here](https://i.stack.imgur.com/XpNgu.png)](https://i.stack.imgur.com/XpNgu.png)
2016/10/11
[ "https://Stackoverflow.com/questions/39985917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5137592/" ]
How about set the `UserID` as index and then join on index for the second data frame? ``` pd.merge(df1, df2.set_index('UserID'), left_on='UserName', right_index=True) # Col1 UserName Col2 # 0 a 1 d # 1 b 2 e # 2 c 3 f ```
There is nothing really nice in it: it's meant to be keeping the columns as the larger cases like left right or outer joins would bring additional information with two columns. Don't try to overengineer your merge line, be explicit as you suggest Solution 1: ``` df2.columns = ['Col2', 'UserName'] pd.merge(df1, df2,on='UserName') Out[67]: Col1 UserName Col2 0 a 1 d 1 b 2 e 2 c 3 f ``` Solution 2: ``` pd.merge(df1, df2, left_on='UserName', right_on='UserID').drop('UserID', axis=1) Out[71]: Col1 UserName Col2 0 a 1 d 1 b 2 e 2 c 3 f ```
54,657,896
I have an input dict-of-string-to-list with possibly different lengths for the list. ``` d = {'b': [2,3], 'a': [1]} ``` when I do: `df = pd.DataFrame(data=d)`, i'm seeing **ValueError: arrays must all be same length** **Question**: How do i fill the missing values with default (e.g. 0) when creating the df? --- The reason to create the df is to get the final result of: `{'b': 3}` whereas `3` is the max of all numbers in the lists.
2019/02/12
[ "https://Stackoverflow.com/questions/54657896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3380951/" ]
You can use [`DataFrame.from_dict`](https://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.DataFrame.from_dict.html) setting `orient` to `index` so the keys of the dictionary are used as indices and the missing values are set to `NaN`. Then simply fill `NaNs` using [`.fillna`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html) and transpose to set the keys as columns: ``` pd.DataFrame.from_dict(d, orient='index').fillna(0).T b a 0 2.0 1.0 1 3.0 0.0 ```
``` d = {'b': [2,3], 'a': [1]} df = pd.DataFrame({ k:pd.Series(v) for k, v in d.items() }) ``` This will give the following output. ``` a b 0 1.0 2 1 NaN 3 ```
73,254,705
I have several custom queries in an interface that extends JpaRepository. The interface is analogous to the below (note: the below is just for illustration, and may have errors, but don't concern yourself with that). ``` public interface MyRepo extends JpaRepository<SMark, String> { @Transactional @Modifying @Query(value = "INSERT INTO my_table(id, col_1, col_2) " + "values(:col_1, :col_2))", nativeQuery = true) int insertRecord(@Param("col_1") String col_1, @Param("col_2") String col_2); ``` So, my issue is that I am finding it difficult to do anything useful with the int return type for anything other than a successful query (which will return a 1). Is there a way to do anything useful with the return other than sending the value as part of the response? In other words, if the response is not a 1, and an exception is not thrown, can the non-1 response be translated into something more informative to the user? For example, I am currently doing the following, which I would like to improve upon if I was a confident about the not-1 status: ``` if(status == 1) { StatusResponse statusResponse = new StatusResponse("Successful Delete ", null); return new ResponseEntity<>(statusResponse, HttpStatus.OK); } else { StatusResponse statusResponse = new StatusResponse("Delete not successful (lacking details from response) ", null); return new ResponseEntity<>(statusResponse, HttpStatus.NOT_ACCEPTABLE); } ``` Grateful for any response. Thanks!
2022/08/05
[ "https://Stackoverflow.com/questions/73254705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8796806/" ]
Use js. First, give your textarea an id attr: `<textarea id="text"></textarea>` then, ``` <script> let t = document.getElementById('text') function addShortcut(placeholder, emoji) { t.addEventListener('change', function(e){ if(t.value.includes(placeholder)) { t.value = t.value.split(placeholder).join(emoji) } }) } //examples: addShortcut('hi', 'hello') addShortcut(':shug:', '¯\\_(ツ)_/¯') </script> ``` If you want to add a shortcut, just use `addShortcut` again after where I did. you can delete the examples Edit: made a typo, fixed it Edit: If you want to have an image, then do something like this: ``` addShortcut(":gif:", "<img src='animation.gif' height='14px' width='auto'></gif>") ``` If you want to use a smaller text size, then just change the height attribute to match your text size. Edit: ```js let t = document.getElementById('text') function addShortcut(placeholder, emoji) { t.addEventListener('blur', function(e) { if (t.innerHTML.includes(placeholder)) { t.value = t.innerHTML.split(placeholder).join(emoji) } }) } //examples: addShortcut('hi', 'hello') addShortcut(':shrug:', '¯\\_(ツ)_/¯') addShortcut(':check:', '<img src="https://cdn.pixabay.com/photo/2016/10/10/01/49/hook-1727484_1280.png"></img>') ``` ```css textarea { font-size: 14px; } ``` ```html <textarea contentEditable="true" id='text' style='border: 1px solid #ccc;'>Hello</textarea> ```
To change source of image I would recommend selecting your image using query selector and then simply replacing it to other image ``` <img class="example-image" src="./image.jpg" alt=""> <script> document.querySelector('.example-image').src = 'image-replace.jpg'; </script> ``` Have in mind that in shown example I used picture I already had on disc, but you can use url to image, and if you want to use textarea to get image path/url, here is the code to do so, it works on a button click: ``` <img class="example-image" src="./image.jpg" alt=""> <textarea class="example-textarea" cols="30" rows="10"></textarea> <button class="example-btn">Click</button> <script> document.querySelector(".example-btn").addEventListener("click", ()=>{ document.querySelector('.example-image').src = document.querySelector('.example-textarea').value; }) </script> ```
19,347,444
The following output is a result of calling `var_export($charge)`; How can I access the output of `'paid'=>true` from `$charge`? Any ideas would be appreciated. I have tried `$charge->_values->paid`, `$charge->paid`, etc.. I haven't had any luck. I have also tried `$charge['_values']['paid']`; ``` Stripe_Charge::__set_state(array( '_apiKey' => 'sk_test_BPZyFpcAM', '_values' => array ( 'id' => 'ch_102kMF29T6', 'object' => 'charge', 'created' => 1381688, 'livemode' => false, 'paid' => true, 'amount' => 104000, 'currency' => 'usd', 'refunded' => false, 'card' => Stripe_Card::__set_state(array( '_apiKey' => 'sk_test_BPZyFpc', '_values' => array ( 'id' => 'card_102kMF29T6', 'object' => 'card', 'last4' => '4242', 'type' => 'Visa', 'exp_month' => 2, 'exp_year' => 2015, 'fingerprint' => '7sRY4jiFM', 'customer' => NULL, 'country' => 'US', 'name' => NULL, 'address_line1' => NULL, 'address_line2' => NULL, 'address_city' => NULL, 'address_state' => NULL, 'address_zip' => NULL, 'address_country' => NULL, 'cvc_check' => 'pass', 'address_line1_check' => NULL, 'address_zip_check' => NULL, ), '_unsavedValues' => Stripe_Util_Set::__set_state(array( '_elts' => array ( ), )), '_transientValues' => Stripe_Util_Set::__set_state(array( '_elts' => array ( ), )), '_retrieveOptions' => array ( ), )), 'captured' => true, 'refunds' => array ( ), 'balance_transaction' => 'txn_102kMF29T6Z', 'failure_message' => NULL, 'failure_code' => NULL, 'amount_refunded' => 0, 'customer' => NULL, 'invoice' => NULL, 'description' => 'admin@fra.org', 'dispute' => NULL, 'metadata' => array ( ), ), '_unsavedValues' => Stripe_Util_Set::__set_state(array( '_elts' => array ( ), )), '_transientValues' => Stripe_Util_Set::__set_state(array( '_elts' => array ( ), )), '_retrieveOptions' => array ( ), )) ```
2013/10/13
[ "https://Stackoverflow.com/questions/19347444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2355051/" ]
you can use `__toArray()` method: ``` $array = $collection->__toArray(true); ``` This will work for this case
whatever returns please parse it with json\_decode and you will get a assoc array in php i.e suppose return array is $ret ``` $ret = json_decode($ret); $ret->paid; $ret->captured; $ret->card->id; and so on.. ``` Hope it will help you.
28,939,067
whenever, I mouseover on the 'li', then, that particular 'li' attribute need to changed to 'clsSect'. On the other hand, based on the list[li] selection, the div content has to set to 'display:block' other should changed to 'display:none'. if the first 'li' selected, then, the first 'div' need to be selected, likewise if the second 'li' selected, then, the second 'div' need to be selected, This below code does not work as expected. Any help please? ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <html> <head> <script src="js/jquery.min.js"></script> <style> </style> </head> <body> <div class="mainBodyContent" id="Contact"> <div class="perimgleft"> <img class="perImg" alt="This is for sample"/> <div id="thisID3"> <p><span>sample3</span></p> <p>To explore job opputunities at 'Company', see our <a name="Career" href="#Careers"><span>Hot Jobs</span></a></p> </div></div> </div> <div class="mainBodyContent" id="About"> <div class="perimgleft"> <img class="perImg" alt="This is for sample"/> <div id="thisID2"> <p><span>sample3</span></p> <p>To explore job opputunities at 'Company', see our <a name="Career" href="#Careers"><span>Hot Jobs</span></a></p> </div></div> </div> <div class="mainBodyContent" id="Careers"> <div class="perimgleft"> <img class="perImg" alt="This is for sample"/> <div id="thisID1"> <p><span>sample1</span></p> <p>To explore job opputunities at 'Company', see our <a name="Career" href="#Careers"><span>Hot Jobs</span></a></p> </div></div> </div> <div id="selRound"> <ul class="clearfix rouncorner"> <li id="fpn1" class="myList clsSect"></li> <li id="fpn2" class="myList"></li> <li id="fpn3" class="myList"></li> </ul> </div> <script> var $hover = $("div.perimgleft img"); $hover1 = $("#Contact div[class='perimgleft'] div");$hover2 = $("#About div[class='perimgleft'] div");$hover3 = $("#Careers div[class='perimgleft'] div"); $("#selRound .myList").mouseover(function(evt) { if(evt.currentTarget.id == 'fpn1'){ $hover1.css('display', 'block'); ($hover2, $hover3).css('display', 'none'); } else if(evt.currentTarget.id == 'fpn2'){ ($hover1, $hover3).css('display', 'none'); $hover2.css('display', 'block'); }else { ($hover1, $hover2).css('display', 'none'); $hover3.css('display', 'block'); } }); $("#selRound .myList").mouseout(function(evt) { }); </script> </body> </html> ```
2015/03/09
[ "https://Stackoverflow.com/questions/28939067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4622995/" ]
on nest version 6 use ``` connextionString.DisableDirectStreaming(); ``` then on response.DebugInformation you can see all information.
Use `result.ConnectionStatus.Request`.
1,854,288
I can use `isset($var)` to check if the variable is not defined or null. (eg. checking if a session variable has been set before) But after setting a variable, how do I reset it to the default such that `isset($var)` returns `false`?
2009/12/06
[ "https://Stackoverflow.com/questions/1854288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41021/" ]
As nacmartin said, `unset` will "undefine" a variable. You could also set the variable to null, however this is how the two approaches differ: ``` $x = 3; $y = 4; isset($x); // true; isset($y); // true; $x = null; unset($y); isset($x); // false isset($y); // false echo $x; // null echo $y; // PHP Notice (y not defined) ```
Also, you can set the variable to `null`: ``` <?php $v= 'string'; var_dump(isset($v)); $v= null; var_dump(isset($v)); ?> ```
19,703,380
**PROBLEM ONLY APPEARS WHEN NO MAIL ACCOUNT IS CONFIGURED - STILL I WOULD APPRECIATE A SOLUTION** I need some help. I have found a very weird habit of this little Script. And I have absolutely no clue, why this should happen. If I run through the code posted below, **Microsoft Outlook** starts. And as long as I don't **terminate** the *Outlook* process the script is stuck! Why would this code, ever, start Outlook? I am lost! ``` $Path = "C:\test.xls" #Excelvar: $Row = [int] 2 $Excel = New-Object -ComObject Excel.Application $Excel.Visible = $true $Excel.DisplayAlerts = $false #Sheets: $ADUsers = "Active Directory Users" $Groups = "Create Groups" $UsertoGroup = "User to groups" $DNS = "DNS" #$Worksheet = $Workbook.Sheets.Add() $checkxls = test-path -pathtype Any $Path if ($checkxls -eq $false) { $wb = $Excel.Workbooks.Add() $wb.Worksheets.add() $wb.SaveAs($Path) $wb.Close() $Excel.Quit() ``` Thx in advance! Powershell output after Outlook is terminated: ``` Application : Microsoft.Office.Interop.Excel.ApplicationClass Creator : 1480803660 Parent : System.__ComObject CodeName : _CodeName : Index : 1 Name : Tabelle4 Next : System.__ComObject OnDoubleClick : OnSheetActivate : OnSheetDeactivate : PageSetup : System.__ComObject Previous : ProtectContents : False ProtectDrawingObjects : False ProtectionMode : False ProtectScenarios : False Visible : -1 Shapes : System.__ComObject TransitionExpEval : False AutoFilterMode : False EnableCalculation : True Cells : System.__ComObject CircularReference : Columns : System.__ComObject ConsolidationFunction : -4157 ConsolidationOptions : {False, False, False} ConsolidationSources : DisplayAutomaticPageBreaks : False EnableAutoFilter : False EnableSelection : 0 EnableOutlining : False EnablePivotTable : False FilterMode : False Names : System.__ComObject OnCalculate : OnData : OnEntry : Outline : System.__ComObject Rows : System.__ComObject ScrollArea : StandardHeight : 15 StandardWidth : 10,71 TransitionFormEntry : False Type : -4167 UsedRange : System.__ComObject HPageBreaks : System.__ComObject VPageBreaks : System.__ComObject QueryTables : System.__ComObject DisplayPageBreaks : False Comments : System.__ComObject Hyperlinks : System.__ComObject _DisplayRightToLeft : False AutoFilter : DisplayRightToLeft : False Scripts : System.__ComObject Tab : System.__ComObject MailEnvelope : CustomProperties : System.__ComObject SmartTags : System.__ComObject Protection : System.__ComObject ListObjects : System.__ComObject EnableFormatConditionsCalculation : True Sort : System.__ComObject PrintedCommentPages : 0 ```
2013/10/31
[ "https://Stackoverflow.com/questions/19703380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2541974/" ]
The issue here is that when you run `$wb.Worksheets.add()` it returns the new worksheet to the pipeline (this is why the Sheet properties are displayed when you kill Outlook). I believe the MailEnvelope property of the Worksheet is what causes Outlook to open (if you store the Sheet and return the MailEnvelope property, the same behaviour occurs). To get around this you can store the returned sheet, use the Out-Null cmdlet or cast the worksheet to void: `$ws = $wb.Worksheets.add()` or `$wb.Worksheets.add() | Out-Null` or `[void] $wb.Worksheets.add()`
You might try running Excel in "safe mode": <http://social.msdn.microsoft.com/Forums/vstudio/en-US/79a8d280-3b80-4371-95e1-e7827472d36f/how-to-start-excel-in-safe-mode-programmatically?forum=vsto>
65,824
I was wondering if there are some particularly important mechanism by which one can break electronics, when undervolting it. Its pretty obvious that lots of electronics will not work properly if undervolted, but what about permanent damage? The question was motivated by repair work. I was wondering about what sorts of secondary effects one should look for when a damaged power supply was involved. I imagine motors could be damaged if they stalled due to undervolting. So what are specific mechanisms for permemenant damage due to undervolting (or better put undersupplying)? Are there even any? To add to the question, what are components or simple circuits that fail when undersupplied?
2013/04/16
[ "https://electronics.stackexchange.com/questions/65824", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/22675/" ]
Wouter has some good information, but there are more scenarios where not providing a high enough voltage can damage a device. Some higher end display screens require multiple voltage sources, and failing to power one source to a high enough level, or fast enough, before a second source, can cause damage to the screen or controller. Some devices with internal mosfet can be damaged by underpowering the source. As was explained by a TI employee about a current controlled led driver, if the VLed source is too low to provide the selected current through a channel, the logic in that channel will try to drive the channel's mosfet harder to try to sink more current. Eventually, the mosfet will burn out, if not other parts of the chip. I wish I could find that discussion and link it. While not directly causing damage to the device being underpowered, failing to provide the right voltage to a heating element could cause what is being heated to not heat up correctly/fast enough. Winter Water Pipe heaters, electric stoves, microwaves (for a loose meaning of "heater"), certain car parts. Worse, medical devices or heating in artic environments. Same for cooling solutions, like fans or ACs or pelters. A underperforming fan due to voltage issues can cause it's target to overheat. Water pumps as well. And all three can be damaged by the side effects of it. Water pumps normally use the moving water to cool themselves. A lower voltage will cause it to move water, but might not be fast enough to cool itself down. Underperforming fans might be cooked by the device it could not cool down. Heaters themselves might freeze if they cannot get hot enough. And last I can think of, battery chargers. A malfunctioning charger, or simply badly designed one, as part of a larger circuit, could cause a lower voltage in a charging state. A battery could feed back into the circuit when it shouldn't.
It depends on your load. If it's a resistive load, lowering voltage means it will conduct less current and dissipate less heat. Nothing wrong here. If you drop the voltage on the gate/base of a transistor and it may not fully saturate and have a larger voltage drop. As power dissipation is P=U\*I; the voltage drop on the transistor could double (from 0.5V to 1V) while the current may stay more or less the same (for e.g. 1000mA to 800mA). You effectively doubled the power dissipation and that could lead to damage! If the device uses a linear regulator, the regulator will have to regulate less voltage. This will lead to lower power dissipation. Of course there is a limit at which the regulator cannot maintain regulation anymore and the output voltage will drop too. This output may shutdown or stop working at a certain point. Switch mode power supplies are a constant power load. If you assume the output to draw a constant power ; for example 3.3V 1A. This equals to 3.3W which means whatever the input voltage is, it will always draw 3.3W. In practice you have efficiency (which can vary) and limits to the voltage region, but it will try to draw 3.3W. If the input voltage drops the input current increases. If parts like inductors, diodes or MOSFETs cannot handle the higher current (heat dissipation or exceeding saturation/peak currents) it can cause damage. However, in that case you're probably exceeding a certain operation window. For example, a product may have a input voltage requirement of 9-15V. Although the switching regulator would work fine on (for example) 7V, it may exceed the current on some part and become unreliable. Sometimes you see "Undervoltage lock-out" on these devices. This is a voltage at which the switch mode supply will shutdown because it cannot guarantee reliable operation.