qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
20,810,210
Consider the following class: ``` public class MyClass { private MyObject obj; public MyClass() { obj = new MyObject(); } public void methodCalledByOtherThreads() { obj.doStuff(); } } ``` Since obj was created on one thread and accessed from another, could obj be null when methodCalledByOtherThread is called? If so, would declaring obj as volatile be the best way to fix this issue? Would declaring obj as final make any difference? Edit: For clarity, I think my main question is: Can other threads see that obj has been initialized by some main thread or could obj be stale (null)?
2013/12/28
[ "https://Stackoverflow.com/questions/20810210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2605245/" ]
For the `methodCalledByOtherThreads` to be called by another thread and cause problems, that thread would have to get a reference to a `MyClass` object whose `obj` field is not initialized, ie. where the constructor has not yet returned. This would be possible if you leaked the `this` reference from the constructor. For example ``` public MyClass() { SomeClass.leak(this); obj = new MyObject(); } ``` If the `SomeClass.leak()` method starts a separate thread that calls `methodCalledByOtherThreads()` on the `this` reference, then you would have problems, but this is true regardless of the `volatile`. Since you don't have what I'm describing above, your code is fine.
This class (if taken as is) is NOT thread safe. In two words: there is reordering of instructions in java ([Instruction reordering & happens-before relationship in java](https://stackoverflow.com/questions/16213443/instruction-reordering-happens-before-relationship-in-java)) and when in your code you're instantiating MyClass, under some circumstances you may get following set of instructions: * Allocate memory for new instance of MyClass; * Return link to this block of memory; * Link to this not fully initialized MyClass is available for other threads, they can call "methodCalledByOtherThreads()" and get NullPointerException; * Initialize internals of MyClass. In order to prevent this and make your MyClass really thread safe - you either have to add "final" or "volatile" to the "obj" field. In this case Java's memory model (starting from Java 5 on) will guarantee that during initialization of MyClass, reference to alocated for it block of memory will be returned only when all internals are initialized. For more details I would strictly recommend you to read nice book "Java Concurrency in Practice". Exactly your case is described on the pages 50-51 (section 3.5.1). I would even say - you just can write correct multithreaded code without reading that book! :)
20,810,210
Consider the following class: ``` public class MyClass { private MyObject obj; public MyClass() { obj = new MyObject(); } public void methodCalledByOtherThreads() { obj.doStuff(); } } ``` Since obj was created on one thread and accessed from another, could obj be null when methodCalledByOtherThread is called? If so, would declaring obj as volatile be the best way to fix this issue? Would declaring obj as final make any difference? Edit: For clarity, I think my main question is: Can other threads see that obj has been initialized by some main thread or could obj be stale (null)?
2013/12/28
[ "https://Stackoverflow.com/questions/20810210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2605245/" ]
It depends on whether the reference is published "unsafely". A reference is "published" by being written to a shared variable; another thread reads the variable to get the reference. If there is no relationship of `happens-before(write, read)`, the publication is called unsafe. An example of unsafe publication is through a non-volatile static field. @chrylis 's interpretation of "unsafe publication" is not accurate. Leaking `this` before constructor exit is orthogonal to the concept of unsafe publication. Through unsafe publication, another thread may observe the object in an uncertain state (hence the name); in your case, field `obj` may appear to be null to another thread. Unless, `obj` is `final`, then it cannot appear to be null even if the host object is published unsafely. This is all too technical and it requires further readings to understand. The good news is, you don't need to master "unsafe publication", because it is a discouraged practice anyway. The best practice is simply: never do unsafe publication; *i.e.* never do data race; *i.e.* always read/write shared data through proper synchronization, by using `synchronized, volatile` or `java.util.concurrent`. If we always avoid unsafe publication, do we still *need* `final` fields? The answer is no. Then why are some objects (e.g. `String`) designed to be "thread safe immutable" by using final fields? Because it's assumed that they can be used in malicious code that tries to create uncertain state through deliberate unsafe publication. I think this is an overblown concern. It doesn't make much sense in server environments - if an application embeds malicious code, the server is compromised, period. It probably makes a bit of sense in Applet environment where JVM runs untrusted codes from unknown sources - even then, this is an improbable attack vector; there's no precedence of this kind of attack; there are a lot of other more easily exploitable security holes, apparently.
This class (if taken as is) is NOT thread safe. In two words: there is reordering of instructions in java ([Instruction reordering & happens-before relationship in java](https://stackoverflow.com/questions/16213443/instruction-reordering-happens-before-relationship-in-java)) and when in your code you're instantiating MyClass, under some circumstances you may get following set of instructions: * Allocate memory for new instance of MyClass; * Return link to this block of memory; * Link to this not fully initialized MyClass is available for other threads, they can call "methodCalledByOtherThreads()" and get NullPointerException; * Initialize internals of MyClass. In order to prevent this and make your MyClass really thread safe - you either have to add "final" or "volatile" to the "obj" field. In this case Java's memory model (starting from Java 5 on) will guarantee that during initialization of MyClass, reference to alocated for it block of memory will be returned only when all internals are initialized. For more details I would strictly recommend you to read nice book "Java Concurrency in Practice". Exactly your case is described on the pages 50-51 (section 3.5.1). I would even say - you just can write correct multithreaded code without reading that book! :)
20,810,210
Consider the following class: ``` public class MyClass { private MyObject obj; public MyClass() { obj = new MyObject(); } public void methodCalledByOtherThreads() { obj.doStuff(); } } ``` Since obj was created on one thread and accessed from another, could obj be null when methodCalledByOtherThread is called? If so, would declaring obj as volatile be the best way to fix this issue? Would declaring obj as final make any difference? Edit: For clarity, I think my main question is: Can other threads see that obj has been initialized by some main thread or could obj be stale (null)?
2013/12/28
[ "https://Stackoverflow.com/questions/20810210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2605245/" ]
For the `methodCalledByOtherThreads` to be called by another thread and cause problems, that thread would have to get a reference to a `MyClass` object whose `obj` field is not initialized, ie. where the constructor has not yet returned. This would be possible if you leaked the `this` reference from the constructor. For example ``` public MyClass() { SomeClass.leak(this); obj = new MyObject(); } ``` If the `SomeClass.leak()` method starts a separate thread that calls `methodCalledByOtherThreads()` on the `this` reference, then you would have problems, but this is true regardless of the `volatile`. Since you don't have what I'm describing above, your code is fine.
It depends on whether the reference is published "unsafely". A reference is "published" by being written to a shared variable; another thread reads the variable to get the reference. If there is no relationship of `happens-before(write, read)`, the publication is called unsafe. An example of unsafe publication is through a non-volatile static field. @chrylis 's interpretation of "unsafe publication" is not accurate. Leaking `this` before constructor exit is orthogonal to the concept of unsafe publication. Through unsafe publication, another thread may observe the object in an uncertain state (hence the name); in your case, field `obj` may appear to be null to another thread. Unless, `obj` is `final`, then it cannot appear to be null even if the host object is published unsafely. This is all too technical and it requires further readings to understand. The good news is, you don't need to master "unsafe publication", because it is a discouraged practice anyway. The best practice is simply: never do unsafe publication; *i.e.* never do data race; *i.e.* always read/write shared data through proper synchronization, by using `synchronized, volatile` or `java.util.concurrent`. If we always avoid unsafe publication, do we still *need* `final` fields? The answer is no. Then why are some objects (e.g. `String`) designed to be "thread safe immutable" by using final fields? Because it's assumed that they can be used in malicious code that tries to create uncertain state through deliberate unsafe publication. I think this is an overblown concern. It doesn't make much sense in server environments - if an application embeds malicious code, the server is compromised, period. It probably makes a bit of sense in Applet environment where JVM runs untrusted codes from unknown sources - even then, this is an improbable attack vector; there's no precedence of this kind of attack; there are a lot of other more easily exploitable security holes, apparently.
20,810,210
Consider the following class: ``` public class MyClass { private MyObject obj; public MyClass() { obj = new MyObject(); } public void methodCalledByOtherThreads() { obj.doStuff(); } } ``` Since obj was created on one thread and accessed from another, could obj be null when methodCalledByOtherThread is called? If so, would declaring obj as volatile be the best way to fix this issue? Would declaring obj as final make any difference? Edit: For clarity, I think my main question is: Can other threads see that obj has been initialized by some main thread or could obj be stale (null)?
2013/12/28
[ "https://Stackoverflow.com/questions/20810210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2605245/" ]
Your other thread **could** see a null object. A volatile object could possibly help, but an explicit lock mechanism (or a Builder) would likely be a better solution. Have a look at [Java Concurrency in Practice - Sample 14.12](https://stackoverflow.com/questions/10528572/java-concurrency-in-practice-sample-14-12)
The originally picked answer by @Sotirios Delimanolis is wrong. @ZhongYu 's answer is correct. There is the visibility issue of the concern here. So if MyClass is published unsafely, anything could happen. Someone in the comment asked for evidence - one can check Listing 3.15 in the book *Java Concurrency in Practice*: ``` public class Holder { private int n; // Initialize in thread A public Holder(int n) { this.n = n; } // Called in thread B public void assertSanity() { if (n != n) throw new AssertionError("This statement is false."); } } ``` Someone comes up an example to verify this piece of code: [coding a proof for potential concurrency issue](https://stackoverflow.com/questions/17728710/coding-a-proof-for-potential-concurrency-issue) As to the specific example of this post: ``` public class MyClass{ private MyObject obj; // Initialize in thread A public MyClass(){ obj = new MyObject(); } // Called in thread B public void methodCalledByOtherThreads(){ obj.doStuff(); } } ``` If MyClass is initialized in Thread A, there is no guarantee that thread B will see this initialization (because the change might stay in the cache of the CPU that Thread A runs on and has not propagated into main memory). Just as @ZhongYu has pointed out, because the write and read happens at 2 independent threads, so there is no `happens-before(write, read)` relation. To fix this, as the original author has mentioned, we can declare private MyObject obj as volatile, which will ensure that the reference itself will be visible to other threads in timely manner (<https://www.logicbig.com/tutorials/core-java-tutorial/java-multi-threading/volatile-ref-object.html>) .
29,317
I have two network interfaces (one wired & one wireless). I have two internet accounts too (each 256 kBps; one from a modem that I use as wired connection & the other from a wireless network). Is it possible to connect to both networks and merge them and get twice the speed (512 kBps)? How? I'm using Ubuntu 10.04 (Lucid Lynx). Thanks
2012/01/17
[ "https://unix.stackexchange.com/questions/29317", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/11920/" ]
This is definitely feasible. Many of us were running mixed, load-balanced broadband configs for corporate years ago and they worked really well. Many probably still do! You can do it in a number of ways, including using `iptables` rules and/or `iproute2` (`ip(8)` command) to setup policy routing. The load balancing is not done at the packet level, but at the *connection* level. That is, all packets of a connection go out of one interface. Which interface this is depends on the routing policy. Without the co-operation of your the first routers just beyond your own infrastructure, this is the only way you can do it. Remote computers have no way to tell that your two IP addresses actually belong to the same computer. In TCP, a connection is uniquely identified by a 4-tuple (Remote-IP, Remote-Port, Local-IP, Local-Port). If you send packets from different IPs, the remote server thinks they belong to two different connections and gets hopelessly confused. Obviously, this sort of thing makes more sense in a corporate environment, or one with lots of users sharing a single connection. At work, we were combining a 256 kbps ADSL line with a 512 kbps cable line (yes, back then) and the whole thing worked remarkably well, with the added benefit of high availability. For some actual practical help, [here's one way of doing it with `iproute2`](http://www.debian-administration.org/articles/377). It's meant for Debian, but it works on Ubuntu too, of course.
Propably yes. My rough idea is to implement an outgoing load-balancer (via LVS) using a virtual IP that you could use as default-gateway. It is propably much more complicated than that and might involve putting up squid or something alike.
50,717,476
Fiddle: <http://sqlfiddle.com/#!18/5d05a/3> I have tables: ``` CREATE TABLE Table1( Date Date, Figure int ); INSERT INTO Table1 (Date, Figure) VALUES ('06-06-18','25'), ('05-12-18','30'), ('05-27-17','30'); ``` I am using this query to return the previous months data ``` DECLARE @PrevMonth int = MONTH(getdate()) -1, @Year int = YEAR(getdate()) SELECT @Year AS [Year], @PrevMonth AS [Month], Figure FROM Table1 WHERE MONTH([Date]) = @PrevMonth AND YEAR([Date]) = @Year ``` Which returns: ``` | Year | Month | Figure | |------|-------|--------| | 2018 | 5 | 30 | ``` However, this wont work once i hit Jan of a new year. In Jan of that new year i would be looking for December of the previous year. Can anyone advise me on a better method to use which would cover Jan in a new year. Thanks
2018/06/06
[ "https://Stackoverflow.com/questions/50717476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8412784/" ]
Querying the month and year parts of a query is a great way to slow it down. You're far better off with the date manipulation on the input parameter (in this case `GETDATE()`) not the column: ``` SELECT * FROM Table1 WHERE [Date] >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1,0) AND [date] < DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()),0); ```
Don't use functions on your table's columnns (it makes them non-SARGable and can't use indexes properly). You can use a good date filter instead. ``` DECLARE @StartDate DATE = DATEADD(DAY, 1,EOMONTH(GETDATE(), - 2)) DECLARE @EndDate DATE = DATEADD(DAY, 1,EOMONTH(GETDATE(), -1)) SELECT Figure FROM Table1 WHERE [Date] >= @StartDate AND [Date] < @EndDate ```
14,320,215
I was wondering if there is a way to create a black transparent overlay to basically cover the entire contents of the webpage? ``` <body> <div class="main-container"> <!--many more divs here to create webpage--> </div> </body> ```
2013/01/14
[ "https://Stackoverflow.com/questions/14320215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1316524/" ]
use this css on a div to create a black transparent overlay: ``` #overlay { width: 100%; height: 100%; background: rgba(0,0,0,0.6); position: fixed; top:0; left: 0; } ```
This might be what you are looking for: <http://malsup.com/jquery/block/>
14,320,215
I was wondering if there is a way to create a black transparent overlay to basically cover the entire contents of the webpage? ``` <body> <div class="main-container"> <!--many more divs here to create webpage--> </div> </body> ```
2013/01/14
[ "https://Stackoverflow.com/questions/14320215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1316524/" ]
use this css on a div to create a black transparent overlay: ``` #overlay { width: 100%; height: 100%; background: rgba(0,0,0,0.6); position: fixed; top:0; left: 0; } ```
The very basic overlay can be made using position absolute: ``` .overlay { position: absolute; top: 0; left: 0; right: 0; bottom: 0; opacity: .6; background-color: #000; } ``` <http://jsfiddle.net/dfsq/4Mn7Q/> UPD. As GSP pointed in comment this is not optimal solution when window height is bigger then a viewport. In this case body `{position: relative;}` should be used as well.
14,320,215
I was wondering if there is a way to create a black transparent overlay to basically cover the entire contents of the webpage? ``` <body> <div class="main-container"> <!--many more divs here to create webpage--> </div> </body> ```
2013/01/14
[ "https://Stackoverflow.com/questions/14320215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1316524/" ]
The very basic overlay can be made using position absolute: ``` .overlay { position: absolute; top: 0; left: 0; right: 0; bottom: 0; opacity: .6; background-color: #000; } ``` <http://jsfiddle.net/dfsq/4Mn7Q/> UPD. As GSP pointed in comment this is not optimal solution when window height is bigger then a viewport. In this case body `{position: relative;}` should be used as well.
This might be what you are looking for: <http://malsup.com/jquery/block/>
2,349,006
$A$ be $3\times3$ matrix with $\operatorname{trace}(A)=3$ and $\det(A)=2$. If $1$ is an eigenvalue of $A$ find eigenvalues for matrix $A^2-2I$? In this question I got eigenvalues of $A=1,1+i,1-i$ . I was thinking to change $\lambda$ to $\lambda^2-2$ in characteristic equation of $A$ to get eigenvalues of required matrix. I m getting characteristic equation $x^6-9x^4+28x^2-30=0$. Let $x=\lambda$. Can anyone tell me why I m wrong? I m not getting results.
2017/07/06
[ "https://math.stackexchange.com/questions/2349006", "https://math.stackexchange.com", "https://math.stackexchange.com/users/453977/" ]
If $p(x)$ is a polynomial, the eigenvalues of $p(A)$ are the numbers $p(\lambda)$ for each eigenvalue $\lambda$ of $A$. What you are doing is instead taking the polynomial $f(p(x))$ where $f(x)$ is the characteristic polynomial of $A$, which is a totally different operation. The roots of $f(p(x))$ are numbers $a$ such that $p(a)$ is an eigenvalue of $A$, not numbers of the form $p(\lambda)$ such that $\lambda$ is an eigenvalue of $A$.
$A = P\pmatrix {1\\&1+i\\&&1-i}P^{-1}\\ A^2 = PDP^{-1}PDP^{-1} = PD^2P^{-1} = P\pmatrix {1\\&2i\\&&-2i}P^{-1}\\ A^2-2I = PD^2P^{-1} - 2PIP^{-1} = P(D^2-2I)P^{-1}\\ A^2-2I = P\pmatrix {-1\\&-2+2i\\&&-2-2i}P^{-1}$
38,014,675
I'm trying to modify a minecraft mod (gravisuite) that puts "Gravitation Engine OFF/ON" whenever I press F, however I want to change this string, I started with replacing "Gravitation Engine OFF" with "Gravitation Engine Turned OFF" by using a hex editor but the file was no longer valid afterwards :/ I tried to use tools like jbe and cjbe and rej and that string is in the constant pool but it will only let me delete it... Is there any way to change a string in a compiled java class without destroying it? Thanks
2016/06/24
[ "https://Stackoverflow.com/questions/38014675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4931748/" ]
I compiled the same class twice with a minor tweak, firstly with "foo" and then with "foo-bar" ``` public class HelloWorld { public static final String HELLO = "foo-bar"; } ``` With "foo" ``` 000000b0 74 01 00 **03** 66 6f 6f 00 21 00 02 00 03 00 00 00 |t...foo.!.......| 000000c0 01 00 19 00 04 00 05 00 01 00 06 00 00 00 02 00 |................| 000000d0 07 00 01 00 01 00 08 00 09 00 01 00 0a 00 00 00 |................| 000000e0 1d 00 01 00 01 00 00 00 05 2a b7 00 01 b1 00 00 |.........*......| 000000f0 00 01 00 0b 00 00 00 06 00 01 00 00 00 01 00 01 |................| 00000100 00 0c 00 00 00 02 00 0d |........| ``` With "foo-bar" ``` 000000b0 74 01 00 **07** 66 6f 6f 2d 62 61 72 00 21 00 02 00 |t...foo-bar.!...| 000000c0 03 00 00 00 01 00 19 00 04 00 05 00 01 00 06 00 |................| 000000d0 00 00 02 00 07 00 01 00 01 00 08 00 09 00 01 00 |................| 000000e0 0a 00 00 00 1d 00 01 00 01 00 00 00 05 2a b7 00 |.............*..| 000000f0 01 b1 00 00 00 01 00 0b 00 00 00 06 00 01 00 00 |................| 00000100 00 01 00 01 00 0c 00 00 00 02 00 0d |............| ``` It seems that the length is also encoded in the structure. Note the 3 and the 7... There is [more information on this structure](https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html) And with a String of 300 characters the preceding two bytes were 01 2c. So given "Gravitation Engine Turned OFF" is 29 characters long, I'd make sure you change the byte immediately before the string to 1D, it should currently be 19 (25 characters for "Gravitation Engine OFF/ON")
A jar file is a zip file of classes, I guess you've figured that out already. Your best best is to load up a a java IDE with a decompiler addon (pretty sure Intellij has this built in). Once you've decompiled you can change the generated source and recompile it. This isn't trivial java stuff, but it's not so complicated either. If you've done some java project development before it's not so hard.
38,014,675
I'm trying to modify a minecraft mod (gravisuite) that puts "Gravitation Engine OFF/ON" whenever I press F, however I want to change this string, I started with replacing "Gravitation Engine OFF" with "Gravitation Engine Turned OFF" by using a hex editor but the file was no longer valid afterwards :/ I tried to use tools like jbe and cjbe and rej and that string is in the constant pool but it will only let me delete it... Is there any way to change a string in a compiled java class without destroying it? Thanks
2016/06/24
[ "https://Stackoverflow.com/questions/38014675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4931748/" ]
I compiled the same class twice with a minor tweak, firstly with "foo" and then with "foo-bar" ``` public class HelloWorld { public static final String HELLO = "foo-bar"; } ``` With "foo" ``` 000000b0 74 01 00 **03** 66 6f 6f 00 21 00 02 00 03 00 00 00 |t...foo.!.......| 000000c0 01 00 19 00 04 00 05 00 01 00 06 00 00 00 02 00 |................| 000000d0 07 00 01 00 01 00 08 00 09 00 01 00 0a 00 00 00 |................| 000000e0 1d 00 01 00 01 00 00 00 05 2a b7 00 01 b1 00 00 |.........*......| 000000f0 00 01 00 0b 00 00 00 06 00 01 00 00 00 01 00 01 |................| 00000100 00 0c 00 00 00 02 00 0d |........| ``` With "foo-bar" ``` 000000b0 74 01 00 **07** 66 6f 6f 2d 62 61 72 00 21 00 02 00 |t...foo-bar.!...| 000000c0 03 00 00 00 01 00 19 00 04 00 05 00 01 00 06 00 |................| 000000d0 00 00 02 00 07 00 01 00 01 00 08 00 09 00 01 00 |................| 000000e0 0a 00 00 00 1d 00 01 00 01 00 00 00 05 2a b7 00 |.............*..| 000000f0 01 b1 00 00 00 01 00 0b 00 00 00 06 00 01 00 00 |................| 00000100 00 01 00 01 00 0c 00 00 00 02 00 0d |............| ``` It seems that the length is also encoded in the structure. Note the 3 and the 7... There is [more information on this structure](https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html) And with a String of 300 characters the preceding two bytes were 01 2c. So given "Gravitation Engine Turned OFF" is 29 characters long, I'd make sure you change the byte immediately before the string to 1D, it should currently be 19 (25 characters for "Gravitation Engine OFF/ON")
There are checksums for the files: ``` Archive: dvt-utils.jar Length Method Size Ratio Date Time CRC-32 Name -------- ------ ------- ----- ---- ---- ------ ---- 332 Defl:N 226 32% 11.05.31 19:41 a745ad09 META-INF/MANIFEST.MF ```
38,014,675
I'm trying to modify a minecraft mod (gravisuite) that puts "Gravitation Engine OFF/ON" whenever I press F, however I want to change this string, I started with replacing "Gravitation Engine OFF" with "Gravitation Engine Turned OFF" by using a hex editor but the file was no longer valid afterwards :/ I tried to use tools like jbe and cjbe and rej and that string is in the constant pool but it will only let me delete it... Is there any way to change a string in a compiled java class without destroying it? Thanks
2016/06/24
[ "https://Stackoverflow.com/questions/38014675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4931748/" ]
You could have a look at the [Apache BCEL (ByteCode Engineering Library)](https://commons.apache.org/proper/commons-bcel/). It contains a remarkably powerful class called [`BCELifier`](https://commons.apache.org/proper/commons-bcel/apidocs/org/apache/bcel/util/BCELifier.html). It is a class that can take an input class, and, when executed, creates a class that, when compiled and executed, creates the input class. What? Yes. So imagine you have a class containing some strings, like this: ``` public class ClassContainingStrings { private String someString = "Some string"; public void call() { System.out.println("Printed string"); System.out.println(someString); } } ``` Now, you can compile this, to obtain the `ClassContainingStrings.class` file. This file can be fed into the `BCELifier`, like this: ``` import java.io.FileOutputStream; import org.apache.bcel.classfile.ClassParser; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.util.BCELifier; public class ChangeStringInClassFile { public static void main(String[] args) throws Exception { String classFileName = "ClassContainingStrings.class"; JavaClass c = new ClassParser(classFileName).parse(); BCELifier b = new BCELifier(c, new FileOutputStream("ClassContainingStringsCreator.java")); b.start(); } } ``` It will create a file called `ClassContainingStringsCreator.java`. For the given example, this will look like this: ``` import org.apache.bcel.generic.*; import org.apache.bcel.classfile.*; import org.apache.bcel.*; import java.io.*; public class ClassContainingStringsCreator implements Constants { private InstructionFactory _factory; private ConstantPoolGen _cp; private ClassGen _cg; public ClassContainingStringsCreator() { _cg = new ClassGen("ClassContainingStrings", "java.lang.Object", "ClassContainingStrings.java", ACC_PUBLIC | ACC_SUPER, new String[] { }); _cp = _cg.getConstantPool(); _factory = new InstructionFactory(_cg, _cp); } public void create(OutputStream out) throws IOException { createFields(); createMethod_0(); createMethod_1(); _cg.getJavaClass().dump(out); } private void createFields() { FieldGen field; field = new FieldGen(ACC_PRIVATE, Type.STRING, "someString", _cp); _cg.addField(field.getField()); } private void createMethod_0() { InstructionList il = new InstructionList(); MethodGen method = new MethodGen(ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] { }, "<init>", "ClassContainingStrings", il, _cp); InstructionHandle ih_0 = il.append(_factory.createLoad(Type.OBJECT, 0)); il.append(_factory.createInvoke("java.lang.Object", "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL)); InstructionHandle ih_4 = il.append(_factory.createLoad(Type.OBJECT, 0)); il.append(new PUSH(_cp, "Some string")); il.append(_factory.createFieldAccess("ClassContainingStrings", "someString", Type.STRING, Constants.PUTFIELD)); InstructionHandle ih_10 = il.append(_factory.createReturn(Type.VOID)); method.setMaxStack(); method.setMaxLocals(); _cg.addMethod(method.getMethod()); il.dispose(); } private void createMethod_1() { InstructionList il = new InstructionList(); MethodGen method = new MethodGen(ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] { }, "call", "ClassContainingStrings", il, _cp); InstructionHandle ih_0 = il.append(_factory.createFieldAccess("java.lang.System", "out", new ObjectType("java.io.PrintStream"), Constants.GETSTATIC)); il.append(new PUSH(_cp, "Printed string")); il.append(_factory.createInvoke("java.io.PrintStream", "println", Type.VOID, new Type[] { Type.STRING }, Constants.INVOKEVIRTUAL)); InstructionHandle ih_8 = il.append(_factory.createFieldAccess("java.lang.System", "out", new ObjectType("java.io.PrintStream"), Constants.GETSTATIC)); il.append(_factory.createLoad(Type.OBJECT, 0)); il.append(_factory.createFieldAccess("ClassContainingStrings", "someString", Type.STRING, Constants.GETFIELD)); il.append(_factory.createInvoke("java.io.PrintStream", "println", Type.VOID, new Type[] { Type.STRING }, Constants.INVOKEVIRTUAL)); InstructionHandle ih_18 = il.append(_factory.createReturn(Type.VOID)); method.setMaxStack(); method.setMaxLocals(); _cg.addMethod(method.getMethod()); il.dispose(); } public static void main(String[] args) throws Exception { ClassContainingStringsCreator creator = new ClassContainingStringsCreator(); creator.create(new FileOutputStream("ClassContainingStrings.class")); } } ``` (yes, it looks horrible, but that should not matter too much). The important thing is that the strings from the original class, namely the string `"Some string"` and `"Printed string"` can be found in there. Now, you can change these strings, and then compile and execute this creator class. It will create a new `ClassContainingStrings.class`, with the modified strings.
A jar file is a zip file of classes, I guess you've figured that out already. Your best best is to load up a a java IDE with a decompiler addon (pretty sure Intellij has this built in). Once you've decompiled you can change the generated source and recompile it. This isn't trivial java stuff, but it's not so complicated either. If you've done some java project development before it's not so hard.
38,014,675
I'm trying to modify a minecraft mod (gravisuite) that puts "Gravitation Engine OFF/ON" whenever I press F, however I want to change this string, I started with replacing "Gravitation Engine OFF" with "Gravitation Engine Turned OFF" by using a hex editor but the file was no longer valid afterwards :/ I tried to use tools like jbe and cjbe and rej and that string is in the constant pool but it will only let me delete it... Is there any way to change a string in a compiled java class without destroying it? Thanks
2016/06/24
[ "https://Stackoverflow.com/questions/38014675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4931748/" ]
You could have a look at the [Apache BCEL (ByteCode Engineering Library)](https://commons.apache.org/proper/commons-bcel/). It contains a remarkably powerful class called [`BCELifier`](https://commons.apache.org/proper/commons-bcel/apidocs/org/apache/bcel/util/BCELifier.html). It is a class that can take an input class, and, when executed, creates a class that, when compiled and executed, creates the input class. What? Yes. So imagine you have a class containing some strings, like this: ``` public class ClassContainingStrings { private String someString = "Some string"; public void call() { System.out.println("Printed string"); System.out.println(someString); } } ``` Now, you can compile this, to obtain the `ClassContainingStrings.class` file. This file can be fed into the `BCELifier`, like this: ``` import java.io.FileOutputStream; import org.apache.bcel.classfile.ClassParser; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.util.BCELifier; public class ChangeStringInClassFile { public static void main(String[] args) throws Exception { String classFileName = "ClassContainingStrings.class"; JavaClass c = new ClassParser(classFileName).parse(); BCELifier b = new BCELifier(c, new FileOutputStream("ClassContainingStringsCreator.java")); b.start(); } } ``` It will create a file called `ClassContainingStringsCreator.java`. For the given example, this will look like this: ``` import org.apache.bcel.generic.*; import org.apache.bcel.classfile.*; import org.apache.bcel.*; import java.io.*; public class ClassContainingStringsCreator implements Constants { private InstructionFactory _factory; private ConstantPoolGen _cp; private ClassGen _cg; public ClassContainingStringsCreator() { _cg = new ClassGen("ClassContainingStrings", "java.lang.Object", "ClassContainingStrings.java", ACC_PUBLIC | ACC_SUPER, new String[] { }); _cp = _cg.getConstantPool(); _factory = new InstructionFactory(_cg, _cp); } public void create(OutputStream out) throws IOException { createFields(); createMethod_0(); createMethod_1(); _cg.getJavaClass().dump(out); } private void createFields() { FieldGen field; field = new FieldGen(ACC_PRIVATE, Type.STRING, "someString", _cp); _cg.addField(field.getField()); } private void createMethod_0() { InstructionList il = new InstructionList(); MethodGen method = new MethodGen(ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] { }, "<init>", "ClassContainingStrings", il, _cp); InstructionHandle ih_0 = il.append(_factory.createLoad(Type.OBJECT, 0)); il.append(_factory.createInvoke("java.lang.Object", "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL)); InstructionHandle ih_4 = il.append(_factory.createLoad(Type.OBJECT, 0)); il.append(new PUSH(_cp, "Some string")); il.append(_factory.createFieldAccess("ClassContainingStrings", "someString", Type.STRING, Constants.PUTFIELD)); InstructionHandle ih_10 = il.append(_factory.createReturn(Type.VOID)); method.setMaxStack(); method.setMaxLocals(); _cg.addMethod(method.getMethod()); il.dispose(); } private void createMethod_1() { InstructionList il = new InstructionList(); MethodGen method = new MethodGen(ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] { }, "call", "ClassContainingStrings", il, _cp); InstructionHandle ih_0 = il.append(_factory.createFieldAccess("java.lang.System", "out", new ObjectType("java.io.PrintStream"), Constants.GETSTATIC)); il.append(new PUSH(_cp, "Printed string")); il.append(_factory.createInvoke("java.io.PrintStream", "println", Type.VOID, new Type[] { Type.STRING }, Constants.INVOKEVIRTUAL)); InstructionHandle ih_8 = il.append(_factory.createFieldAccess("java.lang.System", "out", new ObjectType("java.io.PrintStream"), Constants.GETSTATIC)); il.append(_factory.createLoad(Type.OBJECT, 0)); il.append(_factory.createFieldAccess("ClassContainingStrings", "someString", Type.STRING, Constants.GETFIELD)); il.append(_factory.createInvoke("java.io.PrintStream", "println", Type.VOID, new Type[] { Type.STRING }, Constants.INVOKEVIRTUAL)); InstructionHandle ih_18 = il.append(_factory.createReturn(Type.VOID)); method.setMaxStack(); method.setMaxLocals(); _cg.addMethod(method.getMethod()); il.dispose(); } public static void main(String[] args) throws Exception { ClassContainingStringsCreator creator = new ClassContainingStringsCreator(); creator.create(new FileOutputStream("ClassContainingStrings.class")); } } ``` (yes, it looks horrible, but that should not matter too much). The important thing is that the strings from the original class, namely the string `"Some string"` and `"Printed string"` can be found in there. Now, you can change these strings, and then compile and execute this creator class. It will create a new `ClassContainingStrings.class`, with the modified strings.
There are checksums for the files: ``` Archive: dvt-utils.jar Length Method Size Ratio Date Time CRC-32 Name -------- ------ ------- ----- ---- ---- ------ ---- 332 Defl:N 226 32% 11.05.31 19:41 a745ad09 META-INF/MANIFEST.MF ```
644,043
I was sifting through some stuff I got from a friend whose uncle was a professor of electrical engineering and found a few of these 2.54 mm pitch prototyping cables (commonly known as 'Dupont' cables) which are female-to-female but have a removable male pin. I've looked for variations of the cable name with the word 'removable' but have had no luck. I can find plenty of male-to-male cables but I believe all those male pins are part of the crimped connector and not removable, but I may be wrong. I can probably get regular female-to-female cables and get the pins separately as well. How can I find and purchase either the female-to-female cables with the detachable pins, or the detachable pins alone? [![cable with pin in](https://i.stack.imgur.com/l4Rct.jpg)](https://i.stack.imgur.com/l4Rct.jpg) [![cable with pin out](https://i.stack.imgur.com/22Z0I.jpg)](https://i.stack.imgur.com/22Z0I.jpg)
2022/11/26
[ "https://electronics.stackexchange.com/questions/644043", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/10065/" ]
I believe this is a female single-pin connector along with a single 25 mil square pin, probably taken out of a pin header like this one: [![enter image description here](https://i.stack.imgur.com/RDACD.png)](https://i.stack.imgur.com/RDACD.png) ([image source](https://www.digikey.com/en/products/detail/harwin-inc/M20-9990345/3728227), just a random part on digikey) They don't come out easily, but with pliers and a bit of force you can pull the individual pins out. As an aside, I'm not sure why people call these Dupont connectors. As far as I can determine, Dupont never actually made them. The largest manufacturer of them today is probably either Amphenol, TE Connectivity, or maybe Molex.
I suspect that the pin has broken off the rest of the contact inside the housing - I haven't seen that sort of contact with an intentionally-removable pin. The contacts for those plastic housings should be readily available from anyone selling the housings. There will be both male and female insertable contacts - you crimp the contact on the wire before inserting it in the connector housing. Connector housings, both single and multi-pin, and matching contacts, should be available from electronic distributors like Digikey or Mouser (in US and Canada - other companies elsewhere). There are many variations between makers - don't use company A's contacts in company B's housings.
38,714,238
As a part of learning process, I am roaming around angular js routing concepts. For this, I created one inner folder inside app with two sample test html pages .. When i run the app it should load first page from that folder but it does not not happening .. I am not sure where i have done wrong in this code... I am getting error like this **'angular.js:4640Uncaught Error: [$injector:modulerr]'** Below is my controller code ``` var myApp = angular.module('myApp', ['ngRoute']); myApp.config(function ($routeProvider) { $routeProvider .when('/', { templateUrl: 'Pages/main.html', controller: 'mainController' }) .when('/second', { templateUrl: 'Pages/second.html', controller: 'secondController' }) }); myApp.controller('mainController', ['$scope','$log', function($scope,$log) { }]); myApp.controller('secondController', ['$scope','$log', function($scope,$log) { }]); ``` and html code goes here ``` <!DOCTYPE html> <html lang="en-us" ng-app="myApp"> <head> <title>Learn and Understand AngularJS</title> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <meta charset="UTF-8"> <!-- load bootstrap and fontawesome via CDN --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <style> html, body, input, select, textarea { font-size: 1.05em; } </style> <!-- load angular via CDN --> <script src="https://code.angularjs.org/1.5.8/angular.min.js"></script> <script src="https://code.angularjs.org/1.5.8/angular-route.min.js"></script> <script src="app.js"></script> </head> <body> <header> <nav class="navbar navbar-default"> <div class="container"> <div class="navbar-header"> <a class="navbar-brand" href="/">AngularJS</a> </div> <ul class="nav navbar-nav navbar-right"> <li><a href="#"><i class="fa fa-home"></i>Home</a></li> <li><a href="#/second"><i></i>second</a></li> </ul> </div> </nav> </header> <div class="container"> <div ng-view></div> </div> </body> </html> ``` and for main.html ``` <h1>this is main page</h1> ``` and for second.html ``` <h1>this is second page</h1> ``` Would any one please help on this query, many thanks in advance..
2016/08/02
[ "https://Stackoverflow.com/questions/38714238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/899271/" ]
`BrowserDomAdapter` is not supposed to be used. It's for Angular internal use only. I assume you want to query elements passed as children because you use `ngAfterContentInit`: ```ts @Component({ ... template: ` ... <div #wrapper> <ng-content></ng-content> </div> ... ` }) export class MyComponent { @ViewChild('wrapper') wrapper:ElementRef; ngAfterContentInit(){ this.lightboxImages(); } lightboxImages(){ let images = this.wrapper.nativeElement.querySelector('img','.post-body'); console.log(images); } } ```
> > this.containerBlock.nativeElement.getElementsByTagName("img") > > > Where containerBlock is template reference. This will return all the img tag inside div with template reference containerBlock.
1,435,766
Here is a particular scenario that I have been unclear about (in terms of scope) for a long time. consider the code ``` #include <stdio.h> typedef struct _t_t{ int x; int y; } t_t; typedef struct _s_t{ int a; int b; t_t t; }s_t; void test(s_t & s){ t_t x = {502, 100}; s.t = x; } int main(){ s_t s; test(s); printf("value is %d, %d\n", s.t.x, s.t.y); return 0; } ``` the output is ``` value is 502, 100 ``` What is a bit confusing to me is the following. The declaration ``` t_t x ``` is declared in the scope of the function test. So from what I have read about C programming, it should be garbage out of this scope. Yet it returns a correct result. Is it because the "=" on the line s.t = x; copies the values of x into s.t? edit--- after some experimentation ``` #include <stdio.h> typedef struct _t_t{ int x; int y; } t_t; typedef struct _s_t{ int a; int b; t_t t; }s_t; void test(s_t & s){ t_t x = {502, 100}; t_t * pt = &(s.t); pt = &x; } int main(){ s_t s; test(s); printf("value is %d, %d\n", s.t.x, s.t.y); return 0; } ``` actually outputs ``` value is 134513915, 7446516 ``` as expected.
2009/09/16
[ "https://Stackoverflow.com/questions/1435766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/177931/" ]
> > Is it because the "=" on the line s.t = x; copies the values of x into s.t? > > > Yes. By the way, this is C++. You've passed the "s" local to main as a reference to the function, which modifies it. Because it's a reference, and not a copy, it affects the caller's "s".
You're right, the line ``` s.t = x; ``` will copy the values over.
1,435,766
Here is a particular scenario that I have been unclear about (in terms of scope) for a long time. consider the code ``` #include <stdio.h> typedef struct _t_t{ int x; int y; } t_t; typedef struct _s_t{ int a; int b; t_t t; }s_t; void test(s_t & s){ t_t x = {502, 100}; s.t = x; } int main(){ s_t s; test(s); printf("value is %d, %d\n", s.t.x, s.t.y); return 0; } ``` the output is ``` value is 502, 100 ``` What is a bit confusing to me is the following. The declaration ``` t_t x ``` is declared in the scope of the function test. So from what I have read about C programming, it should be garbage out of this scope. Yet it returns a correct result. Is it because the "=" on the line s.t = x; copies the values of x into s.t? edit--- after some experimentation ``` #include <stdio.h> typedef struct _t_t{ int x; int y; } t_t; typedef struct _s_t{ int a; int b; t_t t; }s_t; void test(s_t & s){ t_t x = {502, 100}; t_t * pt = &(s.t); pt = &x; } int main(){ s_t s; test(s); printf("value is %d, %d\n", s.t.x, s.t.y); return 0; } ``` actually outputs ``` value is 134513915, 7446516 ``` as expected.
2009/09/16
[ "https://Stackoverflow.com/questions/1435766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/177931/" ]
> > Is it because the "=" on the line s.t = x; copies the values of x into s.t? > > > Yes. By the way, this is C++. You've passed the "s" local to main as a reference to the function, which modifies it. Because it's a reference, and not a copy, it affects the caller's "s".
> > > ``` > t_t x = {502, 100}; > s.t = x; > > ``` > > **In your first test**, you're instructing the compiler to *copy* the value of `x` into `s.t` - this works as expected. The local variable `x` goes out of scope, but is never referenced outside of the function - the data it initially contained is copied into the `t` member of `main()`'s local variable `s`. It would be effectively the same if you instead wrote: ``` t_t x = {502, 100}; s.t.x = x.x; s.t.y = x.y; ``` **In your second test**, you assign a pointer to another pointer, both of which are declared as local variables. This does nothing useful - the value in `s.t` remains uninitialized. I've annotated the code to help you follow it: ``` t_t x = {502, 100}; // local variable x initialized with 502, 100 t_t * pt = &(s.t); // local variable pt initialized with ADDRESS OF s.t pt = &x; // local variable pt re-assigned to hold address of local variable x // local variables go out of scope, output parameter s remains unmodified ```
1,435,766
Here is a particular scenario that I have been unclear about (in terms of scope) for a long time. consider the code ``` #include <stdio.h> typedef struct _t_t{ int x; int y; } t_t; typedef struct _s_t{ int a; int b; t_t t; }s_t; void test(s_t & s){ t_t x = {502, 100}; s.t = x; } int main(){ s_t s; test(s); printf("value is %d, %d\n", s.t.x, s.t.y); return 0; } ``` the output is ``` value is 502, 100 ``` What is a bit confusing to me is the following. The declaration ``` t_t x ``` is declared in the scope of the function test. So from what I have read about C programming, it should be garbage out of this scope. Yet it returns a correct result. Is it because the "=" on the line s.t = x; copies the values of x into s.t? edit--- after some experimentation ``` #include <stdio.h> typedef struct _t_t{ int x; int y; } t_t; typedef struct _s_t{ int a; int b; t_t t; }s_t; void test(s_t & s){ t_t x = {502, 100}; t_t * pt = &(s.t); pt = &x; } int main(){ s_t s; test(s); printf("value is %d, %d\n", s.t.x, s.t.y); return 0; } ``` actually outputs ``` value is 134513915, 7446516 ``` as expected.
2009/09/16
[ "https://Stackoverflow.com/questions/1435766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/177931/" ]
> > Is it because the "=" on the line s.t = x; copies the values of x into s.t? > > > Yes. By the way, this is C++. You've passed the "s" local to main as a reference to the function, which modifies it. Because it's a reference, and not a copy, it affects the caller's "s".
Read This : [Default copy-constructors and assignment operators](http://www.uow.edu.au/~lukes/TEXTBOOK/notes-cpp/oop-condestructors/copyconstructors.html) By not providing an assignment operator, the struct \_s\_t will do a shallow-copy of all its members when it is assigned. Because you are storing everything in \_t\_t by value, all of the data is copied by value. The problem you are describing is when \_t\_t holds a pointer to the data. in the case: ``` typedef struct _s_t{ int a; int b; t_t* t; }s_t; void test(s_t & s){ t_t x = {502, 100}; s.t = &x; } ``` This would cause a problem, as t\_t would be destructed at the end of test() at which point that pointer would be invalid. ETA: Because you added more to the question... ``` void test(s_t & s){ t_t x = {502, 100}; t_t * pt = &(s.t); pt = &x; } ``` You've created a different problem here. What has happened there is you have created a pointer to the address of s.t, which is fine. However you have then reassigned that pointer to point to x (this assignment, did nothing to s.t, you are just changing what the pointer pt points to) The reason the output is 'as expected' is because you are just reading the uninitialised state of the struct.
1,435,766
Here is a particular scenario that I have been unclear about (in terms of scope) for a long time. consider the code ``` #include <stdio.h> typedef struct _t_t{ int x; int y; } t_t; typedef struct _s_t{ int a; int b; t_t t; }s_t; void test(s_t & s){ t_t x = {502, 100}; s.t = x; } int main(){ s_t s; test(s); printf("value is %d, %d\n", s.t.x, s.t.y); return 0; } ``` the output is ``` value is 502, 100 ``` What is a bit confusing to me is the following. The declaration ``` t_t x ``` is declared in the scope of the function test. So from what I have read about C programming, it should be garbage out of this scope. Yet it returns a correct result. Is it because the "=" on the line s.t = x; copies the values of x into s.t? edit--- after some experimentation ``` #include <stdio.h> typedef struct _t_t{ int x; int y; } t_t; typedef struct _s_t{ int a; int b; t_t t; }s_t; void test(s_t & s){ t_t x = {502, 100}; t_t * pt = &(s.t); pt = &x; } int main(){ s_t s; test(s); printf("value is %d, %d\n", s.t.x, s.t.y); return 0; } ``` actually outputs ``` value is 134513915, 7446516 ``` as expected.
2009/09/16
[ "https://Stackoverflow.com/questions/1435766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/177931/" ]
> > Is it because the "=" on the line s.t = x; copies the values of x into s.t? > > > Yes. By the way, this is C++. You've passed the "s" local to main as a reference to the function, which modifies it. Because it's a reference, and not a copy, it affects the caller's "s".
An asignment copies the value from one variable into another variable. So although the original local x is gone, you've got a copy in s. It would be quite different when you've just assigned a pointer to x: ``` typedef struct _s_t{ int a; int b; t_t* t; }s_t; void test(s_t & s){ t_t x = {502, 100}; s.t = &x; } ``` Then you would have a problem: you only have the address of x but x is gone. So you've effectively have a reference to an invalid memory location. The behaviour of this program would be undefined then.
1,435,766
Here is a particular scenario that I have been unclear about (in terms of scope) for a long time. consider the code ``` #include <stdio.h> typedef struct _t_t{ int x; int y; } t_t; typedef struct _s_t{ int a; int b; t_t t; }s_t; void test(s_t & s){ t_t x = {502, 100}; s.t = x; } int main(){ s_t s; test(s); printf("value is %d, %d\n", s.t.x, s.t.y); return 0; } ``` the output is ``` value is 502, 100 ``` What is a bit confusing to me is the following. The declaration ``` t_t x ``` is declared in the scope of the function test. So from what I have read about C programming, it should be garbage out of this scope. Yet it returns a correct result. Is it because the "=" on the line s.t = x; copies the values of x into s.t? edit--- after some experimentation ``` #include <stdio.h> typedef struct _t_t{ int x; int y; } t_t; typedef struct _s_t{ int a; int b; t_t t; }s_t; void test(s_t & s){ t_t x = {502, 100}; t_t * pt = &(s.t); pt = &x; } int main(){ s_t s; test(s); printf("value is %d, %d\n", s.t.x, s.t.y); return 0; } ``` actually outputs ``` value is 134513915, 7446516 ``` as expected.
2009/09/16
[ "https://Stackoverflow.com/questions/1435766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/177931/" ]
> > > ``` > t_t x = {502, 100}; > s.t = x; > > ``` > > **In your first test**, you're instructing the compiler to *copy* the value of `x` into `s.t` - this works as expected. The local variable `x` goes out of scope, but is never referenced outside of the function - the data it initially contained is copied into the `t` member of `main()`'s local variable `s`. It would be effectively the same if you instead wrote: ``` t_t x = {502, 100}; s.t.x = x.x; s.t.y = x.y; ``` **In your second test**, you assign a pointer to another pointer, both of which are declared as local variables. This does nothing useful - the value in `s.t` remains uninitialized. I've annotated the code to help you follow it: ``` t_t x = {502, 100}; // local variable x initialized with 502, 100 t_t * pt = &(s.t); // local variable pt initialized with ADDRESS OF s.t pt = &x; // local variable pt re-assigned to hold address of local variable x // local variables go out of scope, output parameter s remains unmodified ```
You're right, the line ``` s.t = x; ``` will copy the values over.
1,435,766
Here is a particular scenario that I have been unclear about (in terms of scope) for a long time. consider the code ``` #include <stdio.h> typedef struct _t_t{ int x; int y; } t_t; typedef struct _s_t{ int a; int b; t_t t; }s_t; void test(s_t & s){ t_t x = {502, 100}; s.t = x; } int main(){ s_t s; test(s); printf("value is %d, %d\n", s.t.x, s.t.y); return 0; } ``` the output is ``` value is 502, 100 ``` What is a bit confusing to me is the following. The declaration ``` t_t x ``` is declared in the scope of the function test. So from what I have read about C programming, it should be garbage out of this scope. Yet it returns a correct result. Is it because the "=" on the line s.t = x; copies the values of x into s.t? edit--- after some experimentation ``` #include <stdio.h> typedef struct _t_t{ int x; int y; } t_t; typedef struct _s_t{ int a; int b; t_t t; }s_t; void test(s_t & s){ t_t x = {502, 100}; t_t * pt = &(s.t); pt = &x; } int main(){ s_t s; test(s); printf("value is %d, %d\n", s.t.x, s.t.y); return 0; } ``` actually outputs ``` value is 134513915, 7446516 ``` as expected.
2009/09/16
[ "https://Stackoverflow.com/questions/1435766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/177931/" ]
Read This : [Default copy-constructors and assignment operators](http://www.uow.edu.au/~lukes/TEXTBOOK/notes-cpp/oop-condestructors/copyconstructors.html) By not providing an assignment operator, the struct \_s\_t will do a shallow-copy of all its members when it is assigned. Because you are storing everything in \_t\_t by value, all of the data is copied by value. The problem you are describing is when \_t\_t holds a pointer to the data. in the case: ``` typedef struct _s_t{ int a; int b; t_t* t; }s_t; void test(s_t & s){ t_t x = {502, 100}; s.t = &x; } ``` This would cause a problem, as t\_t would be destructed at the end of test() at which point that pointer would be invalid. ETA: Because you added more to the question... ``` void test(s_t & s){ t_t x = {502, 100}; t_t * pt = &(s.t); pt = &x; } ``` You've created a different problem here. What has happened there is you have created a pointer to the address of s.t, which is fine. However you have then reassigned that pointer to point to x (this assignment, did nothing to s.t, you are just changing what the pointer pt points to) The reason the output is 'as expected' is because you are just reading the uninitialised state of the struct.
You're right, the line ``` s.t = x; ``` will copy the values over.
1,435,766
Here is a particular scenario that I have been unclear about (in terms of scope) for a long time. consider the code ``` #include <stdio.h> typedef struct _t_t{ int x; int y; } t_t; typedef struct _s_t{ int a; int b; t_t t; }s_t; void test(s_t & s){ t_t x = {502, 100}; s.t = x; } int main(){ s_t s; test(s); printf("value is %d, %d\n", s.t.x, s.t.y); return 0; } ``` the output is ``` value is 502, 100 ``` What is a bit confusing to me is the following. The declaration ``` t_t x ``` is declared in the scope of the function test. So from what I have read about C programming, it should be garbage out of this scope. Yet it returns a correct result. Is it because the "=" on the line s.t = x; copies the values of x into s.t? edit--- after some experimentation ``` #include <stdio.h> typedef struct _t_t{ int x; int y; } t_t; typedef struct _s_t{ int a; int b; t_t t; }s_t; void test(s_t & s){ t_t x = {502, 100}; t_t * pt = &(s.t); pt = &x; } int main(){ s_t s; test(s); printf("value is %d, %d\n", s.t.x, s.t.y); return 0; } ``` actually outputs ``` value is 134513915, 7446516 ``` as expected.
2009/09/16
[ "https://Stackoverflow.com/questions/1435766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/177931/" ]
> > > ``` > t_t x = {502, 100}; > s.t = x; > > ``` > > **In your first test**, you're instructing the compiler to *copy* the value of `x` into `s.t` - this works as expected. The local variable `x` goes out of scope, but is never referenced outside of the function - the data it initially contained is copied into the `t` member of `main()`'s local variable `s`. It would be effectively the same if you instead wrote: ``` t_t x = {502, 100}; s.t.x = x.x; s.t.y = x.y; ``` **In your second test**, you assign a pointer to another pointer, both of which are declared as local variables. This does nothing useful - the value in `s.t` remains uninitialized. I've annotated the code to help you follow it: ``` t_t x = {502, 100}; // local variable x initialized with 502, 100 t_t * pt = &(s.t); // local variable pt initialized with ADDRESS OF s.t pt = &x; // local variable pt re-assigned to hold address of local variable x // local variables go out of scope, output parameter s remains unmodified ```
Read This : [Default copy-constructors and assignment operators](http://www.uow.edu.au/~lukes/TEXTBOOK/notes-cpp/oop-condestructors/copyconstructors.html) By not providing an assignment operator, the struct \_s\_t will do a shallow-copy of all its members when it is assigned. Because you are storing everything in \_t\_t by value, all of the data is copied by value. The problem you are describing is when \_t\_t holds a pointer to the data. in the case: ``` typedef struct _s_t{ int a; int b; t_t* t; }s_t; void test(s_t & s){ t_t x = {502, 100}; s.t = &x; } ``` This would cause a problem, as t\_t would be destructed at the end of test() at which point that pointer would be invalid. ETA: Because you added more to the question... ``` void test(s_t & s){ t_t x = {502, 100}; t_t * pt = &(s.t); pt = &x; } ``` You've created a different problem here. What has happened there is you have created a pointer to the address of s.t, which is fine. However you have then reassigned that pointer to point to x (this assignment, did nothing to s.t, you are just changing what the pointer pt points to) The reason the output is 'as expected' is because you are just reading the uninitialised state of the struct.
1,435,766
Here is a particular scenario that I have been unclear about (in terms of scope) for a long time. consider the code ``` #include <stdio.h> typedef struct _t_t{ int x; int y; } t_t; typedef struct _s_t{ int a; int b; t_t t; }s_t; void test(s_t & s){ t_t x = {502, 100}; s.t = x; } int main(){ s_t s; test(s); printf("value is %d, %d\n", s.t.x, s.t.y); return 0; } ``` the output is ``` value is 502, 100 ``` What is a bit confusing to me is the following. The declaration ``` t_t x ``` is declared in the scope of the function test. So from what I have read about C programming, it should be garbage out of this scope. Yet it returns a correct result. Is it because the "=" on the line s.t = x; copies the values of x into s.t? edit--- after some experimentation ``` #include <stdio.h> typedef struct _t_t{ int x; int y; } t_t; typedef struct _s_t{ int a; int b; t_t t; }s_t; void test(s_t & s){ t_t x = {502, 100}; t_t * pt = &(s.t); pt = &x; } int main(){ s_t s; test(s); printf("value is %d, %d\n", s.t.x, s.t.y); return 0; } ``` actually outputs ``` value is 134513915, 7446516 ``` as expected.
2009/09/16
[ "https://Stackoverflow.com/questions/1435766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/177931/" ]
> > > ``` > t_t x = {502, 100}; > s.t = x; > > ``` > > **In your first test**, you're instructing the compiler to *copy* the value of `x` into `s.t` - this works as expected. The local variable `x` goes out of scope, but is never referenced outside of the function - the data it initially contained is copied into the `t` member of `main()`'s local variable `s`. It would be effectively the same if you instead wrote: ``` t_t x = {502, 100}; s.t.x = x.x; s.t.y = x.y; ``` **In your second test**, you assign a pointer to another pointer, both of which are declared as local variables. This does nothing useful - the value in `s.t` remains uninitialized. I've annotated the code to help you follow it: ``` t_t x = {502, 100}; // local variable x initialized with 502, 100 t_t * pt = &(s.t); // local variable pt initialized with ADDRESS OF s.t pt = &x; // local variable pt re-assigned to hold address of local variable x // local variables go out of scope, output parameter s remains unmodified ```
An asignment copies the value from one variable into another variable. So although the original local x is gone, you've got a copy in s. It would be quite different when you've just assigned a pointer to x: ``` typedef struct _s_t{ int a; int b; t_t* t; }s_t; void test(s_t & s){ t_t x = {502, 100}; s.t = &x; } ``` Then you would have a problem: you only have the address of x but x is gone. So you've effectively have a reference to an invalid memory location. The behaviour of this program would be undefined then.
1,435,766
Here is a particular scenario that I have been unclear about (in terms of scope) for a long time. consider the code ``` #include <stdio.h> typedef struct _t_t{ int x; int y; } t_t; typedef struct _s_t{ int a; int b; t_t t; }s_t; void test(s_t & s){ t_t x = {502, 100}; s.t = x; } int main(){ s_t s; test(s); printf("value is %d, %d\n", s.t.x, s.t.y); return 0; } ``` the output is ``` value is 502, 100 ``` What is a bit confusing to me is the following. The declaration ``` t_t x ``` is declared in the scope of the function test. So from what I have read about C programming, it should be garbage out of this scope. Yet it returns a correct result. Is it because the "=" on the line s.t = x; copies the values of x into s.t? edit--- after some experimentation ``` #include <stdio.h> typedef struct _t_t{ int x; int y; } t_t; typedef struct _s_t{ int a; int b; t_t t; }s_t; void test(s_t & s){ t_t x = {502, 100}; t_t * pt = &(s.t); pt = &x; } int main(){ s_t s; test(s); printf("value is %d, %d\n", s.t.x, s.t.y); return 0; } ``` actually outputs ``` value is 134513915, 7446516 ``` as expected.
2009/09/16
[ "https://Stackoverflow.com/questions/1435766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/177931/" ]
Read This : [Default copy-constructors and assignment operators](http://www.uow.edu.au/~lukes/TEXTBOOK/notes-cpp/oop-condestructors/copyconstructors.html) By not providing an assignment operator, the struct \_s\_t will do a shallow-copy of all its members when it is assigned. Because you are storing everything in \_t\_t by value, all of the data is copied by value. The problem you are describing is when \_t\_t holds a pointer to the data. in the case: ``` typedef struct _s_t{ int a; int b; t_t* t; }s_t; void test(s_t & s){ t_t x = {502, 100}; s.t = &x; } ``` This would cause a problem, as t\_t would be destructed at the end of test() at which point that pointer would be invalid. ETA: Because you added more to the question... ``` void test(s_t & s){ t_t x = {502, 100}; t_t * pt = &(s.t); pt = &x; } ``` You've created a different problem here. What has happened there is you have created a pointer to the address of s.t, which is fine. However you have then reassigned that pointer to point to x (this assignment, did nothing to s.t, you are just changing what the pointer pt points to) The reason the output is 'as expected' is because you are just reading the uninitialised state of the struct.
An asignment copies the value from one variable into another variable. So although the original local x is gone, you've got a copy in s. It would be quite different when you've just assigned a pointer to x: ``` typedef struct _s_t{ int a; int b; t_t* t; }s_t; void test(s_t & s){ t_t x = {502, 100}; s.t = &x; } ``` Then you would have a problem: you only have the address of x but x is gone. So you've effectively have a reference to an invalid memory location. The behaviour of this program would be undefined then.
24,208,909
I have a runtime error that is happening at this line of code: ``` _searchresults = [_beerNames filteredArrayUsingPredicate:resultPredicate]; ``` serchresuls is a NSArray (nil objects) beerNames is a NSArray M (196 objects) and result predicate is a NScomparison predicate and I don't really understand what that means Here is my code for the result predicate ``` NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"name contains[c] %@", searchText]; ``` and searchText is a NSCF string, but it only fills up with one letter before the program crashes. The error it is giving me is this: NSCFString 0x8cbce80> valueForUndefinedKey:]: this class is not key value coding-compliant for the key name. Any ideas on what is going on?
2014/06/13
[ "https://Stackoverflow.com/questions/24208909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3307446/" ]
In order to turn on numbered-sections in latex output you need to use `numbersections` in your YAML block. If you ever want to "discover" things like this with pandoc just poke around the templates: ``` $ grep -i number default.latex $if(numbersections)$ $ grep -i number default.html* $ ``` As you can see this option does not work with html. Markdown and YAML I tested with: ``` --- title: Test numbersections: true --- # blah Text is here. ## Double Blah Twice the text is here ``` If you need it to work with more than beamer,latex,context,opendoc you will need to file a bug at github.
In order to show section number in the produced output pdf, there are two choices. ### In YAML front matter Add the following setting to begin of markdown file ``` --- numbersections: true --- ``` ### In command line We can also use the command option to generate pdf with numbered section. According to [Pandoc documentation](https://pandoc.org/MANUAL.html), the correct options is `--number-sections` or simply `-N`, ``` pandoc test.md -o test.pdf --number-sections # pandoc test.md -o test.pdf -N ```
21,049,090
I just installed Git + TortoiseGit, created a new local repository on my PC, added a file, and now I'm trying to commit it (I guess that's Commit -> "master"). However it says: "User name and email must be set before commit. Do you want to set these now?" Ehh, this is supposed to be a local repository. What does any email address have to do with this? Or am I misunderstanding the way Git works? Note that I'm not using GitHub or BitBucket or whatever. Just a local repository.
2014/01/10
[ "https://Stackoverflow.com/questions/21049090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1072269/" ]
The name and email are added to the commit by Git. It's not related to login credentials. It's useful to set at least the name, even if you don't want to set your email. If you want to leave them blank then you can enter these commands in a terminal: ``` git config --global user.name "" git config --global user.email "" ``` which should create a `~/.gitconfig` file at your system's $HOME, which will look like: ``` [user] name = email = ``` Alternatively, just create or edit your current ~/.gitconfig file to look like this.
In Git both a username and a mail address are associated to each commit, even for local repositories (In fact, in Git, all repositories are arguably local). It is, however, simply used as a label. It won't send you any mail. If you are concerned with your privacy, or you simply don't want to write your real e-mail for whatever reason, you can enter a fake one and it will cause no issues. In fact, this is precissely the approach recommended by GitHub for users with privacy concerns (<https://help.github.com/articles/keeping-your-email-address-private>).
29,682,561
I have an app in which markers can be added to the map using the Google Maps API, I'm trying to send a notification to all devices with the app installed when a new marker is added, this works for the device that is currently using the app but not my other device which does not have the app loaded, is there something else I have to do to register it with other devices? Here is the code for connecting to the server and adding the marker, which calls the showNotification method: ``` try { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://***.***.***.**/markerLocation/save.php"); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); is = entity.getContent(); String msg = "Data entered successfully"; //The method call that makes the alert notification ShowNotification(name); Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show(); } ``` and here is the code for creating the alert: ``` public void ShowNotification(String name) { // define sound URI, the sound to be played when there's a notification Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); // intent triggered, you can add other intent for other actions Intent intent = new Intent(GoogleMapsActivity.this, NotificationReceiver.class); PendingIntent pIntent = PendingIntent.getActivity(GoogleMapsActivity.this, 0, intent, 0); // this is it, we'll build the notification! // in the addAction method, if you don't want any icon, just set the first param to 0 Notification mNotification = new Notification.Builder(this) .setContentTitle(name) .setContentText(name + " has added a marker in your area") .setSmallIcon(R.drawable.ic_launcher) .setContentIntent(pIntent) .setSound(soundUri) .addAction(0, "View", pIntent) .addAction(0, "Remind", pIntent) .build(); NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); // If you want to hide the notification after it was selected, do the code below mNotification.flags |= Notification.FLAG_AUTO_CANCEL; notificationManager.notify(0, mNotification); } ```
2015/04/16
[ "https://Stackoverflow.com/questions/29682561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2757842/" ]
First you will need a Push service to warn other devices of your new marker, then you will need a BroadCastReceiver to receive the push message and emit the Notification on all devices that received it, I would love to explain this and write some example code for you but its widely explained in Android Docus so why reinvent the wheel? Look at this page, it has everything u need: [Google Cloud Messaging GCM](https://developer.android.com/google/gcm/index.html)
I think you are not grasping how the two notifications type functions. The way you would do this is by storing on your server the device id of all your users that have requested to receive the notifications. Then you initiate the notification for all devices from the server not from the app. Notification initiated from the app are only to display a message on the device outside of our app's UI Take a look at this: <https://developer.android.com/google/gcm/index.html>
29,682,561
I have an app in which markers can be added to the map using the Google Maps API, I'm trying to send a notification to all devices with the app installed when a new marker is added, this works for the device that is currently using the app but not my other device which does not have the app loaded, is there something else I have to do to register it with other devices? Here is the code for connecting to the server and adding the marker, which calls the showNotification method: ``` try { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://***.***.***.**/markerLocation/save.php"); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); is = entity.getContent(); String msg = "Data entered successfully"; //The method call that makes the alert notification ShowNotification(name); Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show(); } ``` and here is the code for creating the alert: ``` public void ShowNotification(String name) { // define sound URI, the sound to be played when there's a notification Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); // intent triggered, you can add other intent for other actions Intent intent = new Intent(GoogleMapsActivity.this, NotificationReceiver.class); PendingIntent pIntent = PendingIntent.getActivity(GoogleMapsActivity.this, 0, intent, 0); // this is it, we'll build the notification! // in the addAction method, if you don't want any icon, just set the first param to 0 Notification mNotification = new Notification.Builder(this) .setContentTitle(name) .setContentText(name + " has added a marker in your area") .setSmallIcon(R.drawable.ic_launcher) .setContentIntent(pIntent) .setSound(soundUri) .addAction(0, "View", pIntent) .addAction(0, "Remind", pIntent) .build(); NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); // If you want to hide the notification after it was selected, do the code below mNotification.flags |= Notification.FLAG_AUTO_CANCEL; notificationManager.notify(0, mNotification); } ```
2015/04/16
[ "https://Stackoverflow.com/questions/29682561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2757842/" ]
First you will need a Push service to warn other devices of your new marker, then you will need a BroadCastReceiver to receive the push message and emit the Notification on all devices that received it, I would love to explain this and write some example code for you but its widely explained in Android Docus so why reinvent the wheel? Look at this page, it has everything u need: [Google Cloud Messaging GCM](https://developer.android.com/google/gcm/index.html)
What you need is some kind of support for push notifications, an obvious choice for Android is Google Cloud Messaging (GCM). Since you have a server available, you could tailor the server-side yourself for managing which devices that receive the notifications (plenty of tutorials out there). If you are in a hurry and just want to get stuff working, you can use parse.com. They allow you to send push messages to 1 mil unique devices (through GCM) for free. The upside here is that they make it easier to setup and filter which devices that should receive the notifications.
5,400,733
I've been building a static library to share between multiple iOS projects, and I want to use gcov (or any code coverage analysis tool) to tell me where I'm missing my tests. However, when I enable gcov by following these directions: <http://supermegaultragroovy.com/blog/2005/11/03/unit-testing-and-code-coverage-with-xcode/> I get this error from Libtool: > > > ``` > /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/libtool: can't locate file for: -lgcov > /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/libtool: file: -lgcov is not an object file (not allowed in a library) > > ``` > > For some reason XCode4 can't find the libgcov.a file. It is in many places on my system but for some reason it can't be found. I'm fairly new to XCode, and gcc based programming in general, so I'm not sure how I can fix this, my guess is that I just have to tell it specifically where to find libgcov.a but I'm not sure how to go about that.
2011/03/23
[ "https://Stackoverflow.com/questions/5400733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16445/" ]
Looks like I found a solution. Crazy XCode seems to treat static libraries completely different when invoking gcc. And I thought MSBuild was a build system from hell... it's a snap and at least there are books about it. Anyway, here's how you do it: Add `$(PLATFORM_DEVELOPER_USR_DIR)/lib` to your "Library Search Paths" build setting for your static library and tick the "Recursive" check box. Works for me, let me know if it works for you.
This may help in solving your issue, have a look in to it [GTM](http://code.google.com/p/google-toolbox-for-mac/wiki/SnowLeopardGCov)
12,071,679
I am trying to edit `SharedPreferences` of one app through another app, my code goes like this ``` try { Context plutoContext = getApplicationContext().createPackageContext("me.test",Context.MODE_WORLD_WRITEABLE); SharedPreferences plutoPreferences = PreferenceManager.getDefaultSharedPreferences(plutoContext); Editor plutoPrefEditor = plutoPreferences.edit(); plutoPrefEditor.putString("country", "India"); plutoPrefEditor.commit(); } ``` I am getting an error `E/SharedPreferencesImpl( 304): Couldn't create directory for SharedPreferences file /data/data/me.test/shared_prefs/me.test_preferences.xml` where `me.test` is my another project in me.test proj I can edit and retrieve `SharedPreferences` with no pain I am testing it on Nexus S android 4.0.4 (Samsung), can any one help me
2012/08/22
[ "https://Stackoverflow.com/questions/12071679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1501118/" ]
You need to add the permissions in your AndroidManifest.xml: ``` <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> ``` I have the same problem with you, and I solved it with the above solution.
In my case rebooting Samsung device solved same issue.
12,071,679
I am trying to edit `SharedPreferences` of one app through another app, my code goes like this ``` try { Context plutoContext = getApplicationContext().createPackageContext("me.test",Context.MODE_WORLD_WRITEABLE); SharedPreferences plutoPreferences = PreferenceManager.getDefaultSharedPreferences(plutoContext); Editor plutoPrefEditor = plutoPreferences.edit(); plutoPrefEditor.putString("country", "India"); plutoPrefEditor.commit(); } ``` I am getting an error `E/SharedPreferencesImpl( 304): Couldn't create directory for SharedPreferences file /data/data/me.test/shared_prefs/me.test_preferences.xml` where `me.test` is my another project in me.test proj I can edit and retrieve `SharedPreferences` with no pain I am testing it on Nexus S android 4.0.4 (Samsung), can any one help me
2012/08/22
[ "https://Stackoverflow.com/questions/12071679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1501118/" ]
You need to add the permissions in your AndroidManifest.xml: ``` <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> ``` I have the same problem with you, and I solved it with the above solution.
Just use a different package name in this app. That will create the preferences in a different directory.
12,071,679
I am trying to edit `SharedPreferences` of one app through another app, my code goes like this ``` try { Context plutoContext = getApplicationContext().createPackageContext("me.test",Context.MODE_WORLD_WRITEABLE); SharedPreferences plutoPreferences = PreferenceManager.getDefaultSharedPreferences(plutoContext); Editor plutoPrefEditor = plutoPreferences.edit(); plutoPrefEditor.putString("country", "India"); plutoPrefEditor.commit(); } ``` I am getting an error `E/SharedPreferencesImpl( 304): Couldn't create directory for SharedPreferences file /data/data/me.test/shared_prefs/me.test_preferences.xml` where `me.test` is my another project in me.test proj I can edit and retrieve `SharedPreferences` with no pain I am testing it on Nexus S android 4.0.4 (Samsung), can any one help me
2012/08/22
[ "https://Stackoverflow.com/questions/12071679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1501118/" ]
Just use a different package name in this app. That will create the preferences in a different directory.
If your first app wants to create a SharedPreference that can be read by another app, make sure you create the SharedPreference with the correct mode. Take a look at the [getSharedPreferences()](http://developer.android.com/reference/android/content/Context.html#getSharedPreferences%28java.lang.String,%20int%29) or the [PreferenceManager](http://developer.android.com/reference/android/preference/PreferenceManager.html) class for more details.
12,071,679
I am trying to edit `SharedPreferences` of one app through another app, my code goes like this ``` try { Context plutoContext = getApplicationContext().createPackageContext("me.test",Context.MODE_WORLD_WRITEABLE); SharedPreferences plutoPreferences = PreferenceManager.getDefaultSharedPreferences(plutoContext); Editor plutoPrefEditor = plutoPreferences.edit(); plutoPrefEditor.putString("country", "India"); plutoPrefEditor.commit(); } ``` I am getting an error `E/SharedPreferencesImpl( 304): Couldn't create directory for SharedPreferences file /data/data/me.test/shared_prefs/me.test_preferences.xml` where `me.test` is my another project in me.test proj I can edit and retrieve `SharedPreferences` with no pain I am testing it on Nexus S android 4.0.4 (Samsung), can any one help me
2012/08/22
[ "https://Stackoverflow.com/questions/12071679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1501118/" ]
By the way, (it's not related with the question, but any way) you wrongly use `createPackageContext()` method. You pass there `MODE_WORLD_WRITEABLE` flag which value is **2** and equals to `CONTEXT_IGNORE_SECURITY` flag, so this would be incorrectly interpreted by logic, IMHO.
In my case rebooting Samsung device solved same issue.
12,071,679
I am trying to edit `SharedPreferences` of one app through another app, my code goes like this ``` try { Context plutoContext = getApplicationContext().createPackageContext("me.test",Context.MODE_WORLD_WRITEABLE); SharedPreferences plutoPreferences = PreferenceManager.getDefaultSharedPreferences(plutoContext); Editor plutoPrefEditor = plutoPreferences.edit(); plutoPrefEditor.putString("country", "India"); plutoPrefEditor.commit(); } ``` I am getting an error `E/SharedPreferencesImpl( 304): Couldn't create directory for SharedPreferences file /data/data/me.test/shared_prefs/me.test_preferences.xml` where `me.test` is my another project in me.test proj I can edit and retrieve `SharedPreferences` with no pain I am testing it on Nexus S android 4.0.4 (Samsung), can any one help me
2012/08/22
[ "https://Stackoverflow.com/questions/12071679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1501118/" ]
By the way, (it's not related with the question, but any way) you wrongly use `createPackageContext()` method. You pass there `MODE_WORLD_WRITEABLE` flag which value is **2** and equals to `CONTEXT_IGNORE_SECURITY` flag, so this would be incorrectly interpreted by logic, IMHO.
If your first app wants to create a SharedPreference that can be read by another app, make sure you create the SharedPreference with the correct mode. Take a look at the [getSharedPreferences()](http://developer.android.com/reference/android/content/Context.html#getSharedPreferences%28java.lang.String,%20int%29) or the [PreferenceManager](http://developer.android.com/reference/android/preference/PreferenceManager.html) class for more details.
12,071,679
I am trying to edit `SharedPreferences` of one app through another app, my code goes like this ``` try { Context plutoContext = getApplicationContext().createPackageContext("me.test",Context.MODE_WORLD_WRITEABLE); SharedPreferences plutoPreferences = PreferenceManager.getDefaultSharedPreferences(plutoContext); Editor plutoPrefEditor = plutoPreferences.edit(); plutoPrefEditor.putString("country", "India"); plutoPrefEditor.commit(); } ``` I am getting an error `E/SharedPreferencesImpl( 304): Couldn't create directory for SharedPreferences file /data/data/me.test/shared_prefs/me.test_preferences.xml` where `me.test` is my another project in me.test proj I can edit and retrieve `SharedPreferences` with no pain I am testing it on Nexus S android 4.0.4 (Samsung), can any one help me
2012/08/22
[ "https://Stackoverflow.com/questions/12071679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1501118/" ]
Just use a different package name in this app. That will create the preferences in a different directory.
Issue - "Android : Couldn't create directory for SharedPreferences file" will come when you are already created default shared preference in project. So, one shared preference is exist and again, you are adding with same name default preference. Solution - Create only one default shared preference in app. If do you want to create more shared preference then create shared preference with some name. Note - Only one default shared preference in one app.
12,071,679
I am trying to edit `SharedPreferences` of one app through another app, my code goes like this ``` try { Context plutoContext = getApplicationContext().createPackageContext("me.test",Context.MODE_WORLD_WRITEABLE); SharedPreferences plutoPreferences = PreferenceManager.getDefaultSharedPreferences(plutoContext); Editor plutoPrefEditor = plutoPreferences.edit(); plutoPrefEditor.putString("country", "India"); plutoPrefEditor.commit(); } ``` I am getting an error `E/SharedPreferencesImpl( 304): Couldn't create directory for SharedPreferences file /data/data/me.test/shared_prefs/me.test_preferences.xml` where `me.test` is my another project in me.test proj I can edit and retrieve `SharedPreferences` with no pain I am testing it on Nexus S android 4.0.4 (Samsung), can any one help me
2012/08/22
[ "https://Stackoverflow.com/questions/12071679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1501118/" ]
Just use a different package name in this app. That will create the preferences in a different directory.
In my case rebooting Samsung device solved same issue.
12,071,679
I am trying to edit `SharedPreferences` of one app through another app, my code goes like this ``` try { Context plutoContext = getApplicationContext().createPackageContext("me.test",Context.MODE_WORLD_WRITEABLE); SharedPreferences plutoPreferences = PreferenceManager.getDefaultSharedPreferences(plutoContext); Editor plutoPrefEditor = plutoPreferences.edit(); plutoPrefEditor.putString("country", "India"); plutoPrefEditor.commit(); } ``` I am getting an error `E/SharedPreferencesImpl( 304): Couldn't create directory for SharedPreferences file /data/data/me.test/shared_prefs/me.test_preferences.xml` where `me.test` is my another project in me.test proj I can edit and retrieve `SharedPreferences` with no pain I am testing it on Nexus S android 4.0.4 (Samsung), can any one help me
2012/08/22
[ "https://Stackoverflow.com/questions/12071679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1501118/" ]
You need to add the permissions in your AndroidManifest.xml: ``` <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> ``` I have the same problem with you, and I solved it with the above solution.
Issue - "Android : Couldn't create directory for SharedPreferences file" will come when you are already created default shared preference in project. So, one shared preference is exist and again, you are adding with same name default preference. Solution - Create only one default shared preference in app. If do you want to create more shared preference then create shared preference with some name. Note - Only one default shared preference in one app.
12,071,679
I am trying to edit `SharedPreferences` of one app through another app, my code goes like this ``` try { Context plutoContext = getApplicationContext().createPackageContext("me.test",Context.MODE_WORLD_WRITEABLE); SharedPreferences plutoPreferences = PreferenceManager.getDefaultSharedPreferences(plutoContext); Editor plutoPrefEditor = plutoPreferences.edit(); plutoPrefEditor.putString("country", "India"); plutoPrefEditor.commit(); } ``` I am getting an error `E/SharedPreferencesImpl( 304): Couldn't create directory for SharedPreferences file /data/data/me.test/shared_prefs/me.test_preferences.xml` where `me.test` is my another project in me.test proj I can edit and retrieve `SharedPreferences` with no pain I am testing it on Nexus S android 4.0.4 (Samsung), can any one help me
2012/08/22
[ "https://Stackoverflow.com/questions/12071679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1501118/" ]
You need to add the permissions in your AndroidManifest.xml: ``` <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> ``` I have the same problem with you, and I solved it with the above solution.
By the way, (it's not related with the question, but any way) you wrongly use `createPackageContext()` method. You pass there `MODE_WORLD_WRITEABLE` flag which value is **2** and equals to `CONTEXT_IGNORE_SECURITY` flag, so this would be incorrectly interpreted by logic, IMHO.
12,071,679
I am trying to edit `SharedPreferences` of one app through another app, my code goes like this ``` try { Context plutoContext = getApplicationContext().createPackageContext("me.test",Context.MODE_WORLD_WRITEABLE); SharedPreferences plutoPreferences = PreferenceManager.getDefaultSharedPreferences(plutoContext); Editor plutoPrefEditor = plutoPreferences.edit(); plutoPrefEditor.putString("country", "India"); plutoPrefEditor.commit(); } ``` I am getting an error `E/SharedPreferencesImpl( 304): Couldn't create directory for SharedPreferences file /data/data/me.test/shared_prefs/me.test_preferences.xml` where `me.test` is my another project in me.test proj I can edit and retrieve `SharedPreferences` with no pain I am testing it on Nexus S android 4.0.4 (Samsung), can any one help me
2012/08/22
[ "https://Stackoverflow.com/questions/12071679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1501118/" ]
You need to add the permissions in your AndroidManifest.xml: ``` <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> ``` I have the same problem with you, and I solved it with the above solution.
If your first app wants to create a SharedPreference that can be read by another app, make sure you create the SharedPreference with the correct mode. Take a look at the [getSharedPreferences()](http://developer.android.com/reference/android/content/Context.html#getSharedPreferences%28java.lang.String,%20int%29) or the [PreferenceManager](http://developer.android.com/reference/android/preference/PreferenceManager.html) class for more details.
64,121,826
I have a table of accounts that contains an edit option. When the edit option is clicked, an account edit modal dialog is displayed. The user has the option to close or cancel the edit by clicking the "X" in the top right corner or clicking a Close button. When the modal closes there are state properties that i would like to clear, both dialog properties and parent component properties. The dialog properties are updated without any issues but i receive this error when the parent properties are attempted to be updated: > > Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state. > > > This is the parent component: ``` export class Accounts extends Component { constructor(props, context) { super(props); this.state = { loading: true, showEditUserModal: false, userId: null, redraw: false, } this.handleAccountEdit = this.handleAccountEdit.bind(this); } handleAccountEdit(cell, row, rowIndex) { this.setState({ userId: cell }, this.setState({ showEditUserModal: true })); } //This is parent function being called from dialog close Error occurs here handleAccountEditClose() { this.setState({ userId: null, showEditUserModal: false, redraw: true }); } render() { return ( <div className='container-fluid'> {this.state.showEditUserModal ? <AccountEditModal userId={this.state.userId} parentCloseAccountEditModal={() => this.handleAccountEditClose()}></AccountEditModal> </div> ) } ``` AccountEditModal: ``` export default class AccountEditModal extends React.Component { constructor(props, context) { super(props); this.state = { uId: null, userName: '', showModal: true, } } handleClose = (e) => { this.setState({ showModal: false, uId: null, userName: '' }); } render() { return ( <div > <Modal show={this.state.showModal} onHide={() => { this.handleClose(); this.props.parentCloseAccountEditModal() }} centered > <Modal.Header closeButton> <Modal.Title>Account Edit</Modal.Title> </Modal.Header> <Modal.Body> <div className="row"> <div className="row pad-top float-right"> <div className='col-md-2 my-auto'> <span id='btnCloseAccountEdit' onClick={() => { this.handleClose(); this.props.parentCloseAccountEditModal() }} className='btn btn-success'>Close</span> </div> </div> </div> </Modal.Body> </Modal> </div> ) } ``` How can i update the parent component properties without getting this error? The suggested solution does not call a parent component function. I changed the handleClose to a lambda in the AccountEditModal but still receive the same error.
2020/09/29
[ "https://Stackoverflow.com/questions/64121826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2370664/" ]
I am nit sure what you are doing different than I am but based on your code and explanation I created this demo application and it is working as expected without any errors. May be you might want to compare it to your application and check what is different in your app. Find working [codesandbox](https://codesandbox.io/s/fancy-wind-x3prr) here. **Accounts.js** ``` import React, { Component } from "react"; import { AccountEditModal } from "./AccountEditModal"; export class Accounts extends Component { constructor(props, context) { super(props); this.state = { loading: true, showEditUserModal: false, userId: null, redraw: false }; this.handleAccountEdit = this.handleAccountEdit.bind(this); } handleAccountEdit(cell) { this.setState({ userId: cell }, this.setState({ showEditUserModal: true })); } //This is parent function being called from dialog close Error occurs here handleAccountEditClose() { this.setState({ userId: null, showEditUserModal: false, redraw: true }); } render() { return ( <div className="container-fluid"> {this.state.showEditUserModal ? ( <AccountEditModal userId={this.state.userId} parentCloseAccountEditModal={() => this.handleAccountEditClose()} ></AccountEditModal> ) : ( <table> {this.props.users.map((uId) => { return ( <tr> <td> <button onClick={() => this.handleAccountEdit(uId)}> {uId} </button> </td> </tr> ); })} </table> )} </div> ); } } ``` **AccountEditModal.js** ``` import React, { Component } from "react"; import { Modal } from "react-bootstrap"; export class AccountEditModal extends Component { constructor(props, context) { super(props); this.state = { uId: null, userName: "", showModal: true }; } handleClose = (e) => { this.setState({ showModal: false, uId: null, userName: "" }); }; render() { return ( <div> <Modal show={this.state.showModal} onHide={() => { this.handleClose(); this.props.parentCloseAccountEditModal(); }} centered > <Modal.Header closeButton> <Modal.Title>Account Edit: {this.props.userId}</Modal.Title> </Modal.Header> <Modal.Body> <div className="row"> <div className="row pad-top float-right"> <div className="col-md-2 my-auto"> <span id="btnCloseAccountEdit" onClick={() => { this.handleClose(); this.props.parentCloseAccountEditModal(); }} className="btn btn-success" > Close </span> </div> </div> </div> </Modal.Body> </Modal> </div> ); } } ``` I have added dummy application data in **App.js**: ``` import React, { useState } from "react"; import { Accounts } from "./Accounts"; import "./styles.css"; export default function App() { const [users] = useState([ "User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10" ]); return ( <div className="App"> <h1>Hello CodeSandbox</h1> <Accounts users={users}></Accounts> </div> ); } ```
One easy way to reset your component is to manage it with a key. See: <https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key> More precisely: > > When a key changes, React will create a new component instance rather > than update the current one. > > > So following this, you could for example use a timecode so that every time you call this modal window a new instance is created with default values. Like this: ``` <AccountEditModal key={Date.now()} userId={this.state.userId} parentCloseAccountEditModal={() => this.handleAccountEditClose()}> </AccountEditModal> ``` Then you don't need this function and this call: `this.handleClose();` Simply call this one: `this.props.parentCloseAccountEditModal()` and next time you call the modal, you're going to have a new instance. For normal components, it may introduce non wanted behavior, but for a modal window it's usually exactly the intent: each time you close/open it, you want a reset state, and you're not going to change the props except by opening it - since it's modal and so prevents interactions with the parent.
25,038,980
i'm building a traffic schedule application using Neo4J, NodeJS and GTFS-data; currently, i'm trying to get things working for the traffic on a single day on the Berlin subway network. these are the grand totals i've collected so far: `10 routes 211 stops 4096 trips 83322 stoptimes` to put it simply, GTFS (General Transit Feed Specification) has the concept of a `stoptime` which denotes the event of a given train or bus stopping for passengers to board and alight. `stoptime`s happen on a `trip`, which is a series of `stoptimes`, they happen on a specific date and time, and they happen on a given `stop` for a given `route` (or 'line') in a transit network. so there's a lot of references here. the problem i'm running into is the amount of data and the time it takes to build the database. in order to speed up things, i've already (1) cut down the data to a single day, (2) deleted the database files and have the server create a fresh one (very effective!), (3) searched a lot to get better queries. alas, with the figures as given above, it still takes 30~50 minutes to get all the edges of the graph. these are the indexes i'm building: ``` CREATE CONSTRAINT ON (n:trip) ASSERT n.id IS UNIQUE; CREATE CONSTRAINT ON (n:stop) ASSERT n.id IS UNIQUE; CREATE CONSTRAINT ON (n:route) ASSERT n.id IS UNIQUE; CREATE CONSTRAINT ON (n:stoptime) ASSERT n.id IS UNIQUE; CREATE INDEX ON :trip(`route-id`); CREATE INDEX ON :stop(`name`); CREATE INDEX ON :stoptime(`trip-id`); CREATE INDEX ON :stoptime(`stop-id`); CREATE INDEX ON :route(`name`); ``` i'd guess the unique primary keys should be most important. and here are the queries that take up like 80% of the running time (with 10% that are unrelated to Neo4J, and 10% needed to feed the node data using plain HTTP post requests): ``` MATCH (trip:`trip`), (route:`route`) WHERE trip.`route-id` = route.id CREATE UNIQUE (trip)-[:`trip/route` {`~label`: 'trip/route'}]-(route); MATCH (stoptime:`stoptime`), (trip:`trip`) WHERE stoptime.`trip-id` = trip.id CREATE UNIQUE (trip)-[:`trip/stoptime` {`~label`: 'trip/stoptime'}]-(stoptime); MATCH (stoptime:`stoptime`), (stop:`stop`) WHERE stoptime.`stop-id` = stop.id CREATE UNIQUE (stop)-[:`stop/stoptime` {`~label`: 'stop/stoptime'}]-(stoptime); MATCH (a:stoptime), (b:stoptime) WHERE a.`trip-id` = b.`trip-id` AND ( a.idx + 1 = b.idx OR a.idx - 1 = b.idx ) CREATE UNIQUE (a)-[:linked]-(b); MATCH (stop1:stop)-->(a:stoptime)-[:next]->(b:stoptime)-->(stop2:stop) CREATE UNIQUE (stop1)-[:distance {`~label`: 'distance', value: 0}]-(stop2); ``` the first query is still in the range of some minutes which i find longish given that there are only thousands (not hundreds of thousands or millions) of `trips` in the database. the subsequent queries that involve `stoptime`s take several ten minutes each on my desktop machine. (i've also calculated whether the schedule really contains 83322 stoptimes each day, and yes, it's plausible: in Berlin, subway trains run on 10 lines for 20 hours a day with 6 or 12 trips per hour, and there are 173 subway stations: 10 lines x 2 directions x 17.3 stops per line x 20 hours x 9 trips per hour gives 62280, close enough. there *are* some faulty? / double / extra stop nodes in the data (211 stops instead of 173), but those are few.) frankly, **if i don't find a way to speed up things at least tenfold (rather more), it'll make little sense to use Neo4J for this project**. just in order to cover the single city of Berlin *many*, *many* more stoptimes have to be added, as the subway is just a tiny fraction of the overall public transport here (e.g. bus and tramway have like 170 routes with 7,000 stops, so expect around 7,000,000 stoptimes each day). **Update** the above edge creation queries, which i perform one by one, have now been running for over an hour and not yet finished, meaning that—if things scale in a linear fashion—the time needed to feed the Berlin public transport data for a single day would consume something like a week. therefore, the code currently performs *several* orders of magnitude too slow to be viable. **Update** @MichaelHunger's solution did work; see my response below.
2014/07/30
[ "https://Stackoverflow.com/questions/25038980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256361/" ]
I just imported 12M nodes and 12M rels into Neo4j in 10 minutes using LOAD CSV. You should see your issues when you run profiling on your queries in the shell. Prefix your query with `profile` and look a the profile output if it mentions to use the index or rather just label-scan. Do you use parameters for your insert queries? So that Neo4j can re-use built queries? For queries like this: ``` MATCH (trip:`trip`), (route:`route`) WHERE trip.`route-id` = route.id CREATE UNIQUE (trip)-[:`trip/route` {`~label`: 'trip/route'}]-(route); ``` It will very probably not use your index. Can you perhaps point to your datasource? We can convert it into CSV if it isn't and then import even more quickly. Perhaps we can create a graph gist for your model? I would rather use: ``` MATCH (route:`route`) MATCH (trip:`trip` {`route-id` = route.id) CREATE (trip)-[:`trip/route` {`~label`: 'trip/route'}]-(route); ``` For your initial import you also don't need create unique as you match every trip only once. And I'm not sure what your "~label" is good for? Similar for your other queries. As the data is public it would be cool to work together on this. Something I'd love to hear more about is how you plan do express your query use-cases. I had a really great discussion about timetables for public transport with training attendees last time in Leipzig. You can also email me on michael at neo4j.org Also perhaps you want to check out these links: ### Tramchester * <http://www.thoughtworks.com/de/insights/blog/transforming-travel-and-transport-industry-one-graph-time> * <http://de.slideshare.net/neo4j/graph-connect-v5> * <https://www.youtube.com/watch?v=AhvECxOhEX0> ### London Tube Graph * <http://blog.bruggen.com/2013/11/meet-this-tubular-graph.html> * <http://www.markhneedham.com/blog/2014/03/03/neo4j-2-1-0-m01-load-csv-with-rik-van-bruggens-tube-graph/> * <http://www.markhneedham.com/blog/2014/02/13/neo4j-value-in-relationships-but-value-in-nodes-too/>
**detailed solution** i'm happy to report that @MichaelHunger's solution works like a charm. i modified the edge-building queries from the question with the below shapes that keep to the suggested query outline: ``` MATCH (route:`route`) MATCH (trip:`trip` {`route-id`: route.id}) CREATE (trip)-[:`trip/route` {`~label`: 'trip/route'}]->(route) MATCH (trip:`trip`) MATCH (stoptime:`stoptime` {`trip-id`: trip.id}) CREATE (trip)-[:`trip/stoptime` {`~label`: 'trip/stoptime'}]->(stoptime) MATCH (stop:`stop`) MATCH (stoptime:`stoptime` {`stop-id`: stop.id}) CREATE (stop)-[:`stop/stoptime` {`~label`: 'stop/stoptime'}]->(stoptime) MATCH (a:stoptime) MATCH (b:stoptime {`trip-id`: a.`trip-id`, `idx`: a.idx + 1}) CREATE (a)-[:linked {`~label`: 'linked'}]->(b) MATCH (stop1:stop)--(a:stoptime)-[:linked]-(b:stoptime)--(stop2:stop) CREATE (stop1)-[:distance {`~label`: 'distance', value: 0}]->(stop2) ``` as can be seen, the trick here is to give each participating node a `MATCH` statement of its own and to move the `WHERE` clause inside the second match condition; presumably, as mentioned above, Neo4J can only then take advantage of its indexes. with these queries in place, the process of reading in nodes and building edges takes roughly 13 minutes; of these 13 minutes, fetching the data from an external source, building the node representations and issuing `CREATE` queries takes about 10 minutes, **and building almost a half million edges between them is done in about 3 minutes**. right now none of my queries (especially the node `CREATE` statements and updates for stop distances) use parametrized queries, which is another potential source for performance gains. as for the `~label` field and also the question why i use dahes in names where underscores would be more convenient, well, that's a long story about what i perceive good and practical naming that sometimes clashes with the syntax of some languages (of most languages, should i say). but that's boring detail. maybe more intersting is the question: why is there a `~label` attribute that repeats what the element label says (what you write after the colon)? well, it's an attempt to comply with Neo4J conventions (we use labels here), take advantage of the 'identifier, colon, label' syntax of cypher queries, AND to make it so the labels do appear in the returned values. mind you, labels are so central to graph thinking the Neo4J way, but \*in query results, labels are conspicuously absent. when you include a relationship that is marked with nothing but a label in your result set, then that edge will arrive as an empty object, telling you only that there is *something* but not *what*. so i decided i to duplicate the label on each single node and each single edge. not an optimal solution but at least now i get an informative graph display in the Neo4J browser. as for how to express query use-cases, that's an active field of reserach for me right now. i guess it will all start with a 'field of interest', like 'show all Berlin subway stops', or 'all busses departing within the next 15 minutes from a bus stop near me'. the data already allows to see which stops are directly connected by a subway line, their geographical distance, what services are present and what routes they take. the idea is to grab the data and present them in novel, usable and beatiful ways. [9292](http://9292.nl) is quite close to what i imagine; what's missing are graphical representations of spatial and temporal relationships.
19,321,925
I have a query which I get as: ``` var query = Data.Items .Where(x => criteria.IsMatch(x)) .ToList<Item>(); ``` This works fine. However now I want to break up this list into x number of lists, for example 3. Each list will therefore contain 1/3 the amount of elements from query. Can it be done using LINQ?
2013/10/11
[ "https://Stackoverflow.com/questions/19321925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/524861/" ]
You can use PLINQ partitioners to break the results into separate enumerables. ``` var partitioner = Partitioner.Create<Item>(query); var partitions = partitioner.GetPartitions(3); ``` You'll need to reference the System.Collections.Concurrent namespace. `partitions` will be a list of `IEnumerable<Item>` where each enumerable returns a portion of the query.
I think something like this could work, splitting the list into [`IGrouping`](http://msdn.microsoft.com/en-us/library/bb344977.aspx)s. ``` const int numberOfGroups = 3; var groups = query .Select((item, i) => new { item, i }) .GroupBy(e => e.i % numberOfGroups); ```
19,321,925
I have a query which I get as: ``` var query = Data.Items .Where(x => criteria.IsMatch(x)) .ToList<Item>(); ``` This works fine. However now I want to break up this list into x number of lists, for example 3. Each list will therefore contain 1/3 the amount of elements from query. Can it be done using LINQ?
2013/10/11
[ "https://Stackoverflow.com/questions/19321925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/524861/" ]
I think something like this could work, splitting the list into [`IGrouping`](http://msdn.microsoft.com/en-us/library/bb344977.aspx)s. ``` const int numberOfGroups = 3; var groups = query .Select((item, i) => new { item, i }) .GroupBy(e => e.i % numberOfGroups); ```
You can create an extension method: ``` public static IList<List<T>> GetChunks<T>(this IList<T> items, int numOfChunks) { if (items.Count < numOfChunks) throw new ArgumentException("The number of elements is lower than the number of chunks"); int div = items.Count / numOfChunks; int rem = items.Count % numOfChunks; var listOfLists = new List<T>[numOfChunks]; for (int i = 0; i < numOfChunks; i++) listOfLists[i] = new List<T>(); int currentGrp = 0; int currRemainder = rem; foreach (var el in items) { int currentElementsInGrp = listOfLists[currentGrp].Count; if (currentElementsInGrp == div && currRemainder > 0) { currRemainder--; } else if (currentElementsInGrp >= div) { currentGrp++; } listOfLists[currentGrp].Add(el); } return listOfLists; } ``` then use it like this : ``` var chunks = query.GetChunks(3); ``` N.B. in case of number of elements not divisible by the number of groups, the first groups will be bigger. e.g. `[0,1,2,3,4] --> [0,1] - [2,3] - [4]`
19,321,925
I have a query which I get as: ``` var query = Data.Items .Where(x => criteria.IsMatch(x)) .ToList<Item>(); ``` This works fine. However now I want to break up this list into x number of lists, for example 3. Each list will therefore contain 1/3 the amount of elements from query. Can it be done using LINQ?
2013/10/11
[ "https://Stackoverflow.com/questions/19321925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/524861/" ]
I think something like this could work, splitting the list into [`IGrouping`](http://msdn.microsoft.com/en-us/library/bb344977.aspx)s. ``` const int numberOfGroups = 3; var groups = query .Select((item, i) => new { item, i }) .GroupBy(e => e.i % numberOfGroups); ```
You can use `Skip` and `Take` in a simple `for` to accomplish what you want ``` var groupSize = (int)Math.Ceiling(query.Count() / 3d); var result = new List<List<Item>>(); for (var j = 0; j < 3; j++) result.Add(query.Skip(j * groupSize).Take(groupSize).ToList()); ```
19,321,925
I have a query which I get as: ``` var query = Data.Items .Where(x => criteria.IsMatch(x)) .ToList<Item>(); ``` This works fine. However now I want to break up this list into x number of lists, for example 3. Each list will therefore contain 1/3 the amount of elements from query. Can it be done using LINQ?
2013/10/11
[ "https://Stackoverflow.com/questions/19321925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/524861/" ]
I think something like this could work, splitting the list into [`IGrouping`](http://msdn.microsoft.com/en-us/library/bb344977.aspx)s. ``` const int numberOfGroups = 3; var groups = query .Select((item, i) => new { item, i }) .GroupBy(e => e.i % numberOfGroups); ```
If the order of the elements doesn't matter using an `IGrouping` as suggested by Daniel Imms is probably the most elegant way (add `.Select(gr => gr.Select(e => e.item))` to get an `IEnumerable<IEnumerable<T>>`). If however you want to preserve the order you need to know the total number of elements. Otherwise you wouldn't know when to start the next group. You can do this with LINQ but it requires two enumerations: one for counting and another for returning the data (as suggested by Esteban Elverdin). If enumerating the query is expensive you can avoid the second enumeration by turning the query into a list and then use the [`GetRange`](http://msdn.microsoft.com/en-us/library/21k0e39c.aspx) method: ``` public static IEnumerable<List<T>> SplitList<T>(List<T> list, int numberOfRanges) { int sizeOfRanges = list.Count / numberOfRanges; int remainder = list.Count % numberOfRanges; int startIndex = 0; for (int i = 0; i < numberOfRanges; i++) { int size = sizeOfRanges + (remainder > 0 ? 1 : 0); yield return list.GetRange(startIndex, size); if (remainder > 0) { remainder--; } startIndex += size; } } static void Main() { List<int> list = Enumerable.Range(0, 10).ToList(); IEnumerable<List<int>> result = SplitList(list, 3); foreach (List<int> values in result) { string s = string.Join(", ", values); Console.WriteLine("{{ {0} }}", s); } } ``` The output is: ``` { 0, 1, 2, 3 } { 4, 5, 6 } { 7, 8, 9 } ```
19,321,925
I have a query which I get as: ``` var query = Data.Items .Where(x => criteria.IsMatch(x)) .ToList<Item>(); ``` This works fine. However now I want to break up this list into x number of lists, for example 3. Each list will therefore contain 1/3 the amount of elements from query. Can it be done using LINQ?
2013/10/11
[ "https://Stackoverflow.com/questions/19321925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/524861/" ]
You can use PLINQ partitioners to break the results into separate enumerables. ``` var partitioner = Partitioner.Create<Item>(query); var partitions = partitioner.GetPartitions(3); ``` You'll need to reference the System.Collections.Concurrent namespace. `partitions` will be a list of `IEnumerable<Item>` where each enumerable returns a portion of the query.
You can create an extension method: ``` public static IList<List<T>> GetChunks<T>(this IList<T> items, int numOfChunks) { if (items.Count < numOfChunks) throw new ArgumentException("The number of elements is lower than the number of chunks"); int div = items.Count / numOfChunks; int rem = items.Count % numOfChunks; var listOfLists = new List<T>[numOfChunks]; for (int i = 0; i < numOfChunks; i++) listOfLists[i] = new List<T>(); int currentGrp = 0; int currRemainder = rem; foreach (var el in items) { int currentElementsInGrp = listOfLists[currentGrp].Count; if (currentElementsInGrp == div && currRemainder > 0) { currRemainder--; } else if (currentElementsInGrp >= div) { currentGrp++; } listOfLists[currentGrp].Add(el); } return listOfLists; } ``` then use it like this : ``` var chunks = query.GetChunks(3); ``` N.B. in case of number of elements not divisible by the number of groups, the first groups will be bigger. e.g. `[0,1,2,3,4] --> [0,1] - [2,3] - [4]`
19,321,925
I have a query which I get as: ``` var query = Data.Items .Where(x => criteria.IsMatch(x)) .ToList<Item>(); ``` This works fine. However now I want to break up this list into x number of lists, for example 3. Each list will therefore contain 1/3 the amount of elements from query. Can it be done using LINQ?
2013/10/11
[ "https://Stackoverflow.com/questions/19321925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/524861/" ]
You can use PLINQ partitioners to break the results into separate enumerables. ``` var partitioner = Partitioner.Create<Item>(query); var partitions = partitioner.GetPartitions(3); ``` You'll need to reference the System.Collections.Concurrent namespace. `partitions` will be a list of `IEnumerable<Item>` where each enumerable returns a portion of the query.
You can use `Skip` and `Take` in a simple `for` to accomplish what you want ``` var groupSize = (int)Math.Ceiling(query.Count() / 3d); var result = new List<List<Item>>(); for (var j = 0; j < 3; j++) result.Add(query.Skip(j * groupSize).Take(groupSize).ToList()); ```
19,321,925
I have a query which I get as: ``` var query = Data.Items .Where(x => criteria.IsMatch(x)) .ToList<Item>(); ``` This works fine. However now I want to break up this list into x number of lists, for example 3. Each list will therefore contain 1/3 the amount of elements from query. Can it be done using LINQ?
2013/10/11
[ "https://Stackoverflow.com/questions/19321925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/524861/" ]
You can use PLINQ partitioners to break the results into separate enumerables. ``` var partitioner = Partitioner.Create<Item>(query); var partitions = partitioner.GetPartitions(3); ``` You'll need to reference the System.Collections.Concurrent namespace. `partitions` will be a list of `IEnumerable<Item>` where each enumerable returns a portion of the query.
If the order of the elements doesn't matter using an `IGrouping` as suggested by Daniel Imms is probably the most elegant way (add `.Select(gr => gr.Select(e => e.item))` to get an `IEnumerable<IEnumerable<T>>`). If however you want to preserve the order you need to know the total number of elements. Otherwise you wouldn't know when to start the next group. You can do this with LINQ but it requires two enumerations: one for counting and another for returning the data (as suggested by Esteban Elverdin). If enumerating the query is expensive you can avoid the second enumeration by turning the query into a list and then use the [`GetRange`](http://msdn.microsoft.com/en-us/library/21k0e39c.aspx) method: ``` public static IEnumerable<List<T>> SplitList<T>(List<T> list, int numberOfRanges) { int sizeOfRanges = list.Count / numberOfRanges; int remainder = list.Count % numberOfRanges; int startIndex = 0; for (int i = 0; i < numberOfRanges; i++) { int size = sizeOfRanges + (remainder > 0 ? 1 : 0); yield return list.GetRange(startIndex, size); if (remainder > 0) { remainder--; } startIndex += size; } } static void Main() { List<int> list = Enumerable.Range(0, 10).ToList(); IEnumerable<List<int>> result = SplitList(list, 3); foreach (List<int> values in result) { string s = string.Join(", ", values); Console.WriteLine("{{ {0} }}", s); } } ``` The output is: ``` { 0, 1, 2, 3 } { 4, 5, 6 } { 7, 8, 9 } ```
19,321,925
I have a query which I get as: ``` var query = Data.Items .Where(x => criteria.IsMatch(x)) .ToList<Item>(); ``` This works fine. However now I want to break up this list into x number of lists, for example 3. Each list will therefore contain 1/3 the amount of elements from query. Can it be done using LINQ?
2013/10/11
[ "https://Stackoverflow.com/questions/19321925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/524861/" ]
You can use `Skip` and `Take` in a simple `for` to accomplish what you want ``` var groupSize = (int)Math.Ceiling(query.Count() / 3d); var result = new List<List<Item>>(); for (var j = 0; j < 3; j++) result.Add(query.Skip(j * groupSize).Take(groupSize).ToList()); ```
You can create an extension method: ``` public static IList<List<T>> GetChunks<T>(this IList<T> items, int numOfChunks) { if (items.Count < numOfChunks) throw new ArgumentException("The number of elements is lower than the number of chunks"); int div = items.Count / numOfChunks; int rem = items.Count % numOfChunks; var listOfLists = new List<T>[numOfChunks]; for (int i = 0; i < numOfChunks; i++) listOfLists[i] = new List<T>(); int currentGrp = 0; int currRemainder = rem; foreach (var el in items) { int currentElementsInGrp = listOfLists[currentGrp].Count; if (currentElementsInGrp == div && currRemainder > 0) { currRemainder--; } else if (currentElementsInGrp >= div) { currentGrp++; } listOfLists[currentGrp].Add(el); } return listOfLists; } ``` then use it like this : ``` var chunks = query.GetChunks(3); ``` N.B. in case of number of elements not divisible by the number of groups, the first groups will be bigger. e.g. `[0,1,2,3,4] --> [0,1] - [2,3] - [4]`
19,321,925
I have a query which I get as: ``` var query = Data.Items .Where(x => criteria.IsMatch(x)) .ToList<Item>(); ``` This works fine. However now I want to break up this list into x number of lists, for example 3. Each list will therefore contain 1/3 the amount of elements from query. Can it be done using LINQ?
2013/10/11
[ "https://Stackoverflow.com/questions/19321925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/524861/" ]
If the order of the elements doesn't matter using an `IGrouping` as suggested by Daniel Imms is probably the most elegant way (add `.Select(gr => gr.Select(e => e.item))` to get an `IEnumerable<IEnumerable<T>>`). If however you want to preserve the order you need to know the total number of elements. Otherwise you wouldn't know when to start the next group. You can do this with LINQ but it requires two enumerations: one for counting and another for returning the data (as suggested by Esteban Elverdin). If enumerating the query is expensive you can avoid the second enumeration by turning the query into a list and then use the [`GetRange`](http://msdn.microsoft.com/en-us/library/21k0e39c.aspx) method: ``` public static IEnumerable<List<T>> SplitList<T>(List<T> list, int numberOfRanges) { int sizeOfRanges = list.Count / numberOfRanges; int remainder = list.Count % numberOfRanges; int startIndex = 0; for (int i = 0; i < numberOfRanges; i++) { int size = sizeOfRanges + (remainder > 0 ? 1 : 0); yield return list.GetRange(startIndex, size); if (remainder > 0) { remainder--; } startIndex += size; } } static void Main() { List<int> list = Enumerable.Range(0, 10).ToList(); IEnumerable<List<int>> result = SplitList(list, 3); foreach (List<int> values in result) { string s = string.Join(", ", values); Console.WriteLine("{{ {0} }}", s); } } ``` The output is: ``` { 0, 1, 2, 3 } { 4, 5, 6 } { 7, 8, 9 } ```
You can create an extension method: ``` public static IList<List<T>> GetChunks<T>(this IList<T> items, int numOfChunks) { if (items.Count < numOfChunks) throw new ArgumentException("The number of elements is lower than the number of chunks"); int div = items.Count / numOfChunks; int rem = items.Count % numOfChunks; var listOfLists = new List<T>[numOfChunks]; for (int i = 0; i < numOfChunks; i++) listOfLists[i] = new List<T>(); int currentGrp = 0; int currRemainder = rem; foreach (var el in items) { int currentElementsInGrp = listOfLists[currentGrp].Count; if (currentElementsInGrp == div && currRemainder > 0) { currRemainder--; } else if (currentElementsInGrp >= div) { currentGrp++; } listOfLists[currentGrp].Add(el); } return listOfLists; } ``` then use it like this : ``` var chunks = query.GetChunks(3); ``` N.B. in case of number of elements not divisible by the number of groups, the first groups will be bigger. e.g. `[0,1,2,3,4] --> [0,1] - [2,3] - [4]`
23,282,318
I need to disable the "Say something about this" popup box that is displayed after clicking the Facebook Like button. The simple solution to this is to use the iFrame version of the Like button. However, my like page is hosted with woobox. I cannot change the like button from HTML5 to the iframe version but I do have access to add additional CSS and Javascript. There have been a number of solutions posted to Stackoverflow but some users have pointed out that they no longer work [Facebook Like Button - how to disable Comment pop up?](https://stackoverflow.com/questions/3247855/facebook-like-button-how-to-disable-comment-pop-up) I have tried all of these solutions and can confirm this.
2014/04/25
[ "https://Stackoverflow.com/questions/23282318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3505865/" ]
Okay, I was able to create something that might help you. Here's the JSFiddle: [JSFiddle](http://jsfiddle.net/4vuDD/) What I basically did was I wrapped the like button in a div with hidden overflow. Only problem is, the comment box appears for a second right after loading the page, but goes away after. (it's still contained inside the div, but it covers up the like buttons for a second) Another approach could be something like this: [Changing iFrame elements](https://forum.jquery.com/topic/changing-elements-in-an-iframe) Where you would need to view the source and check Facebook's element id for the comment box. (looks like it's `div#u_0_6._56zz._56z`) Once you have the id you can try to `.hide()` or `.css('display', 'none')` Unfortunately, this id is really obscure and looks to me like it changes on a regular basis. So if it does change, your code obviously won't work. The JSFiddle does seems to work. And it looks like your only sure option.
In reference to your issue with the Woobox layout specifically, you'll want to reference just the portion of the entry form that includes the Like button to hide the overflow on that. The following CSS will do the trick alone: ``` .form-group .input-group.type-like .inputs.grid { overflow: hidden !important; } ``` If you want to fully replace the default Like button with your own IFRAME version of the button plugin, you can use the following: CSS to hide the default button: ``` .embedded .form-group .input-group.type-like .inputs.grid > div:first-child { display: none !important; } ``` and JS to include your own IFRAME version of the button instead, while keeping the general setup of the form the same ``` $(function() { $( '.embedded .form-group .input-group.type-like .inputs.grid' ).prepend( '<iframe src="//www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.facebook.com%2Fportraitize&amp;width&amp;layout=button&amp;action=like&amp;show_faces=false&amp;share=false&amp;height=35&amp;appId=872100376149378" scrolling="no" frameborder="0" style="border:none; overflow:hidden; height:22px; width:60px; float:left;" allowtransparency="true"></iframe>' ); }); ```
23,282,318
I need to disable the "Say something about this" popup box that is displayed after clicking the Facebook Like button. The simple solution to this is to use the iFrame version of the Like button. However, my like page is hosted with woobox. I cannot change the like button from HTML5 to the iframe version but I do have access to add additional CSS and Javascript. There have been a number of solutions posted to Stackoverflow but some users have pointed out that they no longer work [Facebook Like Button - how to disable Comment pop up?](https://stackoverflow.com/questions/3247855/facebook-like-button-how-to-disable-comment-pop-up) I have tried all of these solutions and can confirm this.
2014/04/25
[ "https://Stackoverflow.com/questions/23282318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3505865/" ]
Okay, I was able to create something that might help you. Here's the JSFiddle: [JSFiddle](http://jsfiddle.net/4vuDD/) What I basically did was I wrapped the like button in a div with hidden overflow. Only problem is, the comment box appears for a second right after loading the page, but goes away after. (it's still contained inside the div, but it covers up the like buttons for a second) Another approach could be something like this: [Changing iFrame elements](https://forum.jquery.com/topic/changing-elements-in-an-iframe) Where you would need to view the source and check Facebook's element id for the comment box. (looks like it's `div#u_0_6._56zz._56z`) Once you have the id you can try to `.hide()` or `.css('display', 'none')` Unfortunately, this id is really obscure and looks to me like it changes on a regular basis. So if it does change, your code obviously won't work. The JSFiddle does seems to work. And it looks like your only sure option.
just add this style to the `style="overflow: hidden !important;"` to the `div` like i have done below ``` <div class="fb-like pull-right" data-href="http://thegoldbook.in/demo/singlequestion.php?ques_no='.$ques_id.'" data-width="100" data-layout="button" data-action="like" data-show-faces="false" data-share="true" style="overflow: hidden !important;"></div> ```
47,348
Since for my [last question](https://buddhism.stackexchange.com/q/47334/16806), I did not get a satisfactory answer I am reducing the question to its barebones. What is the difference between 'Witnessing' and 'Mindfulness' from the context of meditation? I mean when I am looking at the sunset without any thoughts in mind and feel a oneness, am I witnessing the sunset or I am being mindful of the eye-consciousness? In the [Mahāsatipaṭṭhānasutta MN 10](https://suttacentral.net/mn10/en/sujato?layout=plain&reference=none&notes=asterisk&highlight=false&script=latin#mn10:2.1) the word mindfulness is used, can I replace it with the word, 'Witnessing' without changing the meaning?
2022/06/01
[ "https://buddhism.stackexchange.com/questions/47348", "https://buddhism.stackexchange.com", "https://buddhism.stackexchange.com/users/16806/" ]
sati ("mindfulness") is one of the most commonly misunderstood teachings. It's been distorted by psychotherapy agendas, and even experienced Buddhist teachers have wildly divergent understandings. If you want the perspective from the original suttas: There's an implicit object of sati, and that's the Dharma, the Buddha's teaching that leads to nirvana. One always remembers to apply the Dharma. All the time. The fourth frame of sati, seeing Dharma as Dharma, is commonly misunderstood to be seeing thoughts (the dhamma that the mind/mano cognizes/viññāna). But the primary role of seeing Dharma as Dharma, is living each moment in accordance with the Buddha's Dharma, and the dhamma-thoughts cognized by the mind are subservient to that primary objective. More detail here: <http://notesonthedhamma.blogspot.com/2022/12/two-ways-in-which-sati-mindfulness-is.html>
Maybe see the Quora thread on Osho's "witness": <https://www.quora.com/What-is-witness-meditation-as-described-by-Osho> I can only tell from my personal experience: I've read books where "witnessing" was used synonymously with perceiving with mindfullness (sati) and without follow-up thoughts (<https://en.wikipedia.org/wiki/Conceptual_proliferation>) Your sunset example seems to be a mix of different elements: The basic perception process goes from the object (external) to the eye sense organ to perception to sign (nimitta), but then stopping there (if you are right that there is no mental proliferation). The feeling of oneness seems to be a separate, second perception from your "internal sense organ". However, it's unclear if the source of this feeling is directly the eye-consciousness, if it is mediated by the perception of "beauty", or if it's the result of a separate associative process based on the memories of what Osho told you about oneness. You may also have a look at oneness and it's background: <https://en.wikipedia.org/wiki/Nondualism> However, attaining advaita usually takes years of meditation practice. Perception of beauty is said (by Sangharakshita somewhere) to provide a glimpse of it.
47,348
Since for my [last question](https://buddhism.stackexchange.com/q/47334/16806), I did not get a satisfactory answer I am reducing the question to its barebones. What is the difference between 'Witnessing' and 'Mindfulness' from the context of meditation? I mean when I am looking at the sunset without any thoughts in mind and feel a oneness, am I witnessing the sunset or I am being mindful of the eye-consciousness? In the [Mahāsatipaṭṭhānasutta MN 10](https://suttacentral.net/mn10/en/sujato?layout=plain&reference=none&notes=asterisk&highlight=false&script=latin#mn10:2.1) the word mindfulness is used, can I replace it with the word, 'Witnessing' without changing the meaning?
2022/06/01
[ "https://buddhism.stackexchange.com/questions/47348", "https://buddhism.stackexchange.com", "https://buddhism.stackexchange.com/users/16806/" ]
the other answers are already good so I'll just add this quote from [wiki](https://en.wikipedia.org/wiki/Sakshi_(witness)) regarding witness: > > "When form is the object of observation or drshyam, then the eye is > the observer or drk; when the eye is the object of observation, then > the mind is the observer; when the pulsations of the mind are the > objects of observation, then Sakshi or the Witnessing-Self is the real > observer; and it is always the observer, and, being self-luminous, can > never be the object of observation. When the notion and the attachment > that one is the physical body is dissolved, and the Supreme Self is > realized, wherever one goes, there one experiences Samadhi. " > > > of course I don't see how the eye can be the object of observation but that's just me...i'm not a god
Maybe see the Quora thread on Osho's "witness": <https://www.quora.com/What-is-witness-meditation-as-described-by-Osho> I can only tell from my personal experience: I've read books where "witnessing" was used synonymously with perceiving with mindfullness (sati) and without follow-up thoughts (<https://en.wikipedia.org/wiki/Conceptual_proliferation>) Your sunset example seems to be a mix of different elements: The basic perception process goes from the object (external) to the eye sense organ to perception to sign (nimitta), but then stopping there (if you are right that there is no mental proliferation). The feeling of oneness seems to be a separate, second perception from your "internal sense organ". However, it's unclear if the source of this feeling is directly the eye-consciousness, if it is mediated by the perception of "beauty", or if it's the result of a separate associative process based on the memories of what Osho told you about oneness. You may also have a look at oneness and it's background: <https://en.wikipedia.org/wiki/Nondualism> However, attaining advaita usually takes years of meditation practice. Perception of beauty is said (by Sangharakshita somewhere) to provide a glimpse of it.
47,348
Since for my [last question](https://buddhism.stackexchange.com/q/47334/16806), I did not get a satisfactory answer I am reducing the question to its barebones. What is the difference between 'Witnessing' and 'Mindfulness' from the context of meditation? I mean when I am looking at the sunset without any thoughts in mind and feel a oneness, am I witnessing the sunset or I am being mindful of the eye-consciousness? In the [Mahāsatipaṭṭhānasutta MN 10](https://suttacentral.net/mn10/en/sujato?layout=plain&reference=none&notes=asterisk&highlight=false&script=latin#mn10:2.1) the word mindfulness is used, can I replace it with the word, 'Witnessing' without changing the meaning?
2022/06/01
[ "https://buddhism.stackexchange.com/questions/47348", "https://buddhism.stackexchange.com", "https://buddhism.stackexchange.com/users/16806/" ]
sati ("mindfulness") is one of the most commonly misunderstood teachings. It's been distorted by psychotherapy agendas, and even experienced Buddhist teachers have wildly divergent understandings. If you want the perspective from the original suttas: There's an implicit object of sati, and that's the Dharma, the Buddha's teaching that leads to nirvana. One always remembers to apply the Dharma. All the time. The fourth frame of sati, seeing Dharma as Dharma, is commonly misunderstood to be seeing thoughts (the dhamma that the mind/mano cognizes/viññāna). But the primary role of seeing Dharma as Dharma, is living each moment in accordance with the Buddha's Dharma, and the dhamma-thoughts cognized by the mind are subservient to that primary objective. More detail here: <http://notesonthedhamma.blogspot.com/2022/12/two-ways-in-which-sati-mindfulness-is.html>
Mindfulness is situational awareness of the body and its context, which occurs effortlessly at all times. Precisely where that awareness occurs, I have no idea. Awareness isn't the best term, as there is no such thing as awareness, but I don't have another convenient word, at this time. Regardless, when it fully opens up, you are safe there. True mindfulness is the pinnacle of what Buddha taught. Knowing your body and its context leads to the end of suffering. This is why Thich Nhat Hanh called it *the safe island of mindfulness.* This is not a mindfulness that is performed by cognizant effort, however, when introduced to the idea of being mindful, one is lavished with a range of various mindfulness-based techniques, which may or may not be helpful. Therefore, if we look at this in progressive terms, we might be able to find an answer to your question. In the beginning, as one approaches the practice of being mindful, one must exert themselves. This very exertion gives mindfulness a definition which makes it stand out from other things - it becomes a routine task, a behaviour that one must perform. This is the preamble phase where a lot of discernment takes place, or what you might call *witnessing*. In this preliminary phase, the mind is going through a preparation, from which sensory preoccupations begin to diminish leading to disenchantment. During that preparation, many questions will arise about the nature of mindfulness, mostly what it actually is, and are you doing it right. These, too, need to become part of what is discerned (or witnessed). Witnessing isn't the best term as it suggests one must push aside thoughts, feelings & sensations so that the witnessing can take place. However, these discernable things must remain intimately close, closer than close. The quality of attention that is used to discern passing phenomena (thoughts, feelings & sensations) is crucial to the whole practice. In Zen terms, this is called 'sweeping' (popular in the Caodong school) and one sweeps with such persistence and regularity that the great empty sky suddenly opens up and all distinctions dissolve. Why is that? Because the discerning mind becomes disenchanted by what it has become caught inside of and seeks freedom as if all by itself. Over in the Theravada tradition, in the [Anguttara Nikaya](http://www.buddha-vacana.org/sutta/anguttara/06/an06-054.html) and Buddhagosa's [Path Of Purification, Page 684](https://www.accesstoinsight.org/lib/authors/nanamoli/PathofPurification2011.pdf) a simile of a crow was used to illustrate the meaning of *tathāgatako*, which I colloquially translate as *'gone, mate!'.* The crow symbolizes the disenchantment of the mind brought about by unrelenting mindfulness practice, and how it searches for another place of rest, which in Buddhist parlance is called Nirvana. It is here where one truly understands mindfulness, but not from the perspective of *doing*, hence it no longer becomes a task. One might say it is now the ordinary part of daily life. [![enter image description here](https://i.stack.imgur.com/0w5sWm.png)](https://i.stack.imgur.com/0w5sWm.png) [The 7 Stages of Purification - Page 107](https://www.buddhanet.net/pdf_file/bm7insight.pdf)
47,348
Since for my [last question](https://buddhism.stackexchange.com/q/47334/16806), I did not get a satisfactory answer I am reducing the question to its barebones. What is the difference between 'Witnessing' and 'Mindfulness' from the context of meditation? I mean when I am looking at the sunset without any thoughts in mind and feel a oneness, am I witnessing the sunset or I am being mindful of the eye-consciousness? In the [Mahāsatipaṭṭhānasutta MN 10](https://suttacentral.net/mn10/en/sujato?layout=plain&reference=none&notes=asterisk&highlight=false&script=latin#mn10:2.1) the word mindfulness is used, can I replace it with the word, 'Witnessing' without changing the meaning?
2022/06/01
[ "https://buddhism.stackexchange.com/questions/47348", "https://buddhism.stackexchange.com", "https://buddhism.stackexchange.com/users/16806/" ]
the other answers are already good so I'll just add this quote from [wiki](https://en.wikipedia.org/wiki/Sakshi_(witness)) regarding witness: > > "When form is the object of observation or drshyam, then the eye is > the observer or drk; when the eye is the object of observation, then > the mind is the observer; when the pulsations of the mind are the > objects of observation, then Sakshi or the Witnessing-Self is the real > observer; and it is always the observer, and, being self-luminous, can > never be the object of observation. When the notion and the attachment > that one is the physical body is dissolved, and the Supreme Self is > realized, wherever one goes, there one experiences Samadhi. " > > > of course I don't see how the eye can be the object of observation but that's just me...i'm not a god
Mindfulness is situational awareness of the body and its context, which occurs effortlessly at all times. Precisely where that awareness occurs, I have no idea. Awareness isn't the best term, as there is no such thing as awareness, but I don't have another convenient word, at this time. Regardless, when it fully opens up, you are safe there. True mindfulness is the pinnacle of what Buddha taught. Knowing your body and its context leads to the end of suffering. This is why Thich Nhat Hanh called it *the safe island of mindfulness.* This is not a mindfulness that is performed by cognizant effort, however, when introduced to the idea of being mindful, one is lavished with a range of various mindfulness-based techniques, which may or may not be helpful. Therefore, if we look at this in progressive terms, we might be able to find an answer to your question. In the beginning, as one approaches the practice of being mindful, one must exert themselves. This very exertion gives mindfulness a definition which makes it stand out from other things - it becomes a routine task, a behaviour that one must perform. This is the preamble phase where a lot of discernment takes place, or what you might call *witnessing*. In this preliminary phase, the mind is going through a preparation, from which sensory preoccupations begin to diminish leading to disenchantment. During that preparation, many questions will arise about the nature of mindfulness, mostly what it actually is, and are you doing it right. These, too, need to become part of what is discerned (or witnessed). Witnessing isn't the best term as it suggests one must push aside thoughts, feelings & sensations so that the witnessing can take place. However, these discernable things must remain intimately close, closer than close. The quality of attention that is used to discern passing phenomena (thoughts, feelings & sensations) is crucial to the whole practice. In Zen terms, this is called 'sweeping' (popular in the Caodong school) and one sweeps with such persistence and regularity that the great empty sky suddenly opens up and all distinctions dissolve. Why is that? Because the discerning mind becomes disenchanted by what it has become caught inside of and seeks freedom as if all by itself. Over in the Theravada tradition, in the [Anguttara Nikaya](http://www.buddha-vacana.org/sutta/anguttara/06/an06-054.html) and Buddhagosa's [Path Of Purification, Page 684](https://www.accesstoinsight.org/lib/authors/nanamoli/PathofPurification2011.pdf) a simile of a crow was used to illustrate the meaning of *tathāgatako*, which I colloquially translate as *'gone, mate!'.* The crow symbolizes the disenchantment of the mind brought about by unrelenting mindfulness practice, and how it searches for another place of rest, which in Buddhist parlance is called Nirvana. It is here where one truly understands mindfulness, but not from the perspective of *doing*, hence it no longer becomes a task. One might say it is now the ordinary part of daily life. [![enter image description here](https://i.stack.imgur.com/0w5sWm.png)](https://i.stack.imgur.com/0w5sWm.png) [The 7 Stages of Purification - Page 107](https://www.buddhanet.net/pdf_file/bm7insight.pdf)
412,304
A few days after installing 6.1.1 some pages started redirecting to the homepage. I renamed .htaccess, disabled all plugins, and am using the 2022 default theme to try to locate the source of the 301 with no luck. So I checked curl, and found the source of the redirect was labeled "Wordpress". So I stopped the redirect and dumped the debug\_backtrace in order to finally locate this thing. I'm guessing there is a canonical URL set up, but for the life of me, I can't figure it out. Any page with the URL [https://stgtrulite.wpengine.com/platform/[anything]](https://stgtrulite.wpengine.com/platform/%5Banything%5D) gets a 301 to <https://stgtrulite.wpengine.com>. The rest of the site works, and I can change the URL of the affected pages, but google has already crawled them with the URL. Can someone please help me out? Here is the dump: ``` Redirect attempted to location: https://stgtrulite.wpengine.com/ Array ( [0] => Array ( [file] => /nas/content/live/stgtrulite/wp-includes/canonical.php [line] => 801 [function] => wp_redirect [args] => Array ( [0] => https://stgtrulite.wpengine.com/ [1] => 301 ) ) [1] => Array ( [file] => /nas/content/live/stgtrulite/wp-includes/class-wp-hook.php [line] => 308 [function] => redirect_canonical [args] => Array ( [0] => https://stgtrulite.wpengine.com/platform/xxx ) ) [2] => Array ( [file] => /nas/content/live/stgtrulite/wp-includes/class-wp-hook.php [line] => 332 [function] => apply_filters [class] => WP_Hook [object] => WP_Hook Object ( [callbacks] => Array ( [0] => Array ( [_wp_admin_bar_init] => Array ( [function] => _wp_admin_bar_init [accepted_args] => 1 ) ) [10] => Array ( [wp_old_slug_redirect] => Array ( [function] => wp_old_slug_redirect [accepted_args] => 1 ) [redirect_canonical] => Array ( [function] => redirect_canonical [accepted_args] => 1 ) [0000000026d0f2cb000000001a0eef68render_sitemaps] => Array ( [function] => Array ( [0] => WP_Sitemaps Object ( [index] => WP_Sitemaps_Index Object ( [registry:protected] => WP_Sitemaps_Registry Object ( [providers:WP_Sitemaps_Registry:private] => Array ( [posts] => WP_Sitemaps_Posts Object ( [name:protected] => posts [object_type:protected] => post ) [taxonomies] => WP_Sitemaps_Taxonomies Object ( [name:protected] => taxonomies [object_type:protected] => term ) [users] => WP_Sitemaps_Users Object ( [name:protected] => users [object_type:protected] => user ) ) ) [max_sitemaps:WP_Sitemaps_Index:private] => 50000 ) [registry] => WP_Sitemaps_Registry Object ( [providers:WP_Sitemaps_Registry:private] => Array ( [posts] => WP_Sitemaps_Posts Object ( [name:protected] => posts [object_type:protected] => post ) [taxonomies] => WP_Sitemaps_Taxonomies Object ( [name:protected] => taxonomies [object_type:protected] => term ) [users] => WP_Sitemaps_Users Object ( [name:protected] => users [object_type:protected] => user ) ) ) [renderer] => WP_Sitemaps_Renderer Object ( [stylesheet:protected] => [stylesheet_index:protected] => ) ) [1] => render_sitemaps ) [accepted_args] => 1 ) ) [11] => Array ( [rest_output_link_header] => Array ( [function] => rest_output_link_header [accepted_args] => 0 ) [wp_shortlink_header] => Array ( [function] => wp_shortlink_header [accepted_args] => 0 ) ) [1000] => Array ( [wp_redirect_admin_locations] => Array ( [function] => wp_redirect_admin_locations [accepted_args] => 1 ) ) [99999] => Array ( [0000000026d0f112000000001a0eef68is_404] => Array ( [function] => Array ( [0] => WpeCommon Object ( [options:protected] => ) [1] => is_404 ) [accepted_args] => 1 ) ) ) [iterations:WP_Hook:private] => Array ( [0] => Array ( [0] => 0 [1] => 10 [2] => 11 [3] => 1000 [4] => 99999 ) ) [current_priority:WP_Hook:private] => Array ( [0] => 10 ) [nesting_level:WP_Hook:private] => 1 [doing_action:WP_Hook:private] => 1 ) [type] => -> [args] => Array ( [0] => [1] => Array ( [0] => ) ) ) [3] => Array ( [file] => /nas/content/live/stgtrulite/wp-includes/plugin.php [line] => 517 [function] => do_action [class] => WP_Hook [object] => WP_Hook Object ( [callbacks] => Array ( [0] => Array ( [_wp_admin_bar_init] => Array ( [function] => _wp_admin_bar_init [accepted_args] => 1 ) ) [10] => Array ( [wp_old_slug_redirect] => Array ( [function] => wp_old_slug_redirect [accepted_args] => 1 ) [redirect_canonical] => Array ( [function] => redirect_canonical [accepted_args] => 1 ) [0000000026d0f2cb000000001a0eef68render_sitemaps] => Array ( [function] => Array ( [0] => WP_Sitemaps Object ( [index] => WP_Sitemaps_Index Object ( [registry:protected] => WP_Sitemaps_Registry Object ( [providers:WP_Sitemaps_Registry:private] => Array ( [posts] => WP_Sitemaps_Posts Object ( [name:protected] => posts [object_type:protected] => post ) [taxonomies] => WP_Sitemaps_Taxonomies Object ( [name:protected] => taxonomies [object_type:protected] => term ) [users] => WP_Sitemaps_Users Object ( [name:protected] => users [object_type:protected] => user ) ) ) [max_sitemaps:WP_Sitemaps_Index:private] => 50000 ) [registry] => WP_Sitemaps_Registry Object ( [providers:WP_Sitemaps_Registry:private] => Array ( [posts] => WP_Sitemaps_Posts Object ( [name:protected] => posts [object_type:protected] => post ) [taxonomies] => WP_Sitemaps_Taxonomies Object ( [name:protected] => taxonomies [object_type:protected] => term ) [users] => WP_Sitemaps_Users Object ( [name:protected] => users [object_type:protected] => user ) ) ) [renderer] => WP_Sitemaps_Renderer Object ( [stylesheet:protected] => [stylesheet_index:protected] => ) ) [1] => render_sitemaps ) [accepted_args] => 1 ) ) [11] => Array ( [rest_output_link_header] => Array ( [function] => rest_output_link_header [accepted_args] => 0 ) [wp_shortlink_header] => Array ( [function] => wp_shortlink_header [accepted_args] => 0 ) ) [1000] => Array ( [wp_redirect_admin_locations] => Array ( [function] => wp_redirect_admin_locations [accepted_args] => 1 ) ) [99999] => Array ( [0000000026d0f112000000001a0eef68is_404] => Array ( [function] => Array ( [0] => WpeCommon Object ( [options:protected] => ) [1] => is_404 ) [accepted_args] => 1 ) ) ) [iterations:WP_Hook:private] => Array ( [0] => Array ( [0] => 0 [1] => 10 [2] => 11 [3] => 1000 [4] => 99999 ) ) [current_priority:WP_Hook:private] => Array ( [0] => 10 ) [nesting_level:WP_Hook:private] => 1 [doing_action:WP_Hook:private] => 1 ) [type] => -> [args] => Array ( [0] => Array ( [0] => ) ) ) [4] => Array ( [file] => /nas/content/live/stgtrulite/wp-includes/template-loader.php [line] => 13 [function] => do_action [args] => Array ( [0] => template_redirect ) ) [5] => Array ( [file] => /nas/content/live/stgtrulite/wp-blog-header.php [line] => 19 [args] => Array ( [0] => /nas/content/live/stgtrulite/wp-includes/template-loader.php ) [function] => require_once ) [6] => Array ( [file] => /nas/content/live/stgtrulite/index.php [line] => 17 [args] => Array ( [0] => /nas/content/live/stgtrulite/wp-blog-header.php ) [function] => require ) ) ```
2022/12/24
[ "https://wordpress.stackexchange.com/questions/412304", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/206120/" ]
In WordPress, there is no concept of "super admins" in the same way that there is in a multisite installation. However, there may be users with the "administrator" role who have access to all areas of the site, including the WordPress settings. If you are an administrator and you are unable to access the WordPress settings, it could be due to a number of reasons. Here are a few things you could try: * Check that you are logged in with an account that has the "administrator" role. * Check if there are any plugins or themes that may be blocking access to the settings. You can try deactivating all plugins and switching to a default theme to see if this resolves the issue. * Check if there are any errors in your site's `wp-config.php` file that may be preventing access to the settings. * If you are using a caching plugin, try clearing the cache to see if that resolves the issue. If none of these suggestions helps, you may need to access the site's database and check via your Host cpanel for any issues there. You can use a tool like `phpMyAdmin` to access the database `wp_users` table and check for any problems. while on `PHPMyAdmin`, Check if there are any issues with the user roles: The user roles in WordPress determine what permissions users have on the site. If your user role has been changed or there are any issues with the user roles, it could prevent you from accessing the dashboard. You can check the `wp_usermeta` table to see if there are any issues with the user roles. To change user roles in the wp\_usermeta table in WordPress using phpMyAdmin, you can follow these steps: 1. Log in to your hosting account and open the phpMyAdmin tool. 2. Select the WordPress database from the list of databases on the left side of the page. 3. Click on the `wp_usermeta` table to open it. 4. Click on the "Browse" tab to view the contents of the table. 5. Find the row corresponding to the user whose role you want to change. The `user_id` column will contain the ID of the user, and the `meta_key` column will contain the string "`wp_capabilities`". 6. Click on the "Edit" link for the row you want to modify. 7. In the "meta\_value" field, enter the desired role for the user. The role should be specified as a serialized array, with the key corresponding to the role and the value set to true. For example, to set the user's role to "administrator", you would enter the following value in the "meta\_value" field: `a:1:{s:13:"administrator";b:1;}`. if a user has the "administrator" role, the `wp_capabilities` field for that user might contain the following value: `a:1:{s:13:"administrator";b:1;}`. This value indicates that the user has the "administrator" role, with the key `s:13:"administrator"` corresponding to the role and the value `b:1;` indicating that the `role is enabled`. 8. Click the "Go" button to save the changes. Please note that changing user roles in the database can have serious consequences if not done carefully. It is important to make sure you understand the implications of modifying the database before making any changes. If you are not comfortable working with databases, it is best to seek the help of a developer or database administrator. I hope this helps! Let me know if you have any other questions.
See @Tamara answers below regarding edits in phpmyadmin for user role levels. There is likely a plugin installed or a modification in the functions.php file that is removing items from the menu list. Log into phpmyadmin for the site, check your username login against those of the other company. Likely the permission level is going to be different. *[Removed instructions for wp\_usermeta as it is no longer relevant]* Most likely there is a plugin or edit in the functions.php which is controlling what you see in the admin menu.
21,169,968
I set up a new Ghost 0.4 blog, created numerous posts, then switched to production mode before setting the site live. To my surprise, the posts I created no longer showed up. Since setting up Ghost 0.3.3, I had forgotten that Ghost uses separate database stores for the production and development environments, and I failed to switch to production mode before creating content. How can I migrate content from Ghost's development environment to its production environment?
2014/01/16
[ "https://Stackoverflow.com/questions/21169968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/705157/" ]
Ghost uses SQLite databases, which stores content in a single file for each content, so it's easy to back-up, move or copy an entire database in one go. To solve the problem of having posts only in my development database, I simply shut down Ghost, and switched the production and development SQLite database files. The files are stored in the Ghost `content/data` sub-folder: * `ghost-dev.db` is the development database * `ghost.db` is the production database If you're in the Ghost folder, the following commands will swap the two environment databases: ``` $ mv content/data/ghost-dev.db content/data/ghost-dev.db-tmp $ mv content/data/ghost.db content/data/ghost-dev.db $ mv content/data/ghost-dev.db-tmp content/data/ghost.db ``` Restart Ghost in either mode to see the changes. It's even easier to just copy everything from development to production: ``` $ cp content/data/ghost-dev.db content/data/ghost.db ```
An easy way to change this behavior is to just choose to use the same database for both production and development. Modify the following line in your `config.js` under development:database:connection from ``` filename: path.join(__dirname, '/content/data/ghost-dev.db') ``` to ``` filename: path.join(__dirname, '/content/data/ghost.db') ```
30,737,541
I want to use enumeration type in C. I know how to use them but I have a question. I have an example like this ``` enum S { A,B,C,G }; ``` I know this works but can i do something like this? ``` enum S {^,*,/,%}; ``` Thanks for your time.
2015/06/09
[ "https://Stackoverflow.com/questions/30737541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3161625/" ]
No. You can only use alphanumeric characters and underscores in identifiers (variable, function, and type names) in C. And the identifier cannot start with a number. Also, you can't use certain reserved keywords. *<http://www.cprogrammingexpert.com/C/Tutorial/fundamentals/identifiers.aspx>* (link broken) UPDATE: Newer link that's not broken: <https://www.w3schools.in/c-programming/identifiers>
The [ANSI C specification](http://eli-project.sourceforge.net/c_html/c.html#m51) says you can use an "OrdinaryIdDef" for enums... so it follows the same rules as--for example--variable & function names
30,737,541
I want to use enumeration type in C. I know how to use them but I have a question. I have an example like this ``` enum S { A,B,C,G }; ``` I know this works but can i do something like this? ``` enum S {^,*,/,%}; ``` Thanks for your time.
2015/06/09
[ "https://Stackoverflow.com/questions/30737541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3161625/" ]
No. You can only use alphanumeric characters and underscores in identifiers (variable, function, and type names) in C. And the identifier cannot start with a number. Also, you can't use certain reserved keywords. *<http://www.cprogrammingexpert.com/C/Tutorial/fundamentals/identifiers.aspx>* (link broken) UPDATE: Newer link that's not broken: <https://www.w3schools.in/c-programming/identifiers>
No. However, you could do something like this: ``` enum S { CARET = '^', STAR = '*', SLASH = '/', PERCENT = '%' }; int foo() { enum S somevar = CARET; // .... if (somevar == PERCENT) // .... } ``` Not sure if that would be useful for whatever it is you're trying to do, though, since you don't really give any background...
30,737,541
I want to use enumeration type in C. I know how to use them but I have a question. I have an example like this ``` enum S { A,B,C,G }; ``` I know this works but can i do something like this? ``` enum S {^,*,/,%}; ``` Thanks for your time.
2015/06/09
[ "https://Stackoverflow.com/questions/30737541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3161625/" ]
No. However, you could do something like this: ``` enum S { CARET = '^', STAR = '*', SLASH = '/', PERCENT = '%' }; int foo() { enum S somevar = CARET; // .... if (somevar == PERCENT) // .... } ``` Not sure if that would be useful for whatever it is you're trying to do, though, since you don't really give any background...
The [ANSI C specification](http://eli-project.sourceforge.net/c_html/c.html#m51) says you can use an "OrdinaryIdDef" for enums... so it follows the same rules as--for example--variable & function names
27,530,000
There seem to be at at least **two or three major ways** of building **apps** that communicate with `bokeh-server` in Bokeh. They correspond to the [folders](https://github.com/bokeh/bokeh/tree/master/examples) [`app`](https://github.com/bokeh/bokeh/tree/master/examples/app), [`embed`](https://github.com/bokeh/bokeh/tree/master/examples/embed) and [`plotting`](https://github.com/bokeh/bokeh/tree/master/examples/plotting)/[`glyphs`](https://github.com/bokeh/bokeh/tree/master/examples/glyphs) under the [examples](https://github.com/bokeh/bokeh/tree/master/examples) directory in Bokeh. On the differences between them, I read [here](https://groups.google.com/a/continuum.io/forum/?utm_medium=email&utm_source=footer#!msg/bokeh/NClF-837DMc/hCfy8tnyFDUJ) the following: > > On the [`stock_app.py`](https://github.com/bokeh/bokeh/blob/master/examples/app/stock_applet/stock_app.py) ([`app`](https://github.com/bokeh/bokeh/tree/master/examples/app) folder) example you are using `bokeh-server` to **embed an > applet** and serve it from the url you specify. That's why you crate a > new `StockApp` class and create a function that creates a new instance > of it and decorates it with @`bokeh_app.route("/bokeh/stocks/")` and > `@object_page("stocks")`. You can follow the **[`app`](https://github.com/bokeh/bokeh/tree/master/examples/app) examples** (sliders, > stock and crossfilter) and use bokeh `@object_page` and `@bokeh_app.route` > decorators to create your custom url. > > > On the [`taylor_server.py`](https://github.com/bokeh/bokeh/blob/master/examples/glyphs/taylor_server.py) example ([`glyphs`](https://github.com/bokeh/bokeh/tree/master/examples/glyphs) folder) it is the **session object** that > is taking care of creating everything on `bokeh-server` for you. From > this interface is not possible to customize urls or create alias. > > > But this confused me, what is meant by an "applet" & "embedding" in Bokeh terminology, and what is **exactly** he difference between applets (presumably [`app`](https://github.com/bokeh/bokeh/tree/master/examples/app) and [`embed`](https://github.com/bokeh/bokeh/tree/master/examples/embed)) and [`plotting`](https://github.com/bokeh/bokeh/tree/master/examples/plotting)/[`glyphs`](https://github.com/bokeh/bokeh/tree/master/examples/glyphs)? Also I thought that the notion of "embedding" only referred to the design pattern that we see in the `embed` folder as in the example [`animated.py`](https://github.com/bokeh/bokeh/blob/master/examples/embed/animated.py), where we embed a `tag` in the body of an HTML file. I don't see that in the [`stock_app.py`](https://github.com/bokeh/bokeh/blob/master/examples/app/stock_applet/stock_app.py), so why is it an embedding example?
2014/12/17
[ "https://Stackoverflow.com/questions/27530000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/283296/" ]
> > But this confused me, what is meant by an "applet" & "embedding" in > Bokeh terminology > > > There is clearly a mistake in the answer you have pasted here (that probably doesn't help you on understanding, sorry). The stock app example `stock_app.py` is in examples\app\stock\_applet\stock\_app.py not embed folder. Also, the terminology used does not help either. On that example you create an applet that can be served in 2 different ways: 1. running directly on a bokeh-server 2. embedded (or integrated if you prefer) into a separate application (a Flask application in that case) You may find more information at the `examples\app\stock_applet\README.md` file. Also, you can find info about applets and bokeh server [examples documentation](http://bokeh.pydata.org/docs/user_guide/examples.html#id2) and [userguide](http://bokeh.pydata.org/docs/user_guide/server.html) Regarding what does embedding means, you can find more info at the user\_guide/embedding section of bokeh docs. To summarize, you can generate code that you can insert on your own web application code to display bokeh components. Examples in examples\embed are also useful to understand this pattern. Finally, the usage of bokeh-server you see in `taylor_server.py` is just using bokeh server to serve you plot (instead of saving it to a static html file). Hope this helps ;-)
Just to add a little bit... I will paste here a quote from Bryan in the mailing list (in another thread, so maybe you missed it): > > Regarding app vs embed. The "apps" are all run *inside* the bokeh-server. So you start them, > by doing something like: > > > > ``` > bokeh-server --script sliders_app.py > > ``` > > The main reason for this is because, otherwise, to make an "app" > outside the server, the only real solutions is to have a long-running > process that polls the server for updates. This is not ideal, and apps > running directly in the server can utilize much better callbacks. > Please note that the "app" concept is still fairly new, and things > like how to start, easily spell, and deploy apps is very much open to > improvement. > > > The "embed" examples simply show off how to embed a Bokeh plot in a > standard web-app (i.e., you want to serve a plot from Flask that has a > plot in it). This can be done with, or without the bokeh-server, but > even if you use a bokeh-server, there is no code running *in the > bokeh-server* that responds to widgets, or updates plots or data. To > update plots you'd have to have a separate python process that > connects to the bokeh-server and polls or pushes data to it. > > > Cheers. Damian
71,547,975
I have tried a lot but still can't solve this.. How can I render a tetrahedron with different texture on each face? At beginning I was trying this way. ```js import * as THREE from 'three'; window.onload = () => { const scene = new THREE.Scene() const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000) const renderer = new THREE.WebGLRenderer({ antialias: true }) renderer.setSize(window.innerWidth, window.innerHeight) document.body.appendChild(renderer.domElement) var geometry = new THREE.CylinderGeometry(0, 2, 3, 3, 3, false) var materials = [ new THREE.MeshBasicMaterial({ color: 0xff00ff }), new THREE.MeshBasicMaterial({ color: 0xff0000 }), new THREE.MeshBasicMaterial({ color: 0x0000ff }), new THREE.MeshBasicMaterial({ color: 0x5100ff }) ] var tetra = new THREE.Mesh(geometry, materials) scene.add(tetra) renderer.render(scene, camera) camera.position.z = 5; var ambientLight = new THREE.AmbientLight(0xffffff, 0.5) scene.add(ambientLight) function animate() { requestAnimationFrame(animate) tetra.rotation.x += 0.04; tetra.rotation.y += 0.04; renderer.render(scene, camera) } animate() } ``` I use a cylinder geometry to "make" a fake tetrahedron. But I found that I can't texturing each face of this "tetrahedron", bc cylinder geometry actually have only 3 faces. Does anyone know how to do it? P.S. I have also tried TetrahedronGeometry but it just didn't work, I guessed it was because TetrahedronGeometry is basically BufferGeometry and there are no faces property on it.
2022/03/20
[ "https://Stackoverflow.com/questions/71547975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4752143/" ]
You can build your own geometry or modify an existing one. To have different materials on sides, use `groups`. ```css body{ overflow: hidden; margin: 0; } ``` ```html <script type="module"> import * as THREE from "https://cdn.skypack.dev/[email protected]"; import {OrbitControls} from "https://cdn.skypack.dev/[email protected]/examples/jsm/controls/OrbitControls" let scene = new THREE.Scene(); let camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 1000); camera.position.set(0, 5, 10).setLength(3); let renderer = new THREE.WebGLRenderer(); renderer.setSize(innerWidth, innerHeight); document.body.appendChild(renderer.domElement); window.addEventListener("resize", event => { camera.aspect = innerWidth / innerHeight; camera.updateProjectionMatrix(); rendrer.setSize(innerWidth, innerHeight); }) let controls = new OrbitControls(camera, renderer.domElement); // https://discourse.threejs.org/t/tetrahedron-non-indexed-buffer-geometry/12542 // tetrahedron // --------------------------------------------------------------------------------------- var pts = [ // https://en.wikipedia.org/wiki/Tetrahedron#Coordinates_for_a_regular_tetrahedron new THREE.Vector3(Math.sqrt(8 / 9), 0, -(1 / 3)), new THREE.Vector3(-Math.sqrt(2 / 9), Math.sqrt(2 / 3), -(1 / 3)), new THREE.Vector3(-Math.sqrt(2 / 9), -Math.sqrt(2 / 3), -(1 / 3)), new THREE.Vector3(0, 0, 1) ]; var faces = [ // triangle soup pts[0].clone(), pts[2].clone(), pts[1].clone(), pts[0].clone(), pts[1].clone(), pts[3].clone(), pts[1].clone(), pts[2].clone(), pts[3].clone(), pts[2].clone(), pts[0].clone(), pts[3].clone() ]; var geom = new THREE.BufferGeometry().setFromPoints(faces); geom.rotateX(-Math.PI * 0.5); geom.computeVertexNormals(); geom.setAttribute("uv", new THREE.Float32BufferAttribute([ // UVs 0.5, 1, 0.06698729810778059, 0.2500000000000001, 0.9330127018922194, 0.2500000000000001, 0.06698729810778059, 0.2500000000000001, 0.9330127018922194, 0.2500000000000001, 0.5, 1, 0.06698729810778059, 0.2500000000000001, 0.9330127018922194, 0.2500000000000001, 0.5, 1, 0.06698729810778059, 0.2500000000000001, 0.9330127018922194, 0.2500000000000001, 0.5, 1 ], 2)); geom.addGroup(0, 3, 0); geom.addGroup(3, 3, 1); geom.addGroup(6, 3, 2); geom.addGroup(9, 3, 3); // --------------------------------------------------------------------------------------- let tl = new THREE.TextureLoader(); let tp = "https://threejs.org/examples/textures/"; let tetra = new THREE.Mesh(geom, [ new THREE.MeshBasicMaterial({map: tl.load(tp + "uv_grid_opengl.jpg")}), new THREE.MeshBasicMaterial({map: tl.load(tp + "colors.png")}), new THREE.MeshBasicMaterial({map: tl.load(tp + "brick_diffuse.jpg")}), new THREE.MeshBasicMaterial({map: tl.load(tp + "758px-Canestra_di_frutta_(Caravaggio).jpg")}) ]) scene.add(tetra); renderer.setAnimationLoop(()=> { renderer.render(scene, camera); }); </script> ```
Finally I understood how to make it work using `three.js` `TetrahedronGeometry`. Actually making our own geo is not necessary, but we will have to reset `uv array` if we are using `three.js` `TetrahedronGeometry`. ```js private initGeometry(){ const radius = this.config.size*Math.sqrt(6)/4; this.geometry = new THREE.TetrahedronGeometry(radius,0); console.log(this.geometry.attributes.uv.array); this.geometry.addGroup(0, 3, 0); this.geometry.addGroup(3, 3, 1); this.geometry.addGroup(6, 3, 2); this.geometry.addGroup(9, 3, 3); this.geometry.setAttribute("uv", new THREE.Float32BufferAttribute([ // UVs, //numbers here are to describe uv coordinate, so they are actually customizable // if you want to customize it, you have to check the vertices position array first. 0,0, 1, 0, 0.5, 1, // 1, 0, 0.5, 1, 0,0, // 1, 0, 0.5, 1, 0,0, // 0,0, 1, 0, 0.5, 1 ], 2)); this.geometry.rotateY(-Math.PI); } ```
735,915
Is it possible to use the built in ASP.NET membership provider to secure a web service? I have a SQL Server database already setup with my membership and now I want to provide a web service that only members are allowed to use. Is it possible to authenticate against this (if so how?) or do I need to have a seperate type of authentication for the web services?
2009/04/09
[ "https://Stackoverflow.com/questions/735915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/53020/" ]
There actually is a solution, it turns out: WebRequest.PreAuthenticate Check out an [article](http://www.west-wind.com/Weblog/posts/243915.aspx) by Rick Strahl.
This "double handshake" is a integral part of NTLM's challenge response model. Your only option would be to change the authentication type. Alternatively, you try re-using the connection for web service calls.
22,850,061
**<http://codepen.io/leongaban/pen/talGc/>** So having an interesting problem here. I've got a left and right div The left div has 3 elements in it: 1) Person 1 2) WANTS TO MEET sign 3) Person 2 The right div just a paragraph, both divs are close to 50% width each. Now if you shrink the browser window, the items inside of the left div will start to wrap. If I know exactly how wide the contents inside of the left div will always be this wouldn't be a problem, I could just solve it with media queries. So here is my problem, the elements inside the left div will always change so I can't find the perfect media query to break on and remove the floats. I believe I can fix this problem in jQuery by calculating the width of all the elements inside the left div, and check to see if it matches the width of their container on window resize then remove the floats. However that seems like doing too much and using too much to solve this problem. Is there a CSS solution to this? All my code is in the CodePen link above, here is the mediaQuery I'm using to remove the floats at 1205px. But again I will never know the correct size to break everytime since the widths will change: ``` @media all and (max-width: 1205px) { .the_requestor, .the_requested, .wants_to_meet { float: none; } .the_requestor { margin: 0 0 10px 0; } .request_details_left { margin-top: 0; border-right: 1px solid #e0e0e0; } .request_details_right { width: 40%; border: 0; } } ``` **Screenshots:** Large Desktop - correct look ![enter image description here](https://i.stack.imgur.com/Cs6Us.png) Resizing the window - problematic look (This is what I want to avoid) ![enter image description here](https://i.stack.imgur.com/pUnER.png) Resized small Desktop - correct look ![enter image description here](https://i.stack.imgur.com/IVa3W.png)
2014/04/03
[ "https://Stackoverflow.com/questions/22850061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/168738/" ]
I suspect what you're *really* trying to do is to show the parent of any `li` with class `active` within a `.cn_submenu`. Your current code looks to see if the **first** `li` of the **first** `.cn_submenu` has the class `active` (ignoring all other `.cn_submenu` and `li` elements), and then uses `this` incorrectly if so. To show the parent of any `li` with class `active` that's inside a `.cn_submenu`: ``` $(document).ready(function(){ $(".cn_submenu li.active").parent().show(); }); ``` How that works: * `$(".cn_submenu li.active")` selects any `li` elements with the class `active` that are descendants of a `.cn_submenu`. * `.parent()` finds the (unique) set of immediate parents of those elements. * `.show()` shows them (if any).
`this` refers to `document` in your question, so you're trying to `show()` the parent of `document`. Use `$('.cn_submenu')` instead.
64,685,502
I have two differents dataframes ``` DF1 = data.frame("A"= c("a","a","b","b","c","c"), "B"= c(1,2,3,4,5,6)) DF2 = data.frame("A"=c("a","b","c"), "C"=c(10,11,12)) ``` I want to add the column `C` to `DF1` grouping by column `A` The expected result is ``` A B C 1 a 1 10 2 a 2 10 3 b 3 11 4 b 4 11 5 c 5 12 6 c 6 12 ``` note: In this example all the groups have the same size but it won't be necessarily the case
2020/11/04
[ "https://Stackoverflow.com/questions/64685502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14578930/" ]
Welcome to stackoverflow. As @KarthikS commented, what you want is a join. 'Joining' is the name of the operation for connecting two tables together. 'Grouping by' a column is mainly used when summarizing a table: For example, group by state and sum number of votes would give the total number of votes by each state (summing without grouping first would give the grand total number of votes). The syntax for joins in dplyr is: ```r output = left_join(df1, df2, by = "shared column") ``` or equivalently ```r output = df1 %>% left_join(df2, by = "shared column") ``` Key reference [here](https://dplyr.tidyverse.org/reference/join.html). In your example, the shared column is `"A"`.
We can use `merge` from `base R` ``` merge(DF1, DF2, by = 'A', all.x = TRUE) ```
42,563,429
I have data coming in and am trying to display the rows it fills with ng-repeat. Here is how the data looks coming in: [![enter image description here](https://i.stack.imgur.com/98EpM.png)](https://i.stack.imgur.com/98EpM.png) SO I am trying to display it on the view: ``` <tbody data-ng-repeat="contract in contracts"> <tr> <td><div data-strat-form-control data-field-display-id="1" data-vmformreadonly="true" data-strat-model="contract" data-field="contracts[0].ndc_id"></div></td> </tr> </tbody> ``` Typing `{{contract.ndc_id}}` or `{{contracts.ndc_id}}` returns nothing. However, `{{contracts[0].ndc_id}}` returns the expected data. But There will be multiple contracts in the array and this will only account for the 1st one it looks like. Why isn't ng-repeat iterating using (contract in contracts)? How do I fix this?
2017/03/02
[ "https://Stackoverflow.com/questions/42563429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1524210/" ]
``` <div ng-repeat="(key, value) in contracts[0]"> {{contracts[0][key]}} | {{value}} <div ng-if="$index === 1"> This is the second value {{value}}</div> <div ng-if="$index === 2"> This is the thrid value {{value}}</div> <div ng-if="$last"> This is the last value {{value}}</div> </div> ```
According to your data, it looks like an object, you cannot do ng-repeat over your object, However you can do this in order to read the properties and values, ``` <div ng-repeat="(key, value) in contracts"> {{key}} | {{value}}</div> ```
28,913,473
This is image : <http://oi60.tinypic.com/118iq7r.jpg> I have a similar database structure to that shown in the table above. However, I have additional columns for the login times. I would like to take the data from the columns and display them on a page. ``` ID | txtName | txtEmail | txtPasswd ------------------------------------------- 1 | Ahmet | [email protected] | 123123 2 | Ali | [email protected] | 312 321 <?php session_start(); ob_start(); include 'connect.php'; $email = $_POST['txtEmail']; $password = $_POST['txtPasswd']; $cryptpass = md5($password); $login = mysql_query("select * from users where txtEmail='".$email."' and txtPasswd='".$cryptpass."' ") or die(mysql_error()); if(mysql_num_rows($login)) { $_SESSION["login"] = true; $_SESSION["user"] = $password; $_SESSION["pass"] = $password; $_SESSION["email"] = $emailadress; header("location:index.php"); } else { if($email=="" or $password=="") { echo ""; } else { header('Location:index.php?error=1'); exit; } } ob_end_flush(); ?> ``` This is my profile page. ``` <?php if (empty($_SESSION["fullname"])) { $fullnamequery = ""; } if(!empty($_SESSION['login'])) { echo '<li class="user logged"> <a href="http://www.petkod.com/hesabim/bilgilerim" title="'.$_SESSION['fullname'].'">'.$_SESSION['fullname'].'<span class="arrow"></span></a> <div class="subMenu"> <ul> <li><a href="http://www.petkod.com/hesabim/bilgilerim" class="info">Bilgilerim</a></li> <li><a href="http://www.petkod.com/hesabim/petlerim" class="pet">Petlerim</a></li> <li><a href="http://www.petkod.com/hesabim/adreslerim" class="address">Adreslerim</a></li> <li><a href="http://www.petkod.com/hesabim/siparisler" class="order">Siparişlerim</a></li> <li><a href="logout.php" class="logout">Çıkış</a></li> </ul> </div> </li>'; }else{echo '<li class="user"><a href="popup-login.php" data-width="520" data-height="556" class="iframe">Giriş Yap</a></li>';}; ?> ```
2015/03/07
[ "https://Stackoverflow.com/questions/28913473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4643769/" ]
Your suggestion is the good choice to make. You can't catch the Router in a Meteor method because it's server side. You have to do it in the **callback function**, exactly like you suggested : ``` Meteor.call('createNewItinerary',itinerary, function(err, data){ if(err){ console.log(err); } Router.go('confirmation'); }); ``` To check that the work has correctly been done on the server, just throw errors, for example: ``` throw new Meteor.Error( 500, 'There was an error processing your request' ); ``` Then if error is thrown, it will be logged in your client side. Hope it helps you :)
Your suggestion makes sense to me: ``` Meteor.call('createNewItinerary',itinerary, function(err, data){ if(err){ console.log(err); } Router.go('confirmation'); }); ``` You'll call createNewItinerary and when it returns you'll send the user to the confirmation page. That said, you might want some error checking - as you've got it currently you send the user to the confirmation page regardless of a successful or failed insert. Perhaps: ``` Meteor.call('createNewItinerary',itinerary, function(err, data){ if(err){ console.log(err); Router.go('errorpage'); // Presuming you have a route setup with this name } else Router.go('confirmation'); }); ```
54,886,421
I have this code: ``` new Thread(new Runnable() { @Override public void run() { //implement } }); ``` My IDE(intellij) suggest to use: ``` new Thread(() -> { //implement }); ``` This guarantee is the same thing? I ask this because class [Thread](https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#Thread()) has multiple constructors.
2019/02/26
[ "https://Stackoverflow.com/questions/54886421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9011164/" ]
Yes, that is equivalent, trust your IDE! Regarding multiple constructors: * you have exactly one constructor argument -> two possible constructor implementations * is `() -> { //implement }` a `String`? - **no** -> only one possible constructor to call -> the one for `Runnable`, which you would call on your own as well.
Yes, it's a similar thing. Both the representation would call the [`Thread(Runnable runnable)`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Thread.html#%3Cinit%3E(java.lang.Runnable)) constructor. The later code in your question ``` () -> { //implement } ``` is a ***lambda representation*** of the ***anonymous class*** in the code previous to it : ``` new Runnable() { @Override public void run() { //implement } } ```
54,886,421
I have this code: ``` new Thread(new Runnable() { @Override public void run() { //implement } }); ``` My IDE(intellij) suggest to use: ``` new Thread(() -> { //implement }); ``` This guarantee is the same thing? I ask this because class [Thread](https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#Thread()) has multiple constructors.
2019/02/26
[ "https://Stackoverflow.com/questions/54886421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9011164/" ]
Yes, it's a similar thing. Both the representation would call the [`Thread(Runnable runnable)`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Thread.html#%3Cinit%3E(java.lang.Runnable)) constructor. The later code in your question ``` () -> { //implement } ``` is a ***lambda representation*** of the ***anonymous class*** in the code previous to it : ``` new Runnable() { @Override public void run() { //implement } } ```
It is similar, but not the exactly same thing. It behaves the same way in all the regular cases. Some methods access their stack (trace). Those might yield different results.
54,886,421
I have this code: ``` new Thread(new Runnable() { @Override public void run() { //implement } }); ``` My IDE(intellij) suggest to use: ``` new Thread(() -> { //implement }); ``` This guarantee is the same thing? I ask this because class [Thread](https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#Thread()) has multiple constructors.
2019/02/26
[ "https://Stackoverflow.com/questions/54886421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9011164/" ]
Yes, it's a similar thing. Both the representation would call the [`Thread(Runnable runnable)`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Thread.html#%3Cinit%3E(java.lang.Runnable)) constructor. The later code in your question ``` () -> { //implement } ``` is a ***lambda representation*** of the ***anonymous class*** in the code previous to it : ``` new Runnable() { @Override public void run() { //implement } } ```
Yes, it is the same. You can use the lambda Expression because interface Runnable has the Annotation @FunctionalInterface.
54,886,421
I have this code: ``` new Thread(new Runnable() { @Override public void run() { //implement } }); ``` My IDE(intellij) suggest to use: ``` new Thread(() -> { //implement }); ``` This guarantee is the same thing? I ask this because class [Thread](https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#Thread()) has multiple constructors.
2019/02/26
[ "https://Stackoverflow.com/questions/54886421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9011164/" ]
Yes, that is equivalent, trust your IDE! Regarding multiple constructors: * you have exactly one constructor argument -> two possible constructor implementations * is `() -> { //implement }` a `String`? - **no** -> only one possible constructor to call -> the one for `Runnable`, which you would call on your own as well.
It is similar, but not the exactly same thing. It behaves the same way in all the regular cases. Some methods access their stack (trace). Those might yield different results.
54,886,421
I have this code: ``` new Thread(new Runnable() { @Override public void run() { //implement } }); ``` My IDE(intellij) suggest to use: ``` new Thread(() -> { //implement }); ``` This guarantee is the same thing? I ask this because class [Thread](https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#Thread()) has multiple constructors.
2019/02/26
[ "https://Stackoverflow.com/questions/54886421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9011164/" ]
Yes, that is equivalent, trust your IDE! Regarding multiple constructors: * you have exactly one constructor argument -> two possible constructor implementations * is `() -> { //implement }` a `String`? - **no** -> only one possible constructor to call -> the one for `Runnable`, which you would call on your own as well.
Yes, it is the same. You can use the lambda Expression because interface Runnable has the Annotation @FunctionalInterface.
69,238,124
From an image made up of 9 smaller images arranged as a 3x3-grid like ``` AAA BBB CCC ``` i want to automatically generate all possible variations as .pngs, where the position of the smaller images does matter, no position can be empty and and each small image must be present three times. I managed to get a list of these permutations with python: ``` from sympy.utilities.iterables import multiset_permutations from pprint import pprint pprint(list(multiset_permutations(['A','A','A','B','B','B','C','C','C']))) ``` resulting in 1680 variations: ``` [['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'], ['A', 'A', 'A', 'B', 'B', 'C', 'B', 'C', 'C'], ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'B', 'C'], ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'C', 'B'], ['A', 'A', 'A', 'B', 'C', 'B', 'B', 'C', 'C'], ['A', 'A', 'A', 'B', 'C', 'B', 'C', 'B', 'C'], ... ['C', 'C', 'C', 'B', 'B', 'B', 'A', 'A', 'A']] ``` How can i replace each letter for each line with the respective small images A.png, B.png and C.png, which are all square 1000 x 1000 px, with the first three 1000 px apart, and two more rows below? Thank you for your help!
2021/09/18
[ "https://Stackoverflow.com/questions/69238124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9338851/" ]
You can achieve this using `flex` and javascript: ```js document.addEventListener("DOMContentLoaded", function() { var btn1= document.getElementById("btn1"); var btn2= document.getElementById("btn2"); var maxWidth = btn1.offsetWidth; if(maxWidth<btn2.offsetWidth)maxWidth=btn2.offsetWidth; maxWidth+=1; btn1.style.width = maxWidth+"px"; btn2.style.width = maxWidth+"px"; }); ``` ```css .container { display:flex; align-items: flex-start; justify-content: space-between; width: 1000px; height: 100px; border: 1px solid black; } ``` ```html <div class="container"> <button id="btn1">Little text (very left)</button> <button id="btn2">This text is way more long than the other (very right)</button> </div> ```
Use a fix larger `width` so that content of 2nd button can be easily contained because 1st one will not create problem . `float` can be used to direct to extreme left/right but it is not recommended ```css .container { width: 1000px; height: 100px; border: 1px solid black; } button{ width:350px; } ``` ```html <div class="container"> <button>Little text (very left)</button> <button style="float:right">This text is way more long than the other (very right)</button> </div> ``` You can use `display: flex` also like in below snippet : ```css .container { width: 1000px; height: 100px; border: 1px solid black; display: flex; justify-content: space-between } button { width: 350px; } ``` ```html <div class="container"> <!--span tag is used which act as container for button to preserve the button default height can remove it to span the whole height of container by button--> <span><button>Little text (very left)</button></span> <span><button>This text is way more long than the other (very right)</button></span> </div> ``` Width of your button can be based on the one which has `max-text` by using method in below snippet > > Here used 3 buttons (can use any number) with different length to demonstrate how function works you can put buttons at extreme ends using above methods so not included here > > > ```js function widthBtn() { var reed = document.getElementsByClassName("container")[0].getElementsByTagName("BUTTON"); let lengths = Array.from(reed).map(e => e.innerHTML.length); let max = Math.max(...lengths); for (let i = 0; i < reed.length; i++) { if (reed[i].innerHTML.length == max) { var maxWidthBtn = reed[i].offsetWidth; } } for (let i = 0; i < reed.length; i++) { reed[i].style.minWidth = maxWidthBtn + "px"; } } widthBtn(); ``` ```css .container { width: 2000px; height: 100px; border: 1px solid black; display: flex; } ``` ```html <div class="container"> <!--span tag is used which act as container for button to preserve the button default height can remove it to span the whole height of container by button--> <button>This text is way more long than the other (very right)</button> <button>Little text text is way more long than the other (very right) (very left)</button> <button>Little text (very left)</button> </div> ``` You can't use CSS to know elements length or width , it is only for styling purpose . Use **JavaScript** language which is suitable to come up with solution
69,238,124
From an image made up of 9 smaller images arranged as a 3x3-grid like ``` AAA BBB CCC ``` i want to automatically generate all possible variations as .pngs, where the position of the smaller images does matter, no position can be empty and and each small image must be present three times. I managed to get a list of these permutations with python: ``` from sympy.utilities.iterables import multiset_permutations from pprint import pprint pprint(list(multiset_permutations(['A','A','A','B','B','B','C','C','C']))) ``` resulting in 1680 variations: ``` [['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'], ['A', 'A', 'A', 'B', 'B', 'C', 'B', 'C', 'C'], ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'B', 'C'], ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'C', 'B'], ['A', 'A', 'A', 'B', 'C', 'B', 'B', 'C', 'C'], ['A', 'A', 'A', 'B', 'C', 'B', 'C', 'B', 'C'], ... ['C', 'C', 'C', 'B', 'B', 'B', 'A', 'A', 'A']] ``` How can i replace each letter for each line with the respective small images A.png, B.png and C.png, which are all square 1000 x 1000 px, with the first three 1000 px apart, and two more rows below? Thank you for your help!
2021/09/18
[ "https://Stackoverflow.com/questions/69238124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9338851/" ]
You can achieve this using `flex` and javascript: ```js document.addEventListener("DOMContentLoaded", function() { var btn1= document.getElementById("btn1"); var btn2= document.getElementById("btn2"); var maxWidth = btn1.offsetWidth; if(maxWidth<btn2.offsetWidth)maxWidth=btn2.offsetWidth; maxWidth+=1; btn1.style.width = maxWidth+"px"; btn2.style.width = maxWidth+"px"; }); ``` ```css .container { display:flex; align-items: flex-start; justify-content: space-between; width: 1000px; height: 100px; border: 1px solid black; } ``` ```html <div class="container"> <button id="btn1">Little text (very left)</button> <button id="btn2">This text is way more long than the other (very right)</button> </div> ```
You can do it simply by changing a little in your code. ``` .container { border: 2px solid red; padding: 10px; display: flex; flex-direction: row; justify-content: space-between; } ``` Here I am just making the outer container flex and setting the flex direction row. This will set both buttons in a single row. Now just add:`justify-content: space-between;` and both the buttons will be aligned as you want. By the way there is also an alternate method through which you can do this work. Just give unique id to both the buttons. ``` <div class="container"> <button id="btn1">Little text (very left)</button> <button id="btn2">This text is way more long than the other (very right)</button> </div> ``` Now set the `float` property to `left` and `right` ``` #btn{ float: left; } #btn2{ float: right; } ``` I think it should work now. Thanks
69,238,124
From an image made up of 9 smaller images arranged as a 3x3-grid like ``` AAA BBB CCC ``` i want to automatically generate all possible variations as .pngs, where the position of the smaller images does matter, no position can be empty and and each small image must be present three times. I managed to get a list of these permutations with python: ``` from sympy.utilities.iterables import multiset_permutations from pprint import pprint pprint(list(multiset_permutations(['A','A','A','B','B','B','C','C','C']))) ``` resulting in 1680 variations: ``` [['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'], ['A', 'A', 'A', 'B', 'B', 'C', 'B', 'C', 'C'], ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'B', 'C'], ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'C', 'B'], ['A', 'A', 'A', 'B', 'C', 'B', 'B', 'C', 'C'], ['A', 'A', 'A', 'B', 'C', 'B', 'C', 'B', 'C'], ... ['C', 'C', 'C', 'B', 'B', 'B', 'A', 'A', 'A']] ``` How can i replace each letter for each line with the respective small images A.png, B.png and C.png, which are all square 1000 x 1000 px, with the first three 1000 px apart, and two more rows below? Thank you for your help!
2021/09/18
[ "https://Stackoverflow.com/questions/69238124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9338851/" ]
Here you should use JavaScript. First, get buttons widths, compare them and then make equal the less button to bigger. ```js let btn = document.querySelectorAll('button') if(btn[0].offsetWidth > btn[1].offsetWidth) { btn[1].style.width = `${btn[0].offsetWidth}px` } else { btn[0].style.width = `${btn[1].offsetWidth}px` } console.log(btn) ``` ```css .container { width: 800px; height: 100px; border: 1px solid black; display: flex; justify-content: space-between; align-items: flex-start; } ``` ```html <div class="container"> <button>Little text (very left)</button> <button>This text is way more long than the other (very right)</button> </div> ```
Use a fix larger `width` so that content of 2nd button can be easily contained because 1st one will not create problem . `float` can be used to direct to extreme left/right but it is not recommended ```css .container { width: 1000px; height: 100px; border: 1px solid black; } button{ width:350px; } ``` ```html <div class="container"> <button>Little text (very left)</button> <button style="float:right">This text is way more long than the other (very right)</button> </div> ``` You can use `display: flex` also like in below snippet : ```css .container { width: 1000px; height: 100px; border: 1px solid black; display: flex; justify-content: space-between } button { width: 350px; } ``` ```html <div class="container"> <!--span tag is used which act as container for button to preserve the button default height can remove it to span the whole height of container by button--> <span><button>Little text (very left)</button></span> <span><button>This text is way more long than the other (very right)</button></span> </div> ``` Width of your button can be based on the one which has `max-text` by using method in below snippet > > Here used 3 buttons (can use any number) with different length to demonstrate how function works you can put buttons at extreme ends using above methods so not included here > > > ```js function widthBtn() { var reed = document.getElementsByClassName("container")[0].getElementsByTagName("BUTTON"); let lengths = Array.from(reed).map(e => e.innerHTML.length); let max = Math.max(...lengths); for (let i = 0; i < reed.length; i++) { if (reed[i].innerHTML.length == max) { var maxWidthBtn = reed[i].offsetWidth; } } for (let i = 0; i < reed.length; i++) { reed[i].style.minWidth = maxWidthBtn + "px"; } } widthBtn(); ``` ```css .container { width: 2000px; height: 100px; border: 1px solid black; display: flex; } ``` ```html <div class="container"> <!--span tag is used which act as container for button to preserve the button default height can remove it to span the whole height of container by button--> <button>This text is way more long than the other (very right)</button> <button>Little text text is way more long than the other (very right) (very left)</button> <button>Little text (very left)</button> </div> ``` You can't use CSS to know elements length or width , it is only for styling purpose . Use **JavaScript** language which is suitable to come up with solution
69,238,124
From an image made up of 9 smaller images arranged as a 3x3-grid like ``` AAA BBB CCC ``` i want to automatically generate all possible variations as .pngs, where the position of the smaller images does matter, no position can be empty and and each small image must be present three times. I managed to get a list of these permutations with python: ``` from sympy.utilities.iterables import multiset_permutations from pprint import pprint pprint(list(multiset_permutations(['A','A','A','B','B','B','C','C','C']))) ``` resulting in 1680 variations: ``` [['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'], ['A', 'A', 'A', 'B', 'B', 'C', 'B', 'C', 'C'], ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'B', 'C'], ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'C', 'B'], ['A', 'A', 'A', 'B', 'C', 'B', 'B', 'C', 'C'], ['A', 'A', 'A', 'B', 'C', 'B', 'C', 'B', 'C'], ... ['C', 'C', 'C', 'B', 'B', 'B', 'A', 'A', 'A']] ``` How can i replace each letter for each line with the respective small images A.png, B.png and C.png, which are all square 1000 x 1000 px, with the first three 1000 px apart, and two more rows below? Thank you for your help!
2021/09/18
[ "https://Stackoverflow.com/questions/69238124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9338851/" ]
Here you should use JavaScript. First, get buttons widths, compare them and then make equal the less button to bigger. ```js let btn = document.querySelectorAll('button') if(btn[0].offsetWidth > btn[1].offsetWidth) { btn[1].style.width = `${btn[0].offsetWidth}px` } else { btn[0].style.width = `${btn[1].offsetWidth}px` } console.log(btn) ``` ```css .container { width: 800px; height: 100px; border: 1px solid black; display: flex; justify-content: space-between; align-items: flex-start; } ``` ```html <div class="container"> <button>Little text (very left)</button> <button>This text is way more long than the other (very right)</button> </div> ```
You can do it simply by changing a little in your code. ``` .container { border: 2px solid red; padding: 10px; display: flex; flex-direction: row; justify-content: space-between; } ``` Here I am just making the outer container flex and setting the flex direction row. This will set both buttons in a single row. Now just add:`justify-content: space-between;` and both the buttons will be aligned as you want. By the way there is also an alternate method through which you can do this work. Just give unique id to both the buttons. ``` <div class="container"> <button id="btn1">Little text (very left)</button> <button id="btn2">This text is way more long than the other (very right)</button> </div> ``` Now set the `float` property to `left` and `right` ``` #btn{ float: left; } #btn2{ float: right; } ``` I think it should work now. Thanks
846,748
I'm running an openLDAP server version 2.4.40 on CentOS 7. LDAP is going to be configured using online conf option (olc). Thanks to this [question](https://stackoverflow.com/questions/17669586/where-is-my-data-directories-store-by-slapd-openldap-on-ubuntu), I know that slapd's database files are in `/var/lib/ldap`. I'm trying to run an openLDAP server on a linux box as read-only OS partition and another partition for persistent data. I will be able to install and configure openLDAP on the OS partition, but will lose access to it after configuring it. **Question:** Is it possible to change the location LDAP reads/writes data from */var/lib/ldap* to somewhere on the persistent data partition?
2017/04/26
[ "https://serverfault.com/questions/846748", "https://serverfault.com", "https://serverfault.com/users/405449/" ]
I read your question in two parts: 1. You want to have the OS be read-only while preserving write access to the LDAP data 2. As a solution for #1, you propose storing the LDAP data in a location other than `/var/lib/ldap` While I suspect #2 is possible, I don't have enough direct experience with OpenLDAP to address that directly. What I can do is suggest an alternative solution for #1. It's trivial to mount a difference disk partion at `/var/lib/ldap`, both through the `mount` command and through `fstab`. This should effectively accomplish your goal, whether or not OpenLDAP handles this natively. You might also be able to replace the `/var/lib/ldap` folder with a symlink to the desired location. Again, this bypasses OpenLDAP and any support that is or is not built into that project. Finally, you should also think about preserving write access for certain log areas. The techniques in the paragraph above can work for moving log file locations, too.
Openldap does not appear to support moving a database, DB, file after it has been created. Openldap does not currently support deleting DB files either. It is possible to create a new DB file and define its olcDbDirectory attribute to a path on another partition. ``` dn: olcDatabase=bdb,cn=config objectClass: olcBdbConfig olcDatabase: bdb olcDbDirectory: /partition/db/new-db-file olcSuffix: dc=example,dc=net ``` Information found in ch 6.1.1.4.5 [Add/Delete Databases using OLC](http://www.zytrax.com/books/ldap/ch6/slapd-config.html#use-databases)
846,748
I'm running an openLDAP server version 2.4.40 on CentOS 7. LDAP is going to be configured using online conf option (olc). Thanks to this [question](https://stackoverflow.com/questions/17669586/where-is-my-data-directories-store-by-slapd-openldap-on-ubuntu), I know that slapd's database files are in `/var/lib/ldap`. I'm trying to run an openLDAP server on a linux box as read-only OS partition and another partition for persistent data. I will be able to install and configure openLDAP on the OS partition, but will lose access to it after configuring it. **Question:** Is it possible to change the location LDAP reads/writes data from */var/lib/ldap* to somewhere on the persistent data partition?
2017/04/26
[ "https://serverfault.com/questions/846748", "https://serverfault.com", "https://serverfault.com/users/405449/" ]
I used to move the default database of openldap after each new setup. The steps I do when I want to move a database : * Stop `slapd` ``` sudo service slapd stop ``` * `slapcat` the content of the `cn=config` branch in a LDIF file ``` sudo slapcat -b cn=config > /tmp/config.ldif ``` * Copy the `/var/lib/ldap` directory wherever you want it * Make sure the user `openldap` owns the new directory and all the files inside * Edit the previously exported LDIF to modify the `olcDbDirectory` to the new location * Import the LDIF (Make sure the `/etc/ldap/slapd.d` is empty before doing this) ``` sudo rm -r /etc/ldap/slapd.d/* sudo slapadd -F /etc/ldap/slapd.d -b cn=config -l /tmp/config.ldif ``` * Make sure the `/etc/ldap/slapd.d` and all its content is owned by `openldap` ``` sudo chown -R openldap:openldap /etc/ldap/slapd.d/ ``` * Edit needed configuration to allow Slapd to use this new database directory For example, with `apparmor`, edit the file `/etc/apparmor.d/usr.sbin.slapd` and add the following lines: ``` /path/to/new/db/ r, /path/to/new/db/** rwk, ``` * Restart apparmor and slapd ``` sudo service apparmor restart sudo service slapd start ``` Usually it does the trick. It's also how I backup the configuration of my openldap instances.
I read your question in two parts: 1. You want to have the OS be read-only while preserving write access to the LDAP data 2. As a solution for #1, you propose storing the LDAP data in a location other than `/var/lib/ldap` While I suspect #2 is possible, I don't have enough direct experience with OpenLDAP to address that directly. What I can do is suggest an alternative solution for #1. It's trivial to mount a difference disk partion at `/var/lib/ldap`, both through the `mount` command and through `fstab`. This should effectively accomplish your goal, whether or not OpenLDAP handles this natively. You might also be able to replace the `/var/lib/ldap` folder with a symlink to the desired location. Again, this bypasses OpenLDAP and any support that is or is not built into that project. Finally, you should also think about preserving write access for certain log areas. The techniques in the paragraph above can work for moving log file locations, too.
846,748
I'm running an openLDAP server version 2.4.40 on CentOS 7. LDAP is going to be configured using online conf option (olc). Thanks to this [question](https://stackoverflow.com/questions/17669586/where-is-my-data-directories-store-by-slapd-openldap-on-ubuntu), I know that slapd's database files are in `/var/lib/ldap`. I'm trying to run an openLDAP server on a linux box as read-only OS partition and another partition for persistent data. I will be able to install and configure openLDAP on the OS partition, but will lose access to it after configuring it. **Question:** Is it possible to change the location LDAP reads/writes data from */var/lib/ldap* to somewhere on the persistent data partition?
2017/04/26
[ "https://serverfault.com/questions/846748", "https://serverfault.com", "https://serverfault.com/users/405449/" ]
I used to move the default database of openldap after each new setup. The steps I do when I want to move a database : * Stop `slapd` ``` sudo service slapd stop ``` * `slapcat` the content of the `cn=config` branch in a LDIF file ``` sudo slapcat -b cn=config > /tmp/config.ldif ``` * Copy the `/var/lib/ldap` directory wherever you want it * Make sure the user `openldap` owns the new directory and all the files inside * Edit the previously exported LDIF to modify the `olcDbDirectory` to the new location * Import the LDIF (Make sure the `/etc/ldap/slapd.d` is empty before doing this) ``` sudo rm -r /etc/ldap/slapd.d/* sudo slapadd -F /etc/ldap/slapd.d -b cn=config -l /tmp/config.ldif ``` * Make sure the `/etc/ldap/slapd.d` and all its content is owned by `openldap` ``` sudo chown -R openldap:openldap /etc/ldap/slapd.d/ ``` * Edit needed configuration to allow Slapd to use this new database directory For example, with `apparmor`, edit the file `/etc/apparmor.d/usr.sbin.slapd` and add the following lines: ``` /path/to/new/db/ r, /path/to/new/db/** rwk, ``` * Restart apparmor and slapd ``` sudo service apparmor restart sudo service slapd start ``` Usually it does the trick. It's also how I backup the configuration of my openldap instances.
Openldap does not appear to support moving a database, DB, file after it has been created. Openldap does not currently support deleting DB files either. It is possible to create a new DB file and define its olcDbDirectory attribute to a path on another partition. ``` dn: olcDatabase=bdb,cn=config objectClass: olcBdbConfig olcDatabase: bdb olcDbDirectory: /partition/db/new-db-file olcSuffix: dc=example,dc=net ``` Information found in ch 6.1.1.4.5 [Add/Delete Databases using OLC](http://www.zytrax.com/books/ldap/ch6/slapd-config.html#use-databases)
846,748
I'm running an openLDAP server version 2.4.40 on CentOS 7. LDAP is going to be configured using online conf option (olc). Thanks to this [question](https://stackoverflow.com/questions/17669586/where-is-my-data-directories-store-by-slapd-openldap-on-ubuntu), I know that slapd's database files are in `/var/lib/ldap`. I'm trying to run an openLDAP server on a linux box as read-only OS partition and another partition for persistent data. I will be able to install and configure openLDAP on the OS partition, but will lose access to it after configuring it. **Question:** Is it possible to change the location LDAP reads/writes data from */var/lib/ldap* to somewhere on the persistent data partition?
2017/04/26
[ "https://serverfault.com/questions/846748", "https://serverfault.com", "https://serverfault.com/users/405449/" ]
I've done this successfully and used it in AWS to retain my data when I have to refresh the machine image. If you've rebuilt OpenLDAP with the ``` slaptest -f slapd.conf -F slapd.d ``` command (yes, we're still using the old way of config, but running it with `slapd.d` —I'm working on it) then really all you have to do is modify the directory location in the database configuration section of slapd.conf ``` directory /data/ldap ``` Create the `DB_CONFIG` file (`chown` to `ldap:ldap`) in `/data/ldap` because LDAP will yell if it's not there. Once you run the `slaptest` command (`slaptest -f slapd.conf -F slapd.d`), your DB will be created there. You'll probably need to `chown -R ldap:ldap /data` and `/etc/openldap` once you're done with the `slaptest` commmand. If this is successful your DB or DBs will be located in `/data/ldap` Save your `slapd.conf` file on your external partition so you can import it back when you set up another server. When you need to spin up another server, import the `slapd.conf` file and run the slaptest command. You'll have to `chown -R ldap:ldap` to `/data` and `/etc/openldap` again, but when you start openldap, it should pick up the DBs on the external partition. This is a solution in flux right now, but it's serving us well in standing up OpenLDAP in the cloud. We will obviously streamline this awkward process. We'll script all the things, maybe move `/etc/openldap` to a symlinked external drive, and modify the `slapd.d` with `ldifs` only instead of relying on the deprecated `slapd.conf`, but for now it's working fine.
Openldap does not appear to support moving a database, DB, file after it has been created. Openldap does not currently support deleting DB files either. It is possible to create a new DB file and define its olcDbDirectory attribute to a path on another partition. ``` dn: olcDatabase=bdb,cn=config objectClass: olcBdbConfig olcDatabase: bdb olcDbDirectory: /partition/db/new-db-file olcSuffix: dc=example,dc=net ``` Information found in ch 6.1.1.4.5 [Add/Delete Databases using OLC](http://www.zytrax.com/books/ldap/ch6/slapd-config.html#use-databases)
846,748
I'm running an openLDAP server version 2.4.40 on CentOS 7. LDAP is going to be configured using online conf option (olc). Thanks to this [question](https://stackoverflow.com/questions/17669586/where-is-my-data-directories-store-by-slapd-openldap-on-ubuntu), I know that slapd's database files are in `/var/lib/ldap`. I'm trying to run an openLDAP server on a linux box as read-only OS partition and another partition for persistent data. I will be able to install and configure openLDAP on the OS partition, but will lose access to it after configuring it. **Question:** Is it possible to change the location LDAP reads/writes data from */var/lib/ldap* to somewhere on the persistent data partition?
2017/04/26
[ "https://serverfault.com/questions/846748", "https://serverfault.com", "https://serverfault.com/users/405449/" ]
I used to move the default database of openldap after each new setup. The steps I do when I want to move a database : * Stop `slapd` ``` sudo service slapd stop ``` * `slapcat` the content of the `cn=config` branch in a LDIF file ``` sudo slapcat -b cn=config > /tmp/config.ldif ``` * Copy the `/var/lib/ldap` directory wherever you want it * Make sure the user `openldap` owns the new directory and all the files inside * Edit the previously exported LDIF to modify the `olcDbDirectory` to the new location * Import the LDIF (Make sure the `/etc/ldap/slapd.d` is empty before doing this) ``` sudo rm -r /etc/ldap/slapd.d/* sudo slapadd -F /etc/ldap/slapd.d -b cn=config -l /tmp/config.ldif ``` * Make sure the `/etc/ldap/slapd.d` and all its content is owned by `openldap` ``` sudo chown -R openldap:openldap /etc/ldap/slapd.d/ ``` * Edit needed configuration to allow Slapd to use this new database directory For example, with `apparmor`, edit the file `/etc/apparmor.d/usr.sbin.slapd` and add the following lines: ``` /path/to/new/db/ r, /path/to/new/db/** rwk, ``` * Restart apparmor and slapd ``` sudo service apparmor restart sudo service slapd start ``` Usually it does the trick. It's also how I backup the configuration of my openldap instances.
I've done this successfully and used it in AWS to retain my data when I have to refresh the machine image. If you've rebuilt OpenLDAP with the ``` slaptest -f slapd.conf -F slapd.d ``` command (yes, we're still using the old way of config, but running it with `slapd.d` —I'm working on it) then really all you have to do is modify the directory location in the database configuration section of slapd.conf ``` directory /data/ldap ``` Create the `DB_CONFIG` file (`chown` to `ldap:ldap`) in `/data/ldap` because LDAP will yell if it's not there. Once you run the `slaptest` command (`slaptest -f slapd.conf -F slapd.d`), your DB will be created there. You'll probably need to `chown -R ldap:ldap /data` and `/etc/openldap` once you're done with the `slaptest` commmand. If this is successful your DB or DBs will be located in `/data/ldap` Save your `slapd.conf` file on your external partition so you can import it back when you set up another server. When you need to spin up another server, import the `slapd.conf` file and run the slaptest command. You'll have to `chown -R ldap:ldap` to `/data` and `/etc/openldap` again, but when you start openldap, it should pick up the DBs on the external partition. This is a solution in flux right now, but it's serving us well in standing up OpenLDAP in the cloud. We will obviously streamline this awkward process. We'll script all the things, maybe move `/etc/openldap` to a symlinked external drive, and modify the `slapd.d` with `ldifs` only instead of relying on the deprecated `slapd.conf`, but for now it's working fine.
1,539,772
I am trying to `move` folder and files from one location to another on the same mapped network drive. I have used ROBOCOPY and XCOPY. However, they copy and then delete the files. My files can be over 50GB, thus I want to MOVE. ``` move "P:\public\video\recording\123\*.*" "P:\public\video\recording\" move /S "P:\public\video\recording\123\*.*" "P:\public\video\recording\" move "P:\public\video\recording\123\*" "P:\public\video\recording\" move "P:\public\video\recording\123\*" "P:\public\video\recording." ``` **None of the above work**. I am not sure if it is possible? I have tried so many different variations with no success. Additional information Okay, reading the comments, this command working on a network share? I have noticed the follow: 1. When moving only files, the script moves them, not copies them. Tested with a 40GB file. 2. When you have folders with files, it copies and then deletes them after. These are my observations thus far.
2020/04/07
[ "https://superuser.com/questions/1539772", "https://superuser.com", "https://superuser.com/users/118319/" ]
**Yet another update:** Works in Windows 11 too. **Update:** Works in Windows 10 version 21H1 too. Original answer: As of Windows 10 version 2004, you can do the following to remove the "Share with Skype" from the context menu: 1. Run the following `REG ADD` command in an elevated cmd: ``` REG ADD "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked" /v {776DBC8D-7347-478C-8D71-791E12EF49D8} /d Skype ``` 2. Restart the Explorer process through Task Manager to see the effect. You do not need to restart Windows. \* Based on the answer given by [Ajasja](https://superuser.com/a/1569321/401935). So all credits go to him. I merely created the REG command.
Just a reminder, that uninstalling Skype will of course also fix the issue.
1,539,772
I am trying to `move` folder and files from one location to another on the same mapped network drive. I have used ROBOCOPY and XCOPY. However, they copy and then delete the files. My files can be over 50GB, thus I want to MOVE. ``` move "P:\public\video\recording\123\*.*" "P:\public\video\recording\" move /S "P:\public\video\recording\123\*.*" "P:\public\video\recording\" move "P:\public\video\recording\123\*" "P:\public\video\recording\" move "P:\public\video\recording\123\*" "P:\public\video\recording." ``` **None of the above work**. I am not sure if it is possible? I have tried so many different variations with no success. Additional information Okay, reading the comments, this command working on a network share? I have noticed the follow: 1. When moving only files, the script moves them, not copies them. Tested with a 40GB file. 2. When you have folders with files, it copies and then deletes them after. These are my observations thus far.
2020/04/07
[ "https://superuser.com/questions/1539772", "https://superuser.com", "https://superuser.com/users/118319/" ]
In case you are using the Skype App, removing the context menu item is trickier. One way is to delete `DllPath` under ``` HKEY_CLASSES_ROOT\PackagedCom\Package\Microsoft.SkypeApp_15.61.100.0_x86__kzf8qxf38zg5c\Class\{776DBC8D-7347-478C-8D71-791E12EF49D8} ``` However updates to the app will probably restore this. Adding the following `REG_SZ` key `"{776DBC8D-7347-478C-8D71-791E12EF49D8}"="Skype"` to `[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked]` is probably a good idea. Restart Windows to take effect. [![Blocking Skype Explorer extension](https://i.stack.imgur.com/FCk0d.png)](https://i.stack.imgur.com/FCk0d.png) ---
The location has changed to: ``` Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Classes\PackagedCom\Package\Microsoft.SkypeApp_15.61.87.0_x86__kzf8qxf38zg5c\Class\{776DBC8D-7347-478C-8D71-791E12EF49D8} ``` Manually delete the `DllPath` value in the Registry Editor. Note that as the application updates it may change so take note of the path and look for a similaur GUID.
1,539,772
I am trying to `move` folder and files from one location to another on the same mapped network drive. I have used ROBOCOPY and XCOPY. However, they copy and then delete the files. My files can be over 50GB, thus I want to MOVE. ``` move "P:\public\video\recording\123\*.*" "P:\public\video\recording\" move /S "P:\public\video\recording\123\*.*" "P:\public\video\recording\" move "P:\public\video\recording\123\*" "P:\public\video\recording\" move "P:\public\video\recording\123\*" "P:\public\video\recording." ``` **None of the above work**. I am not sure if it is possible? I have tried so many different variations with no success. Additional information Okay, reading the comments, this command working on a network share? I have noticed the follow: 1. When moving only files, the script moves them, not copies them. Tested with a 40GB file. 2. When you have folders with files, it copies and then deletes them after. These are my observations thus far.
2020/04/07
[ "https://superuser.com/questions/1539772", "https://superuser.com", "https://superuser.com/users/118319/" ]
There are two main entries for "Share with Skype" in registry. * To disable one from `Skype for Desktop` use following `.reg` file: ``` Windows Registry Editor Version 5.00 [HKEY_CLASSES_ROOT\*\shell\ShareWithSkype] "LegacyDisable"="" ``` Method above survives reinstall. It also survives install if `.reg` file is merged before installation, so hopefully will survive updates too. Deleting Skype via Control Panel also wipes this tweak, so manual reinstall requires `.reg` file to be merged again after deletion/installation. * To disable another one from `Skype for Windows 10` use following `.reg` file: ``` Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked] "{776DBC8D-7347-478C-8D71-791E12EF49D8}"="Skype" ```
The location has changed to: ``` Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Classes\PackagedCom\Package\Microsoft.SkypeApp_15.61.87.0_x86__kzf8qxf38zg5c\Class\{776DBC8D-7347-478C-8D71-791E12EF49D8} ``` Manually delete the `DllPath` value in the Registry Editor. Note that as the application updates it may change so take note of the path and look for a similaur GUID.
1,539,772
I am trying to `move` folder and files from one location to another on the same mapped network drive. I have used ROBOCOPY and XCOPY. However, they copy and then delete the files. My files can be over 50GB, thus I want to MOVE. ``` move "P:\public\video\recording\123\*.*" "P:\public\video\recording\" move /S "P:\public\video\recording\123\*.*" "P:\public\video\recording\" move "P:\public\video\recording\123\*" "P:\public\video\recording\" move "P:\public\video\recording\123\*" "P:\public\video\recording." ``` **None of the above work**. I am not sure if it is possible? I have tried so many different variations with no success. Additional information Okay, reading the comments, this command working on a network share? I have noticed the follow: 1. When moving only files, the script moves them, not copies them. Tested with a 40GB file. 2. When you have folders with files, it copies and then deletes them after. These are my observations thus far.
2020/04/07
[ "https://superuser.com/questions/1539772", "https://superuser.com", "https://superuser.com/users/118319/" ]
On Windows 8 (and Windows 10?), RegEdit found the entry at `HKEY_CLASSES_ROOT\*\shell\ShareWithSkype` Deleted that, and the item disappeared from the context menu immediately - no need to reboot / log out. No need to mess with [ShellExView 2.01](https://www.nirsoft.net/utils/shexview.html) because Skype did not show up there anyway.
Just a reminder, that uninstalling Skype will of course also fix the issue.
1,539,772
I am trying to `move` folder and files from one location to another on the same mapped network drive. I have used ROBOCOPY and XCOPY. However, they copy and then delete the files. My files can be over 50GB, thus I want to MOVE. ``` move "P:\public\video\recording\123\*.*" "P:\public\video\recording\" move /S "P:\public\video\recording\123\*.*" "P:\public\video\recording\" move "P:\public\video\recording\123\*" "P:\public\video\recording\" move "P:\public\video\recording\123\*" "P:\public\video\recording." ``` **None of the above work**. I am not sure if it is possible? I have tried so many different variations with no success. Additional information Okay, reading the comments, this command working on a network share? I have noticed the follow: 1. When moving only files, the script moves them, not copies them. Tested with a 40GB file. 2. When you have folders with files, it copies and then deletes them after. These are my observations thus far.
2020/04/07
[ "https://superuser.com/questions/1539772", "https://superuser.com", "https://superuser.com/users/118319/" ]
On Windows 8 (and Windows 10?), RegEdit found the entry at `HKEY_CLASSES_ROOT\*\shell\ShareWithSkype` Deleted that, and the item disappeared from the context menu immediately - no need to reboot / log out. No need to mess with [ShellExView 2.01](https://www.nirsoft.net/utils/shexview.html) because Skype did not show up there anyway.
The location has changed to: ``` Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Classes\PackagedCom\Package\Microsoft.SkypeApp_15.61.87.0_x86__kzf8qxf38zg5c\Class\{776DBC8D-7347-478C-8D71-791E12EF49D8} ``` Manually delete the `DllPath` value in the Registry Editor. Note that as the application updates it may change so take note of the path and look for a similaur GUID.
1,539,772
I am trying to `move` folder and files from one location to another on the same mapped network drive. I have used ROBOCOPY and XCOPY. However, they copy and then delete the files. My files can be over 50GB, thus I want to MOVE. ``` move "P:\public\video\recording\123\*.*" "P:\public\video\recording\" move /S "P:\public\video\recording\123\*.*" "P:\public\video\recording\" move "P:\public\video\recording\123\*" "P:\public\video\recording\" move "P:\public\video\recording\123\*" "P:\public\video\recording." ``` **None of the above work**. I am not sure if it is possible? I have tried so many different variations with no success. Additional information Okay, reading the comments, this command working on a network share? I have noticed the follow: 1. When moving only files, the script moves them, not copies them. Tested with a 40GB file. 2. When you have folders with files, it copies and then deletes them after. These are my observations thus far.
2020/04/07
[ "https://superuser.com/questions/1539772", "https://superuser.com", "https://superuser.com/users/118319/" ]
In case you are using the Skype App, removing the context menu item is trickier. One way is to delete `DllPath` under ``` HKEY_CLASSES_ROOT\PackagedCom\Package\Microsoft.SkypeApp_15.61.100.0_x86__kzf8qxf38zg5c\Class\{776DBC8D-7347-478C-8D71-791E12EF49D8} ``` However updates to the app will probably restore this. Adding the following `REG_SZ` key `"{776DBC8D-7347-478C-8D71-791E12EF49D8}"="Skype"` to `[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked]` is probably a good idea. Restart Windows to take effect. [![Blocking Skype Explorer extension](https://i.stack.imgur.com/FCk0d.png)](https://i.stack.imgur.com/FCk0d.png) ---
There are two main entries for "Share with Skype" in registry. * To disable one from `Skype for Desktop` use following `.reg` file: ``` Windows Registry Editor Version 5.00 [HKEY_CLASSES_ROOT\*\shell\ShareWithSkype] "LegacyDisable"="" ``` Method above survives reinstall. It also survives install if `.reg` file is merged before installation, so hopefully will survive updates too. Deleting Skype via Control Panel also wipes this tweak, so manual reinstall requires `.reg` file to be merged again after deletion/installation. * To disable another one from `Skype for Windows 10` use following `.reg` file: ``` Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked] "{776DBC8D-7347-478C-8D71-791E12EF49D8}"="Skype" ```
1,539,772
I am trying to `move` folder and files from one location to another on the same mapped network drive. I have used ROBOCOPY and XCOPY. However, they copy and then delete the files. My files can be over 50GB, thus I want to MOVE. ``` move "P:\public\video\recording\123\*.*" "P:\public\video\recording\" move /S "P:\public\video\recording\123\*.*" "P:\public\video\recording\" move "P:\public\video\recording\123\*" "P:\public\video\recording\" move "P:\public\video\recording\123\*" "P:\public\video\recording." ``` **None of the above work**. I am not sure if it is possible? I have tried so many different variations with no success. Additional information Okay, reading the comments, this command working on a network share? I have noticed the follow: 1. When moving only files, the script moves them, not copies them. Tested with a 40GB file. 2. When you have folders with files, it copies and then deletes them after. These are my observations thus far.
2020/04/07
[ "https://superuser.com/questions/1539772", "https://superuser.com", "https://superuser.com/users/118319/" ]
**Yet another update:** Works in Windows 11 too. **Update:** Works in Windows 10 version 21H1 too. Original answer: As of Windows 10 version 2004, you can do the following to remove the "Share with Skype" from the context menu: 1. Run the following `REG ADD` command in an elevated cmd: ``` REG ADD "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked" /v {776DBC8D-7347-478C-8D71-791E12EF49D8} /d Skype ``` 2. Restart the Explorer process through Task Manager to see the effect. You do not need to restart Windows. \* Based on the answer given by [Ajasja](https://superuser.com/a/1569321/401935). So all credits go to him. I merely created the REG command.
There are two main entries for "Share with Skype" in registry. * To disable one from `Skype for Desktop` use following `.reg` file: ``` Windows Registry Editor Version 5.00 [HKEY_CLASSES_ROOT\*\shell\ShareWithSkype] "LegacyDisable"="" ``` Method above survives reinstall. It also survives install if `.reg` file is merged before installation, so hopefully will survive updates too. Deleting Skype via Control Panel also wipes this tweak, so manual reinstall requires `.reg` file to be merged again after deletion/installation. * To disable another one from `Skype for Windows 10` use following `.reg` file: ``` Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked] "{776DBC8D-7347-478C-8D71-791E12EF49D8}"="Skype" ```
1,539,772
I am trying to `move` folder and files from one location to another on the same mapped network drive. I have used ROBOCOPY and XCOPY. However, they copy and then delete the files. My files can be over 50GB, thus I want to MOVE. ``` move "P:\public\video\recording\123\*.*" "P:\public\video\recording\" move /S "P:\public\video\recording\123\*.*" "P:\public\video\recording\" move "P:\public\video\recording\123\*" "P:\public\video\recording\" move "P:\public\video\recording\123\*" "P:\public\video\recording." ``` **None of the above work**. I am not sure if it is possible? I have tried so many different variations with no success. Additional information Okay, reading the comments, this command working on a network share? I have noticed the follow: 1. When moving only files, the script moves them, not copies them. Tested with a 40GB file. 2. When you have folders with files, it copies and then deletes them after. These are my observations thus far.
2020/04/07
[ "https://superuser.com/questions/1539772", "https://superuser.com", "https://superuser.com/users/118319/" ]
There are two main entries for "Share with Skype" in registry. * To disable one from `Skype for Desktop` use following `.reg` file: ``` Windows Registry Editor Version 5.00 [HKEY_CLASSES_ROOT\*\shell\ShareWithSkype] "LegacyDisable"="" ``` Method above survives reinstall. It also survives install if `.reg` file is merged before installation, so hopefully will survive updates too. Deleting Skype via Control Panel also wipes this tweak, so manual reinstall requires `.reg` file to be merged again after deletion/installation. * To disable another one from `Skype for Windows 10` use following `.reg` file: ``` Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked] "{776DBC8D-7347-478C-8D71-791E12EF49D8}"="Skype" ```
Just a reminder, that uninstalling Skype will of course also fix the issue.
1,539,772
I am trying to `move` folder and files from one location to another on the same mapped network drive. I have used ROBOCOPY and XCOPY. However, they copy and then delete the files. My files can be over 50GB, thus I want to MOVE. ``` move "P:\public\video\recording\123\*.*" "P:\public\video\recording\" move /S "P:\public\video\recording\123\*.*" "P:\public\video\recording\" move "P:\public\video\recording\123\*" "P:\public\video\recording\" move "P:\public\video\recording\123\*" "P:\public\video\recording." ``` **None of the above work**. I am not sure if it is possible? I have tried so many different variations with no success. Additional information Okay, reading the comments, this command working on a network share? I have noticed the follow: 1. When moving only files, the script moves them, not copies them. Tested with a 40GB file. 2. When you have folders with files, it copies and then deletes them after. These are my observations thus far.
2020/04/07
[ "https://superuser.com/questions/1539772", "https://superuser.com", "https://superuser.com/users/118319/" ]
In case you are using the Skype App, removing the context menu item is trickier. One way is to delete `DllPath` under ``` HKEY_CLASSES_ROOT\PackagedCom\Package\Microsoft.SkypeApp_15.61.100.0_x86__kzf8qxf38zg5c\Class\{776DBC8D-7347-478C-8D71-791E12EF49D8} ``` However updates to the app will probably restore this. Adding the following `REG_SZ` key `"{776DBC8D-7347-478C-8D71-791E12EF49D8}"="Skype"` to `[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked]` is probably a good idea. Restart Windows to take effect. [![Blocking Skype Explorer extension](https://i.stack.imgur.com/FCk0d.png)](https://i.stack.imgur.com/FCk0d.png) ---
Just a reminder, that uninstalling Skype will of course also fix the issue.
1,539,772
I am trying to `move` folder and files from one location to another on the same mapped network drive. I have used ROBOCOPY and XCOPY. However, they copy and then delete the files. My files can be over 50GB, thus I want to MOVE. ``` move "P:\public\video\recording\123\*.*" "P:\public\video\recording\" move /S "P:\public\video\recording\123\*.*" "P:\public\video\recording\" move "P:\public\video\recording\123\*" "P:\public\video\recording\" move "P:\public\video\recording\123\*" "P:\public\video\recording." ``` **None of the above work**. I am not sure if it is possible? I have tried so many different variations with no success. Additional information Okay, reading the comments, this command working on a network share? I have noticed the follow: 1. When moving only files, the script moves them, not copies them. Tested with a 40GB file. 2. When you have folders with files, it copies and then deletes them after. These are my observations thus far.
2020/04/07
[ "https://superuser.com/questions/1539772", "https://superuser.com", "https://superuser.com/users/118319/" ]
In case you are using the Skype App, removing the context menu item is trickier. One way is to delete `DllPath` under ``` HKEY_CLASSES_ROOT\PackagedCom\Package\Microsoft.SkypeApp_15.61.100.0_x86__kzf8qxf38zg5c\Class\{776DBC8D-7347-478C-8D71-791E12EF49D8} ``` However updates to the app will probably restore this. Adding the following `REG_SZ` key `"{776DBC8D-7347-478C-8D71-791E12EF49D8}"="Skype"` to `[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked]` is probably a good idea. Restart Windows to take effect. [![Blocking Skype Explorer extension](https://i.stack.imgur.com/FCk0d.png)](https://i.stack.imgur.com/FCk0d.png) ---
**Yet another update:** Works in Windows 11 too. **Update:** Works in Windows 10 version 21H1 too. Original answer: As of Windows 10 version 2004, you can do the following to remove the "Share with Skype" from the context menu: 1. Run the following `REG ADD` command in an elevated cmd: ``` REG ADD "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked" /v {776DBC8D-7347-478C-8D71-791E12EF49D8} /d Skype ``` 2. Restart the Explorer process through Task Manager to see the effect. You do not need to restart Windows. \* Based on the answer given by [Ajasja](https://superuser.com/a/1569321/401935). So all credits go to him. I merely created the REG command.
59,729,547
I have a series of bat files that I want to run in parallel, for example: ``` start program1_1.bat start program1_2.bat start program1_3.bat wait until program1 finished then start program2_1.bat start program2_2.bat start program2_3.bat wait until program2 finished then ... ``` So far, what I've tried is this [function](https://stackoverflow.com/questions/41584281/how-to-run-three-batch-files-in-parallel-and-run-another-three-batch-files-after): ``` :waitForFinish set counter=0 for /f %%i in ('tasklist /NH /FI "Imagename eq cmd.exe') do set /a counter=counter+1 if counter GTR 2 Goto waitForFinish ``` But it just launched the first 3 bat files and stop... How can I solve this problem? Thanks, EDIT: This is the content of `program1_i.bat` file: ``` program1.exe input_i.txt ``` It will run program1.exe for each input file. The same for `program2_i.bat`.
2020/01/14
[ "https://Stackoverflow.com/questions/59729547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11369131/" ]
**\* *Update* \*** The solution provided [here](https://stackoverflow.com/a/33585114/12343998) works nicely to achieve parallel running of subprograms without needing user entry (pause) or a fixed length Timeout between program groups. Combined with the original answer: ``` @echo off :controller Call :launcher "program1_1.bat" "program1_2.bat" "program1_3.bat" Call :launcher "program2_1.bat" "program2_2.bat" "program2_3.bat" pause EXIT :launcher For %%a in (%*) Do ( Start "+++batch+++" "%%~a" ) :loop timeout /t 1 >nul tasklist /fi "windowtitle eq +++batch+++*" |find "cmd.exe" >nul && goto :loop GOTO :EOF ``` --- ***Original Answer:*** This is a simple way to ensure each group of programs is finished before the next. The fault in the tasklist method is that if there's other cmd.exe processes running, the If condition may not be true when expected, causing the script to hang. The start /wait option is not ideal, as you intend on running multiple programs simultaneously - and if the subprogram you wait on finishes before the other subs, you're back to square 1. ``` @echo off :controller Call :launcher "program1_1.bat" "program1_2.bat" "program1_3.bat" Call :launcher "program2_1.bat" "program2_2.bat" "program2_3.bat" pause EXIT :launcher For %%a in (%*) Do ( Start "" "%%~a" ) pause GOTO :EOF ```
Try `/WAIT` switch on `start` command. I guess if you wrap bats into script called with wait switch, it could work.
59,729,547
I have a series of bat files that I want to run in parallel, for example: ``` start program1_1.bat start program1_2.bat start program1_3.bat wait until program1 finished then start program2_1.bat start program2_2.bat start program2_3.bat wait until program2 finished then ... ``` So far, what I've tried is this [function](https://stackoverflow.com/questions/41584281/how-to-run-three-batch-files-in-parallel-and-run-another-three-batch-files-after): ``` :waitForFinish set counter=0 for /f %%i in ('tasklist /NH /FI "Imagename eq cmd.exe') do set /a counter=counter+1 if counter GTR 2 Goto waitForFinish ``` But it just launched the first 3 bat files and stop... How can I solve this problem? Thanks, EDIT: This is the content of `program1_i.bat` file: ``` program1.exe input_i.txt ``` It will run program1.exe for each input file. The same for `program2_i.bat`.
2020/01/14
[ "https://Stackoverflow.com/questions/59729547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11369131/" ]
Your question is a little vague on the exact expected results. I am however assuming that you want to do something like this. ``` start /wait program1_1.bat | start /wait program1_2.bat | start /wait program1_3.bat start /wait program2_1.bat | start /wait program2_2.bat | start /wait program2_3.bat ``` The single pipe separators let's us launch the first three commands in parallel and only start the next three commands once the first three has all completed, simply because the next 3 commands are in the next `batch` line the use of `start /wait`
Try `/WAIT` switch on `start` command. I guess if you wrap bats into script called with wait switch, it could work.
59,729,547
I have a series of bat files that I want to run in parallel, for example: ``` start program1_1.bat start program1_2.bat start program1_3.bat wait until program1 finished then start program2_1.bat start program2_2.bat start program2_3.bat wait until program2 finished then ... ``` So far, what I've tried is this [function](https://stackoverflow.com/questions/41584281/how-to-run-three-batch-files-in-parallel-and-run-another-three-batch-files-after): ``` :waitForFinish set counter=0 for /f %%i in ('tasklist /NH /FI "Imagename eq cmd.exe') do set /a counter=counter+1 if counter GTR 2 Goto waitForFinish ``` But it just launched the first 3 bat files and stop... How can I solve this problem? Thanks, EDIT: This is the content of `program1_i.bat` file: ``` program1.exe input_i.txt ``` It will run program1.exe for each input file. The same for `program2_i.bat`.
2020/01/14
[ "https://Stackoverflow.com/questions/59729547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11369131/" ]
Ok, here is what worked for me: ``` @echo off setlocal enableextensions enabledelayedexpansion call :InitDos start program1_1.bat start program1_2.bat start program1_3.bat call :waitForFinish start program2_1.bat start program2_2.bat start program2_3.bat call :waitForFinish Goto:eof : waitForFinish set /a counter=0 for /f %%i in ('tasklist /NH /FI "Imagename eq cmd.exe"') do ( set /a counter+=1 ) if !counter! GTR !init_count! Goto waitForFinish goto :eof : InitDos set /a init_count=0 for /f %%i in ('tasklist /NH /FI "Imagename eq cmd.exe"') do ( set /a init_count+=1 ) goto :eof ```
Try `/WAIT` switch on `start` command. I guess if you wrap bats into script called with wait switch, it could work.
59,729,547
I have a series of bat files that I want to run in parallel, for example: ``` start program1_1.bat start program1_2.bat start program1_3.bat wait until program1 finished then start program2_1.bat start program2_2.bat start program2_3.bat wait until program2 finished then ... ``` So far, what I've tried is this [function](https://stackoverflow.com/questions/41584281/how-to-run-three-batch-files-in-parallel-and-run-another-three-batch-files-after): ``` :waitForFinish set counter=0 for /f %%i in ('tasklist /NH /FI "Imagename eq cmd.exe') do set /a counter=counter+1 if counter GTR 2 Goto waitForFinish ``` But it just launched the first 3 bat files and stop... How can I solve this problem? Thanks, EDIT: This is the content of `program1_i.bat` file: ``` program1.exe input_i.txt ``` It will run program1.exe for each input file. The same for `program2_i.bat`.
2020/01/14
[ "https://Stackoverflow.com/questions/59729547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11369131/" ]
Your question is a little vague on the exact expected results. I am however assuming that you want to do something like this. ``` start /wait program1_1.bat | start /wait program1_2.bat | start /wait program1_3.bat start /wait program2_1.bat | start /wait program2_2.bat | start /wait program2_3.bat ``` The single pipe separators let's us launch the first three commands in parallel and only start the next three commands once the first three has all completed, simply because the next 3 commands are in the next `batch` line the use of `start /wait`
**\* *Update* \*** The solution provided [here](https://stackoverflow.com/a/33585114/12343998) works nicely to achieve parallel running of subprograms without needing user entry (pause) or a fixed length Timeout between program groups. Combined with the original answer: ``` @echo off :controller Call :launcher "program1_1.bat" "program1_2.bat" "program1_3.bat" Call :launcher "program2_1.bat" "program2_2.bat" "program2_3.bat" pause EXIT :launcher For %%a in (%*) Do ( Start "+++batch+++" "%%~a" ) :loop timeout /t 1 >nul tasklist /fi "windowtitle eq +++batch+++*" |find "cmd.exe" >nul && goto :loop GOTO :EOF ``` --- ***Original Answer:*** This is a simple way to ensure each group of programs is finished before the next. The fault in the tasklist method is that if there's other cmd.exe processes running, the If condition may not be true when expected, causing the script to hang. The start /wait option is not ideal, as you intend on running multiple programs simultaneously - and if the subprogram you wait on finishes before the other subs, you're back to square 1. ``` @echo off :controller Call :launcher "program1_1.bat" "program1_2.bat" "program1_3.bat" Call :launcher "program2_1.bat" "program2_2.bat" "program2_3.bat" pause EXIT :launcher For %%a in (%*) Do ( Start "" "%%~a" ) pause GOTO :EOF ```
59,729,547
I have a series of bat files that I want to run in parallel, for example: ``` start program1_1.bat start program1_2.bat start program1_3.bat wait until program1 finished then start program2_1.bat start program2_2.bat start program2_3.bat wait until program2 finished then ... ``` So far, what I've tried is this [function](https://stackoverflow.com/questions/41584281/how-to-run-three-batch-files-in-parallel-and-run-another-three-batch-files-after): ``` :waitForFinish set counter=0 for /f %%i in ('tasklist /NH /FI "Imagename eq cmd.exe') do set /a counter=counter+1 if counter GTR 2 Goto waitForFinish ``` But it just launched the first 3 bat files and stop... How can I solve this problem? Thanks, EDIT: This is the content of `program1_i.bat` file: ``` program1.exe input_i.txt ``` It will run program1.exe for each input file. The same for `program2_i.bat`.
2020/01/14
[ "https://Stackoverflow.com/questions/59729547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11369131/" ]
Your question is a little vague on the exact expected results. I am however assuming that you want to do something like this. ``` start /wait program1_1.bat | start /wait program1_2.bat | start /wait program1_3.bat start /wait program2_1.bat | start /wait program2_2.bat | start /wait program2_3.bat ``` The single pipe separators let's us launch the first three commands in parallel and only start the next three commands once the first three has all completed, simply because the next 3 commands are in the next `batch` line the use of `start /wait`
Ok, here is what worked for me: ``` @echo off setlocal enableextensions enabledelayedexpansion call :InitDos start program1_1.bat start program1_2.bat start program1_3.bat call :waitForFinish start program2_1.bat start program2_2.bat start program2_3.bat call :waitForFinish Goto:eof : waitForFinish set /a counter=0 for /f %%i in ('tasklist /NH /FI "Imagename eq cmd.exe"') do ( set /a counter+=1 ) if !counter! GTR !init_count! Goto waitForFinish goto :eof : InitDos set /a init_count=0 for /f %%i in ('tasklist /NH /FI "Imagename eq cmd.exe"') do ( set /a init_count+=1 ) goto :eof ```
208,002
I'm new to LaTeX and I have a question about the LaTeX code (which I have to do for my essay), for the inner product of vectors on an exponential\*,how can I fix the problem that the two vektors k and x have their vectors taht are not parallel . *The vector of k is much higher that the vector in x* ( I use the command \overrightarrow for the vector, and I have also use the \displaystyle for a sum that exist in the same equation). How can I fix that? Thanks cheers :)
2014/10/19
[ "https://tex.stackexchange.com/questions/208002", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/64448/" ]
Actually, X11 is not erased but moved to /opt/X11. So, the simplest solution would probably be to manually add the symbolic link from /usr/X11 to /opt/X11: ``` sudo ln -s /opt/X11 /usr/X11 ```
Fixed after installing the latest XQuartz: <http://xquartz.macosforge.org/landing/> The problem seems to be related to the fact that X11 was erased during the upgrade.
208,002
I'm new to LaTeX and I have a question about the LaTeX code (which I have to do for my essay), for the inner product of vectors on an exponential\*,how can I fix the problem that the two vektors k and x have their vectors taht are not parallel . *The vector of k is much higher that the vector in x* ( I use the command \overrightarrow for the vector, and I have also use the \displaystyle for a sum that exist in the same equation). How can I fix that? Thanks cheers :)
2014/10/19
[ "https://tex.stackexchange.com/questions/208002", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/64448/" ]
Fixed after installing the latest XQuartz: <http://xquartz.macosforge.org/landing/> The problem seems to be related to the fact that X11 was erased during the upgrade.
I had the exact same problem with another program that was working prior to upgrading to OS X Yosemite, and then returned the following error subsequent to upgrading: ``` dyld: Library not loaded: /usr/X11/lib/libX11.6.dylib Referenced from: /Users/grosbj/LANL/MCNP5/bin/mcnp5 Reason: image not found Trace/BPT trap: 5 ``` fabianfuchs' suggestion fixed it!: ``` sudo ln -s /opt/X11 /usr/X11 ``` Thanks!