id
stringlengths
3
6
prompt
stringlengths
100
55.1k
response_j
stringlengths
30
18.4k
55706
Is it bad habit to use the same `ResultSet` object in Java? Why or why not? //It seems to be my only option here, as I am trying to query a table for its record count, and then query a view of that table; I don't know how to change the view. In other words, is ``` ResultSet myResultSet = statement.executeQuery("SELECT count(*) FROM table"); myResultSet.next(); int recordCount = myResultSet.getInt(1); myResultSet = statement.executeQuery("SELECT * FROM tableView"); //set other variables based on contents of fetched view ``` a bad idea?
The code you have posted does not "reuse the same `ResultSet`", it simply discards one `ResultSet` object and then uses the same variable to hold a reference to a different `ResultSet` created by the second `executeQuery`. It would be good coding practice to call `close()` on the first result set before you overwrite the reference with the second one, but this is not strictly necessary because > > A `ResultSet` object is automatically closed when the `Statement` object that generated it is closed, **re-executed**, or used to retrieve the next result from a sequence of multiple results. > > > (from the [ResultSet JavaDoc documentation](http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html), my bold)
55944
I am trying to get the view position (Right upper corner position and left bottom corner position) and display custom dialog right or left side of view but i am not getting exact position of view. This is my code ``` int x=view.getLeft()+ (view.getHeight()*4); int y= view.getBottom()+(view.getWidth()*2); showDialog(x,y,Gravity.TOP,Gravity.LEFT);` public void showDialog(int x, int y,int gravity_y,int gravity_x){ final Dialog dialog = new Dialog(this, R.style.ActivityDialog); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE)); dialog.setContentView(R.layout.cofirm_sell); dialog.setCanceledOnTouchOutside(false); WindowManager.LayoutParams wmlp = dialog.getWindow().getAttributes(); dialog.getWindow().getAttributes().windowAnimations=R.style.DialogTheme; wmlp.gravity = gravity_y | gravity_x; wmlp.x = x; wmlp.y = y; ImageButton close=(ImageButton)dialog.findViewById(R.id.close); close.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog.show(); ``` } I want this [![enter image description here](https://i.stack.imgur.com/HW5Cq.png)](https://i.stack.imgur.com/HW5Cq.png)
Check this: ``` int[] outLocation = new int[2]; view.getLocationOnScreen(outLocation); Rect rect = new Rect( outLocation[0], outLocation[1], outLocation[0] + view.getWidth(), outLocation[1] + view.getHeight()); //right upper corner rect.right,rect.top //left bottom corner rect.left,rect.bottom ```
56170
I have a table with two timestamp fields. I simply defined them with a name and the type `TIMESTAMP`, yet for some reason MySQL automatically set one of them with a default value and the attribute `on update CURRENT_TIMESTAMP`. I was planning on having NO default value in either of the fields, but one of the fields is called "date\_updated" so I suppose I could set the mentioned attribute to that field. Unfortunately, it's the field "date\_created" that was set with the `on update CURRENT_TIMESTAMP` attribute, and no matter what I do, MySQL won't let me remove it. I've tried editing the "date\_created" field and removing the attribute. When clicking save, the attribute is back. I have also tried selecting both fields, removing the attribute from one of them and setting it on the other. It gives me the error `#1293 - Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause` and suddenly both attribute columns on the values are set to `on update CURRENT_TIMESTAMP` the result: ``` Error SQL query: ALTER TABLE `pages` CHANGE `date_created` `date_created` TIMESTAMP NOT NULL , CHANGE `date_updated` `date_updated` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL MySQL said: #1293 - Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause ``` Must I really recreate both those columns in the correct order to fix this? I would like to know how I could solve this problem correctly, for future reference. Thanks --- Now I've also tried to run ``` ALTER TABLE pages CHANGE date_created date_created TIMESTAMP NOT NULL ```
You should specify **`DEFAULT CURRENT_TIMESTAMP`** (or `DEFAULT 0`) ``` ALTER TABLE pages CHANGE date_created date_created TIMESTAMP NOT NULL DEFAULT 0, CHANGE `date_updated` `date_updated` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL ```
56428
*Source of the problem, 3b [here](http://tenttiarkisto.fi/exams/9745.1.pdf).* > > **Problem Question** > > > Electricity density in cylinder coordinates is $\bar{J}=e^{-r^2}\bar{e}\_z$. Current creates magnetic field of the > form $\bar{H}=H(r)\bar{e}\_{\phi}$ where $H(0)=0$. Define $H(r)$ from > the maxwell equations > > > $$\nabla\times\bar{H}=\frac{1}{r}\begin{vmatrix}\bar{e}\_r & > r\bar{e}\_\phi & \bar{e}\_z \\ \partial\_r & \partial\_\phi & \partial\_z > \\ H\_r & r H\_\phi & H\_z \\ \end{vmatrix} = \bar{J}.$$ > > > So $$\begin{align} \nabla\times\bar{H} &= \frac{1}{r} \bar{e}\_r \begin{vmatrix} \partial\_\phi & \partial\_z \\ r H\_\phi & H\_z \\ \end{vmatrix} - r\bar{e}\_\phi \begin{vmatrix} \partial\_r & \partial\_z \\ H\_r & H\_z \\ \end{vmatrix} + \bar{e}\_z \begin{vmatrix} \partial\_r & \partial\_\phi \\ H\_r & r H\_\phi \\ \end{vmatrix} \\ &= \frac{1}{r} \left( \bar{e}\_r (\partial\_\phi H\_z-\partial\_z H\_\phi) - r\bar{e}\_\phi (\partial\_r H\_z-\partial\_z H\_r) + \bar{e}\_z (\partial\_r rH\_\phi-\partial\_\phi H\_r) \right). \end{align}$$ I messed the calculations here up when I tried to go back to Cartesian coordinates because it is otherwise hard for me to see the math. So I tried to think things with them $$\begin{cases} x=r\cos(\phi) \\ y=r\sin(\phi) \\ z=h \\ \end{cases}$$ but it took me many pages of erroneous calculations and I could not finish on time. Now my friend suggested the below. > > **My friend's approach which I could not understand yet or his purpose, something to do with independence** > > > $$\begin{align} H &= H(r)e\_\phi\\ &=0+H\_\phi e\_\phi+0 \end{align}$$ > > > where > > > $$\begin{cases} H\_\phi = H(r) <---\text{ independent of R}\\ H\_r = 0 > \\ H\_2 =0 \\ \end{cases}.$$ > > > Could someone explain what I am doing wrong in going back to the Cartesian? I know it is not wrong but it is extremely slow way of doing things. I am not sure whether I was meant to remember the page 817 [here](https://noppa.aalto.fi/noppa/kurssi/mat-1.1020/materiaali/Mat-1_1020_juhani_pitkaranta__tkk_n_laaja_matematiikka_ii__2007_.pdf?state%3aCourseAdditionalMaterial=BrO0ABXcgAAAAAgAAGWVkaXRVc2VyV2FudHNUb0NoYW5nZUZpbGVzcgARamF2YS5sYW5nLkJvb2xlYW7NIHKA1Zz67gIAAVoABXZhbHVleHAAdxMAABBlZGl0RGlhbG9nSGlkZGVuc3EAfgAAAQ%3D%3D) or what is really essential to solve this problem?
This service blocked my original answer with stupid two days' ban so shortly $$\nabla\times\bar{H}= \begin{pmatrix}\partial\_x \\ \partial\_y \\ \partial\_y\end{pmatrix}\times\bar{H}\not = \begin{pmatrix}\partial\_r \\ \partial\_\alpha \\ \partial\_\phi\end{pmatrix}\times\bar{H}$$ where I want to stress $$\nabla \not = \begin{pmatrix}\partial\_r \\ \partial\_\alpha \\ \partial\_\phi\end{pmatrix}.$$ Then with the WW, you will get first degree-differential equation. Sorry I am now missing all references but this was the crux point to realize, not to mix the $\nabla$ from cartesian coordinates to polar coordinates. I will update this if I can find the original answer, stupid censorship, well perhaps this is just gamification -- I lost my answer, stupid. Now I am too angry to concentrate on this junk, $\nabla$ is defined in cartesian -- to calculate mock $\nabla$ in polar coordinates you need to do some weekend calculations... (I mean to verify the conversion formula).
57081
I'm building a location app where I display background locations from a Room database in my MainActivity. I can get a ViewModel by calling ``` locationViewModel = ViewModelProviders.of(this).get(LocationViewModel.class); locationViewModel.getLocations().observe(this, this); ``` Periodic background locations should be saved to the Room database when I receive location updates via a BroadCastReceiver. They should be saved by calling `locationViewModel.getLocations().setValue()` ``` public class LocationUpdatesBroadcastReceiver extends BroadcastReceiver { static final String ACTION_PROCESS_UPDATES = "com.google.android.gms.location.sample.backgroundlocationupdates.action" + ".PROCESS_UPDATES"; @Override public void onReceive(Context context, Intent intent) { if (intent != null) { final String action = intent.getAction(); if (ACTION_PROCESS_UPDATES.equals(action)) { LocationResult result = LocationResult.extractResult(intent); if (result != null) { List<Location> locations = result.getLocations(); List<SavedLocation> locationsToSave = covertToSavedLocations(locations) //Need an instance of LocationViewModel to call locationViewModel.getLocations().setValue(locationsToSave) } } } } } ``` Question is how should I get the LocationViewModel instance in a non-activity class like this BroadcastReceiver? Is it correct to call `locationViewModel = ViewModelProviders.of(context).get(LocationViewModel.class)` where context is the context that I receive from `onReceive (Context context, Intent intent)` of the BroadcastReceiver? After getting the ViewModel, do I need to use [LiveData.observeForever](https://developer.android.com/reference/android/arch/lifecycle/LiveData#observeforever) and [LiveData.removeObserver](https://developer.android.com/reference/android/arch/lifecycle/LiveData.html#removeObserver(android.arch.lifecycle.Observer%3CT%3E)) since the BroadcastReceiver is not a LifecycleOwner?
> > Question is how should I get the LocationViewModel instance in a > non-activity class like this BroadcastReceiver? > > > You shouldn't do that. Its bad design practice. > > Is it correct to call locationViewModel = > ViewModelProviders.of(context).get(LocationViewModel.class) where > context is the context that I receive from onReceive (Context context, > Intent intent) of the BroadcastReceiver? > > > No. It won't help **You can achieve your desired outcome as follows:** Separate your Room DB operation from `ViewModel` in a separate singleton class. Use it in `ViewModel` and any other place required. When Broadcast is received, write data to DB through this singleton class rather than `ViewModel`. If you are observing for the `LiveData` in your Fragment, then it will update your views too.
57203
Trying to extend an custom element : ```js class ABC extends HTMLDivElement { connectedCallback() { console.log('ABC here') } } customElements.define("x-abc", ABC, { extends: 'div' }) class XYZ extends ABC { connectedCallback() { console.log('XYZ here') } } customElements.define("x-xyz", XYZ, { extends: 'x-abc' }) ``` ```html <div is="x-abc"></div> <div is="x-xyz"></div> ``` but getting this error : ``` Uncaught DOMException: Failed to execute 'define' on 'CustomElementRegistry': "x-abc" is a valid custom element name ``` The err is confusing because it say 'is valid', not 'is not valid' !! On the other hand FF says : ``` Uncaught DOMException: CustomElementRegistry.define: 'x-xyz' cannot extend a custom element ``` I want to build hierarchy of custom elements.
The error may sound confusing at first, but actually it is very clear. The spec clearly defines that you can only extend built-ins using the `is` syntax. As it is currently designed, using `ABC` as a base class is definitely not the brightest idea (until you drop extending `HTMLDivElement` in favour of `HTMLElement`). You have not explained why you need to extend `div` elements, which is definitely not what you typically build a component hierarchy on. It is not even (and probably never will be) supported in Safari. Instead, extend `HTMLElement`, and omit the `is`-syntax. ```js class ABC extends HTMLElement { connectedCallback() { console.log('ABC here') } } customElements.define('x-abc', ABC) class XYZ extends ABC { connectedCallback() { super.connectedCallback(); console.log('XYZ here') } } customElements.define('x-xyz', XYZ) ``` ```html <x-abc></x-abc> <x-xyz></x-xyz> ``` If for whatever strange reason you need to keep extending `HTMLDivElement` (instead of `HTMLElement` which would be the proper way), here you go: Just replace the `{extends: 'x-abc'}` part with `{extends: 'div'}`. Both your components extend `div` (their defining tag name). ```js class ABC extends HTMLDivElement { connectedCallback() { console.log('ABC here') } } customElements.define('x-abc', ABC, { extends: 'div' }) class XYZ extends ABC { connectedCallback() { super.connectedCallback(); console.log('XYZ here') } } customElements.define('x-xyz', XYZ, { extends: 'div' }) ``` ```html <div is="x-abc"></div> <div is="x-xyz"></div> ```
57206
I would like to update a field in a single feature class by a.) searching for a field where the values are not blank and b.) searching for a field where the values are blank. A typical scenario of this update would occur if there are two service requests in one feature class with the same service request number with one being updated. When the updated feature is in the feature class, it does not maintain all of the same values that the previous feature class held. The one field that I would like to update is `VehicleNam`. So if I have a feature class where SR # 555 appears twice, as OID1 and OID2, but only OID1 has a value for `VehicleNam` I would like to update the `VehicleNam` field in OID2 as well. Here is the script that I have so far, however an error is being thrown at line 5. I am using ArcGIS 10.2.2 `with arcpy.da.UpdateCursor(fc, ["VehicleNam"],"""VehicleNam <> ''""") as ucursor: with arcpy.da.SearchCursor(fc, ["VehicleNam"],"""VehicleNam = ''""") as scursor: for srow in scursor: svalue = srow[0] urow = ucursor.next() # instead of a full "for urow in ucursor" loop each time urow[0] = svalue ucursor.updateRow(urow)` `Runtime error Traceback (most recent call last): File "<string>", line 5, in <module> StopIteration`
Creating two cursors on the same feature class is going to be problematic. I'd create a dictionary of your matches first, and then iterate again and update. Something like this (untested): ``` #SR field name srField = "SR_FIELD_NAME" vehNameDi = dict ([(sr, vehNam) for sr, vehName in arcpy.da.SearchCursor (fc, [srField, "VehicleNam"],"""VehicleNam <> ''""")]) with arcpy.da.UpdateCursor(fc, [srField, "VehicleNam"],"""VehicleNam = ''""") as cursor: for sr, vehNam in cursor: if not sr in vehNameDi: continue row = (sr, vehNameDi [sr]) cursor.updateRow (row) del cursor ```
57227
Is it possible to use something like sessions like the ones in PHP in C++? In PHP they're used like ``` $_SESSION['name'] = $value; ``` I really want to make the same application using C++ as PHP...requires a run-time parser. My application written in PHP uses sessions so that i can fetch some stuff from a website(numbers) and store the value in a SESSION varible which i call last to compare it to the new value when the page is reloaded. I'd rather have the same functionality in C++. Seeing as this is going nowhere i am going to provide the PHP code ``` <?php session_start(); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,"http://dashjr.org/~luke-jr/programs/bitcoin/pool/balances.json"); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); $result=curl_exec ($ch); curl_close ($ch); echo 'Last BTC: '.$_SESSION['last'].'<br>'; $obj = json_decode($result,true); echo 'Current BTC: '; $new = (int)$obj["1Hy5h24yBYKtQ1vNGaxY5rBJSEuTiMkBkx"]["balance"]/100000000; echo $new; if((int)$_SESSION['last'] < $new) { echo '<br><br>You earned more'; } else { echo '<br><br>You earned less'; } $_SESSION['last'] = $obj["1Hy5h24yBYKtQ1vNGaxY5rBJSEuTiMkBkx"]["balance"]/100000000; unset($result,$obj); ?> ``` I need to port *that* to C++.
This makes no sense, PHP sessions are a kludge because the process does not survive one HTTP request to the next. I really dunno what do you want to achieve here. Maybe <http://www.boost.org/doc/libs/1_46_1/doc/html/interprocess.html> this?
57272
I'm using VS to encrypt some data using this function: ``` public static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes) { byte[] encryptedBytes = null; // Set your salt here, change it to meet your flavor: // The salt bytes must be at least 8 bytes. byte[] saltBytes = new byte[] { 6, 99, 26, 12, 68, 22, 89, 12, 49, 55, 92, 82, 87, 86, 10, 75, 98, 122, 73 }; using (MemoryStream ms = new MemoryStream()) { using (RijndaelManaged AES = new RijndaelManaged()) { AES.KeySize = 256; AES.BlockSize = 256; var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000); AES.Key = key.GetBytes(AES.KeySize / 8); AES.IV = key.GetBytes(AES.BlockSize / 8); AES.Mode = CipherMode.CBC; using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length); cs.Close(); } encryptedBytes = ms.ToArray(); } } return encryptedBytes; } ``` My question is why when I put plain text to encrypt the output only contains readable characters that can be viewed with any text processor like notepad, but, if the data to encrypt is from a file containing special characters the output now also contains special characters that can't be viewed from text processor... why??? Example of encrypt "hello" "fMIiLZzIKME2gTAarpQqP7y8kOjQvDS12lSOOBtaCbI=" Example of encrypt binary data: "b!,˜à4ovƒº1úlÔÊ jô†õ ;>²Ñ)j¦¹‘åüLÖN—nU+5"
After `onHide` didn't worked, I found a workaround using getter/setter like: In my child component: ``` private _showDialog: boolean = false; set showDialog(_show: boolean) { let result: boolean = this._showDialog != _show; if (result == true) { this._showDialog = _show; this.onCloseDialog.emit({ hasChanges: this.hasChanges, state: this._showDialog }); } } get showDialog(): boolean{ return this._showDialog; } ``` And in parent template: ``` <!--View Car Colors Dialog In Parent Component--> <view-car-colors [showDialog]="showCarColorsDialog" (onCloseDialog)="onCarColorsCloseDialog($event)"></view-car-colors> ``` In Component, I receive the emit event: ``` private onCarColorsCloseDialog($event: any): void { let result = this.showCarColorsDialog != $event.state; if (result == true) { this.showCarColorsDialog = $event.state; if ($event.hasChanges) { this.getCarColors(); } } } ```
57583
I am using spring data JPA repository, my requirement is when i call repository class methods in service class it should show only custom methods like addUser(X,Y) instead of save(). * Few things i understand, implementation of spring repository is provided by spring framework at runtime, So we cannot provide out own implementation. (This will overhead). * All methods in JPARepository is public only, so its obivious when we implement this interface all methods will be visible through out. * I am thinking of using DAO and Repository both at same time. DAO will provide custom function signature and repository will implement DAO interface. Any Hack ?
If you don't want the methods from `JpaRepository` or `CrudRepository`, don't extend those but just [`Repository`](https://docs.spring.io/spring-data/data-commons/docs/current/api/) instead. It is perfectly fine to have a repository interface like ``` MyVeryLimitedRepository extends Repository<User, Long> { User findByName(String name); } ``` Of course methods like `addUser(X,Y)` will need a custom implementation.
57693
I've now written a few applications using scala actors and I'm interested in how people have approached or dealt with some of the problems I've encountered. **A plethora of Message classes or !?** I have an actor which reacts to a user operation and must cause something to happen. Let's say it `react`s to a message `UserRequestsX(id)`. A continuing problem I have is that, because I want to modularize my programs, a single actor on its own is unable to complete the action without involving other actors. For example, suppose I need to use the `id` parameter to retrieve a bunch of values and then these need to be deleted via some other actor. If I were writing a normal Java program, I might do something like: ``` public void reportTrades(Date date) { Set<Trade> trades = persistence.lookup(date); reportService.report(trades); } ``` Which is simple enough. However, using actors this becomes a bit of a pain because I want to avoid using **`!?`**. One actor reacts to the `ReportTrades(date)` message but it must ask a `PersistenceActor` for the trades and then a `ReportActor` to report them. The only way I've found of doing this is to do: ``` react { case ReportTrades(date) => persistenceActor ! GetTradesAndReport(date) } ``` So that in my `PersistenceActor` I have a react block: ``` react { case GetTradesAndReport(date) => val ts = trades.get(date) //from persietent store reportActor ! ReportTrades(ts) } ``` But now I have 2 problems: 1. I have to create extra message classes to represent *the same request* (i.e. "report trades"). In fact I have three in this scenario but I may have many more - it becomes a problem keeping track of these 2. What should I call the first and third message `ReportTrades`? It's confusing to call them both `ReportTrades` (or if I do, I must put them in separate packages). Essentially there is no such thing as `overloading` a class by `val` type. Is there something I'm missing? Can I avoid this? Should I just give up and use **`!?`** Do people use some organizational structure to clarify what is going on?
To me, your `ReportTrades` message is mixing two different concepts. One is a Request, the order is a Response. They might be named `GetTradesReport(Date)` and `SendTradesReport(List[Trade])`, for example. Or, maybe, `ReportTradesByDate(Date)` and `GenerateTradesReport(List[Trade])`.
58137
``` apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "22.0.1" defaultConfig { applicationId "com.nusecond.karun.suredeal" minSdkVersion 18 targetSdkVersion 23 versionCode 1 versionName "1.0" } signingConfigs { release { storeFile file("suredealreleasekey.keystore") storePassword "suredeal" keyAlias "SuredealReleaseKey" keyPassword "suredeal" } } buildTypes { release { signingConfig signingConfigs.release } } packagingOptions { exclude 'META-INF/ASL2.0' exclude 'META-INF/LICENSE' exclude 'META-INF/license.txt' exclude 'META-INF/NOTICE' exclude 'META-INF/notice.txt' } } repositories { mavenCentral() } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:design:23.1.1' compile 'com.android.support:appcompat-v7:23.1.1' compile 'com.android.support:recyclerview-v7:23.1.1' compile 'com.facebook.android:facebook-android-sdk:4.6.0' testCompile 'com.android.support:support-annotations:23.1.1' androidTestCompile 'com.android.support:support-annotations:23.1.1' compile 'com.google.android.gms:play-services-base:8.4.0' compile 'com.google.android.gms:play-services-plus:8.4.0' compile 'com.google.android.gms:play-services-auth:8.4.0' compile 'com.android.support:support-v13:23.1.1' /** * GSON */ compile 'com.google.code.gson:gson:2.4' // UI AutomatorTesting androidTestCompile 'com.android.support.test:runner:0.2' androidTestCompile 'com.android.support.test:rules:0.2' androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.0' compile 'com.google.android.gms:play-services-appindexing:8.4.0' /** * Spring Dependencies * compile 'org.springframework.android:spring-android-rest-template:1.0.1.RELEASE' * compile 'com.fasterxml.jackson.core:jackson-core:2.4.2' * compile 'com.fasterxml.jackson.core:jackson-annotations:2.4.0' */ compile 'org.springframework.android:spring-android-rest-template:2.0.0.M3' compile 'com.fasterxml.jackson.core:jackson-databind:2.4.2' /** * Android Annotation Dependencies */ compile 'org.glassfish.main:javax.annotation:4.0-b33' /** * Volley Jar */ compile files('libs/volley.jar') compile 'com.mcxiaoke.volley:library:1.0.19' /** * GCM Dependency */ compile 'com.google.android.gms:play-services-gcm:8.4.0' /** * Universal image Loader */ compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5' compile files('libs/urlimageviewhelper-1.0.4.jar') compile 'com.squareup.picasso:picasso:2.5.2' } repositories { maven { url 'http://repo.spring.io/milestone' } } ``` 1. This is build.gradle 2. Here I'm generating signed APK using Gradle Build.(`./gradlew assembleRelease`). 3.Build Failed for task app:processReleaseResources. Here the stacktrace: ``` ---------- ./gradlew assembleRelease --stacktrace :app:preBuild UP-TO-DATE :app:preReleaseBuild UP-TO-DATE :app:checkReleaseManifest :app:preDebugBuild UP-TO-DATE :app:prepareComAndroidSupportAppcompatV72311Library UP-TO-DATE :app:prepareComAndroidSupportDesign2311Library UP-TO-DATE :app:prepareComAndroidSupportRecyclerviewV72311Library UP-TO-DATE :app:prepareComAndroidSupportSupportV132311Library UP-TO-DATE :app:prepareComAndroidSupportSupportV42311Library UP-TO-DATE :app:prepareComFacebookAndroidFacebookAndroidSdk460Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesAppindexing840Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesAuth840Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesBase840Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesBasement840Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesGcm840Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesMeasurement840Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesPlus840Library UP-TO-DATE :app:prepareReleaseDependencies :app:compileReleaseAidl UP-TO-DATE :app:compileReleaseRenderscript UP-TO-DATE :app:generateReleaseBuildConfig UP-TO-DATE :app:generateReleaseAssets UP-TO-DATE :app:mergeReleaseAssets UP-TO-DATE :app:generateReleaseResValues UP-TO-DATE :app:generateReleaseResources UP-TO-DATE :app:mergeReleaseResources UP-TO-DATE :app:processReleaseManifest UP-TO-DATE :app:processReleaseResources FAILED FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:processReleaseResources'. > at index 4 * Try: Run with --info or --debug option to get more log output. * Exception is: org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:processReleaseResources'. at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46) at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35) at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:64) at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58) at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:42) at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52) at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53) at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43) at org.gradle.api.internal.AbstractTask.executeWithoutThrowingTaskFailure(AbstractTask.java:310) at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.executeTask(AbstractTaskPlanExecutor.java:79) at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:63) at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:51) at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:23) at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:88) at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37) at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62) at org.gradle.execution.DefaultBuildExecuter.access$200(DefaultBuildExecuter.java:23) at org.gradle.execution.DefaultBuildExecuter$2.proceed(DefaultBuildExecuter.java:68) at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32) at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62) at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:55) at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:149) at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:106) at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:86) at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:90) at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28) at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35) at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41) at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:28) at org.gradle.launcher.exec.DaemonUsageSuggestingBuildActionExecuter.execute(DaemonUsageSuggestingBuildActionExecuter.java:50) at org.gradle.launcher.exec.DaemonUsageSuggestingBuildActionExecuter.execute(DaemonUsageSuggestingBuildActionExecuter.java:27) at org.gradle.launcher.cli.RunBuildAction.run(RunBuildAction.java:40) at org.gradle.internal.Actions$RunnableActionAdapter.execute(Actions.java:169) at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:237) at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:210) at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:35) at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:24) at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:206) at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:169) at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:33) at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:22) at org.gradle.launcher.Main.doAction(Main.java:33) at org.gradle.launcher.bootstrap.EntryPoint.run(EntryPoint.java:45) at org.gradle.launcher.bootstrap.ProcessBootstrap.runNoExit(ProcessBootstrap.java:54) at org.gradle.launcher.bootstrap.ProcessBootstrap.run(ProcessBootstrap.java:35) at org.gradle.launcher.GradleMain.main(GradleMain.java:23) at org.gradle.wrapper.BootstrapMainStarter.start(BootstrapMainStarter.java:33) at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:130) at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:48) Caused by: java.lang.NullPointerException: at index 4 at com.google.common.collect.ObjectArrays.checkElementNotNull(ObjectArrays.java:240) at com.google.common.collect.ObjectArrays.checkElementsNotNull(ObjectArrays.java:231) at com.google.common.collect.ObjectArrays.checkElementsNotNull(ObjectArrays.java:226) at com.google.common.collect.ImmutableList.construct(ImmutableList.java:303) at com.google.common.collect.ImmutableList.copyOf(ImmutableList.java:258) at com.android.ide.common.process.ProcessInfoBuilder.createProcess(ProcessInfoBuilder.java:55) at com.android.builder.core.AaptPackageProcessBuilder.build(AaptPackageProcessBuilder.java:444) at com.android.builder.core.AndroidBuilder.processResources(AndroidBuilder.java:915) at com.android.build.gradle.tasks.ProcessAndroidResources.doFullTaskAction(ProcessAndroidResources.java:138) at com.android.build.gradle.internal.tasks.IncrementalTask.taskAction(IncrementalTask.java:98) at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:75) at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.doExecute(AnnotationProcessingTaskFactory.java:243) at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:219) at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.execute(AnnotationProcessingTaskFactory.java:230) at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:208) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61) ... 49 more BUILD FAILED Total time: 6.696 secs ``` I'm stuck here Any solution How to fix this issue plz Help me.
For me the issue was being caused by a circular reference in an xml file. Lint would usually flag the issue, unless instructed not too. Check for: ``` tools:ignore="ResourceCycle" ```
58332
**Snake Games** ``` Module[ {dir = {-1, 0}, x = -1., y = 0., snake = Table[{i, 0}, {i, 0, 4}], gameover = False, target = {RandomInteger[17] - 9, RandomInteger[17] - 9}, timecount = 0, score = 0}, Manipulate[ If[ Mod[timecount, 5] == 0 && u != {-1, -1} && gameover == False, x = u[[1]]; y = u[[2]]; dir = If[ y >= x, If[y >= -x, {0, 1}, {-1, 0}], If[y >= -x, {1, 0}, {0, -1}] ]; If[ MemberQ[snake, snake[[1]] + dir] || (snake[[1]] + dir)[[ 1]] < -10 || (snake[[1]] + dir)[[1]] > 9 || (snake[[1]] + dir)[[2]] < -10 || (snake[[1]] + dir)[[2]] > 9, gameover = True; score = Length[snake] - 5 ]; If[ (snake[[1]] + dir) == target, target = {RandomInteger[17] - 9, RandomInteger[17] - 9}, snake = Most[snake] ]; PrependTo[snake, snake[[1]] + dir] ]; timecount++; Framed[ Graphics[ If[ False == gameover, Append[ Table[Rectangle[i, i + {1, 1}], {i, snake}], Rectangle[target, target + {1, 1}] ], {Rectangle[{-10, -10}, {10, 10}], Text[Style[" Game over! ", FontSize -> 36], {0, 3}, Background -> White], Text[Style[" Score: ", FontSize -> 24], {0, 0}, Background -> White], Text[Style[score, FontSize -> 24], {0, -2}, Background -> White]} ], Axes -> False, PlotRange -> {{-10, 10}, {-10, 10}}, ImagePadding -> 0 ], FrameMargins -> 0 ], {u, {-1, -1}, {1, 1}}, ControlPlacement -> Right ] ] ``` It is not convenient for the user to play this game in the above form. So how can I rewrite it without using `Manipulate`, but using other functions that can provide a better user interface?
I think you've actually done a good job considering you are only using `Manipulate`. Here's a simplified snake game using `Dynamic`: ``` snake = {{0, 0}, {0, 1}, {0, 2}}; dir = {0, -1}; directions = { "UpArrowKeyDown" :> (dir = {0, 1}), "DownArrowKeyDown" :> (dir = {0, -1}), "LeftArrowKeyDown" :> (dir = {-1, 0}), "RightArrowKeyDown" :> (dir = {1, 0})}; EventHandler[ Graphics[ Dynamic[Rectangle /@ snake], PlotRange -> 5], directions] While[True, Pause[.5]; snake = Most[snake]~Prepend~(snake[[1]] + dir);] ``` Here I put the `Dynamic` inside the `Graphics` expression, rather than wrapping the whole `Graphics` with a `Dynamic`. This works because `Graphics` is designed to let it work, and it does make a difference (in general) if you need performance. I recommend you read the documentation for [Dynamic](http://reference.wolfram.com/mathematica/ref/Dynamic.html) (especially the "Details") and the [Advanced Dynamic Functionality](http://reference.wolfram.com/mathematica/tutorial/AdvancedDynamicFunctionality.html) tutorial. It's kinda boring but it's useful. Another thing I should point out, that wasn't obvious to me at first, is that `Dynamic` uses `Set`, quite explicitly. What this means in practice is that `Dynamic` works, for example, with array locations: ``` array = {1, 2, 3}; Dynamic[array] Slider[Dynamic[array[[2]]]] While[True, Pause[.5]; array[[2]] = RandomReal[]] ``` As well as for function downvalues such as `f[2]`. This makes the programming easier for larger controls, such as matrix controls and the like.
58477
I am a sleep deprived mum of a 9 1/2 month old boy. He's otherwise a smiley, healthy and seems to be on the top percentile for both weight and height for his age. So he doesn't seem to be sleep deprived, grumpy and starving or obese. He is also completely breastfed- fresh from the tap, not through choice but he simply refuses the bottle (which is another issue) but my plan is to wean him in 3-4 months. He also doesn't take the pacifier... he objects to anything artificial in his mouth and we have tried many things (except for starving him until he takes the bottle) and now we have simply given up. He's eating solid alright and basically enjoy eating, he has also cut his day feeds drastically. Nighttime however is becoming more and more of a nightmare. He was never a good sleeper and I made the rookie mistake of letting him sleep on the breast. I never managed the put him down awake thing that everyone else seems to be able to do. We also co-sleep so that I wouldn't die from all the multiple wakings. Recently things have gotten from bad to worse. He goes to sleep fairly easily but wakes up every hour up to midnight or 1 am, then he wakes up every 2 hours until he wakes up for the day between 0600 to 0630. He goes to bad between 1830 to 1930 depending on when he wakes up from his last nap but typically he is out by 1900. Then the hourly waking starts. I have searched the Internet and it seems the sleep association is to blame, as he falls asleep on the breast he needs it to get back to sleep again. He can't connect the sleep cycles himself. These sounds most likely the most plausible reason, but what can I do about it save cry-it-out?? I think he also have a second sleep association- which is being close to me. Sometimes (but rarely) he does get off the breast and wiggles himself to sleep but usually stuck against me. The reason why I would like to leave CIO until there are no options left are because: 1. He wails and get more upset the longer he cries. He doesn't calm down easily once he starts. 2. He started crawling and few days later crusing and now he can go from furniture to furniture and climb down from the sofa, things actually started to worsen a month ago when he started turning in his sleep and got on all fours at night and started crying but he wasn't mobile until 2 weeks ago. 3. He is teething. His 3 teeth broke through in a week and one more on the way. I started giving him ibuprofen yesterday and he seemed to have slept better; will do it again tonight. 4. His separation anxiety seems to be getting worse. He was always clingy but now he wails when I leave the room and crawls to chase after me. He also clutches to be tightly after every feed. So with so much going on, I really don't want to make it harder for him.. but at the same time things are getting worse on the home front as dear husband is blaming me for fostering his bad habits, inhibiting his ability to be independent and basically being the reason why he can smooth himself to sleep. What can I do to improve the situation? Should I wait it out, cry it out?
Well there are a number of things. Separation anxiety getting worse is normal, developmentally appropriate & something you just have to pass through. The age where you might see more improvement with that is past 18 months. All children have it to some degree, and some are much more than others. I saw no difference in the children that had me back at work at 6 weeks & the one I was home for, in that regard, despite being "used to" me leaving daily. It's a normal healthy part of early childhood. It's hard, but it will pass on it's own. Frequent waking can be a cycle, but it also is associated with oral ties, lip & tongue as well as things like silent reflux. A child's sleep cycle isn't like an adult, it's actually 45mins, so when a child wakes hourly, chances are they have become fully alert after a single sleep cycle. I noticed you said you permitted the baby to sleep on the breast. One way to help you is to work on trying to get baby to fall asleep at naps & at the first bed sleep, unlatched. I know it's work. I have been through it. If you are persistent, and just unlatch them while awake & shush, pat, walk, bounce, rock, etc, they will fall asleep. If you can consistently get the baby to finally accept unlatching before sleep, you do generally see them waking you less at night. All babies & children rouse. Adults do as well. It's normal. We roll over, change positions, etc. So you simply are aiming to get the baby to a place where he is more likely to get back to sleep without rousing you to do so. For me, I have always found getting them to unlatch before they dose off, is most helpful there. And if baby is going through milestones, developmental leaps, growth spurts & teeth, it's also just going to sometimes be stormy. It helps to remind yourself how fast the 9 months has gone. It will help you remember that this will pass faster than it seems too. It feels long in the moment, but then you can't believe it & they are talking & running around & you made it through after all. So The separation anxiety is normal stuff & expect that it will intensify going forward: <http://www.parenting.com/article/separation-anxiety-age-by-age> If you have ever been told your baby has a tie or suspected it, you may want to have that relooked at. <http://www.drghaheri.com/blog/2014/2/20/a-babys-weight-gain-is-not-the-only-marker-of-successful-breastfeeding> You might want to check into getting the "wonder weeks" app. It pretty accurately will tell you when to developmentally expect certain behaviors. It's not 100% but will give you a better idea of when your baby is most apt to being crabbier, wake more, etc. This blog sort of explains about the book & app. <http://www.weebeedreaming.com/my-blog/wonder-weeks-and-sleep> And if you are interested, there is a sleep consultant that doesn't do CIO that I have heard rave reviews on & I know her through a mom group, and she has given me very sound input. I know there is a section on nap help on her site that is free. <http://childrenssleepconsultant.com/> And mostly, hang in there. I found that least few months before they hit a year hard. There are a lot of things at play. It's a tough age. It's wonderful in a lot of ways too, but the developmentally things happening, growth spurts, teeth, they combine to also challenge you at a time when you have hoped this whole thing was going to start getting easier. It will. It then just gets harder in new ways though. But sleep will get better & with more sleep, then all of life seems more manageable. And be nice to yourself whenever you can. Take long baths or just a 15 minute walk alone, or any other way you can squeeze in some breathing space. That too helps to make it more manageable & something I insist that I do for myself every single day. The only time I don't might be during illness. I will walk out even if the baby is screaming about it, because I always put them with someone loving & kind & just take that time to clear my head & have 15 minutes to be alone with my thoughts & listen to the wind.
58598
Recently I learned that in some Middle Eastern countries they add cardamom and cloves to their coffee to flavor it. **Are there any other coffee flavorings found around the globe I might not have heard of?**
I prefer my coffee flavored just with water. However, it is common for people to flavor their coffee with many other ingredients with respect to their personal preference. As personal preference is closely related to culture, **yes, you may enlist some location-based flavoring ingredients for coffee**. **In Turkey**, generally, coffee does not have any ingredients except sugar. In the west part, mastic is sometimes added for flavor. This is a common tradition with Greeks, I assume. In the Southeast part, cardamom is rarely added. This is a common tradition with Syrians, I assume. I never heard of cloves around here. --- **Sugar** and its close relatives: I think this is the most common one, independent from the geography. **Milk** may be the second most common one. Mostly used in the Italian-influenced Western coffee. **Chocolate** is only common in the Austrian-influenced coffee recipes, I assume. *From now on, I think we may say not very common flavorings.* **Cinnamon** is common both on Austrian-influenced coffees and old-style coffees. **Mastic** is common around Aegean Sea with Turkish brewing method. **Cardamom** is common around Syria with Turkish brewing method. **Cloves** is common around Arabian Peninsula with Saudi brewing method (say, a brewing method close to Turkish). **Chicory** is common in Vietnam, South India and in New Orleans/Southern Louisiana of USA. **Butter** is common in East Africa, Himalayas and very recently in North America under the fancy name of "bulletproof". **Coconut** and **Marjoram** are my recent encounters in some old Turkish recipes together with Cardamom. Especially, when the beans are ground in *dibek*, an ancient Turkish coffee mortar.
58749
How can I make sure that Emacs opens files with extension `*.rec` as normal text files? When I try to open a file with the extnsion `*.rec`, I get the error message `Running someFile.rec...done` without the file being opened. [![Screenshot](https://i.stack.imgur.com/KYwU5.png)](https://i.stack.imgur.com/KYwU5.png) I assume that `rec-mode` is not installed because its status is `Available from gnu` (see below). [![Status of the rec-mode package](https://i.stack.imgur.com/ujlGX.png)](https://i.stack.imgur.com/ujlGX.png) What can I do in order for Emacs to open `*.rec` files as plain, normal text files?
To tell Emacs that `*.rec` files should be opened in `text-mode`: ```el (add-to-list 'auto-mode-alist '("\\.rec\\'" . text-mode)) ```
58931
I am working with Google Maps API V3 to calculate all the possible routes from a given Source to the specified Destination. For this I takes the Destination and Source as inputs from the user and pass these values in the request with option provideRouteAlternatives: true. I am successful in calculating different Routes and also marking i.e. displaying them on my Map. Now I am wondering if it is possible to name the Different Routes. By naming the Routes I mean adding a small description to each Route like the Street Name etc. which that particular route takes while moving from Source to Destination. I want to do this so as to make it look more interactive. For example if there are 3 Routes possible from location A (Arizona Street, San Diego, CA, USA) to location B (Fenton Parkway, San Diego, CA 92108, USA) then instead of showing results like Route 1, Route 2, Route 3 it should show the Street names like "Texas St & Rio San Diego Dr", "Texas St & Friar Rd", "Friars Rd". I am able to calculate all the other things like the trip distance and total trip time for each of my Route but have no clue to how to add this description to each of my Route. Any help will be appreciated. Thanks
Have you looked into [string formatting](http://www.mathworks.com/help/matlab/matlab_prog/formatting-strings.html)? ``` fid = fopen( 'myFile.txt', 'w' ); for ii=1:size(cloud,1) fprintf( fid, '%.5g\t%.5g\r\n', cloud(ii,1), cloud(ii,2) ); end fclose( fid ); % do not forget to close the file :-) ``` Have you considered [`save`](http://www.mathworks.com/help/matlab/ref/save.html)ing into ascii file? ``` save( 'myFile.txt', 'cloud', '-ascii', '-tabs' ); ``` **EDIT:** 1. End-of-line issue: for text file there are several way of marking the end of line: On windows it is usually required to print `\r\n`, for Mac and Linux sometimes it is enough to use `\r` and sometimes `\n` (I'm not 100% sure). So, you might need to experiment with it a bit to find out what works best for your machine. (Thanks @Rody for correcting me here) 2. Accuracy: the number in the formatting string `%.5g` determines the accuracy of the printed number. Again, you can play with it till you are satisfied with the results.
59390
I'm creating split archives using the following code: ``` string filename = "FileName.pdf"; using (ZipFile zip = new ZipFile()) { zip.UseZip64WhenSaving = Zip64Option.Default; zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Default; using (FileStream stream = new FileStream(temp, FileMode.Open)) { zip.AddEntry(filename, stream); zip.MaxOutputSegmentSize = settings.AttachmentSize * (1024 * 1024); zip.Save(zipFileName); } } ``` The code above generates 3 files: `file.zip, file.z01 and file.z02`. When I right-click that zip file and select `Extract All` (not using WinRAR or other zipping software to extract, just the built-in Windows zip) it gives me the following error: > > The same volume can not be used as both the source and destination > > > ![enter image description here](https://i.stack.imgur.com/I9RGE.png) ![enter image description here](https://i.stack.imgur.com/4b8ld.png) What's weird is that it only happens on the first time I try to extract the files, the succeeding extractions are OK so it must be how the files were zipped in the first place. **UPDATE 1** The same thing happens even if I extract to a different folder There have been discussions with regards to this issue on the DotNetZip Codeplex site, but it seems the issue has not been resolved yet <http://dotnetzip.codeplex.com/discussions/239172> <http://dotnetzip.codeplex.com/discussions/371005> **UPDATE 2** Looking at the doc for the [MaxOutputSegmentSize](http://www.nudoq.org/#!/Packages/DotNetZip/Ionic.Zip/ZipFile/P/MaxOutputSegmentSize) property, it is quoted: > > I don't believe Windows Explorer can extract a split archive. > > > There's no further explanation though as to why. I consider this to be a false-positive since as mentioned above, > > it only happens on the first time I try to extract the files, the > succeeding extractions are OK > > > I'm using Windows 8.1 64-bit.
First thing you'd always want to do when searching for the reason why software fails is locating the source of the error message. You do that by [using Google first](https://www.google.com/search?q=%22the+same+volume+can+not+be+used+as+both+the+source+and+destination%22&ie=utf-8&oe=utf-8). Second hit (right now) is golden, [somebody](http://www.win7dll.info/zipfldr_dll.html) has decompiled Windows executables and located this specific string as resource ID #10209 in a file named `zipfldr.dll` with a Microsoft copyright notification. That is an excellent match, zipfldr.dll is the shell namespace extension that Windows uses to display the content of a .zip file as though it is a folder. You can see it in Regedit.exe, navigate to `HKEY_CLASSES_ROOT\CLSID\ {E88DCCE0-B7B3-11d1-A9F0-00AA0060FA31}` for the primary registration. The `HKEY_CLASSES_ROOT\SystemFileAssociations\ .zip\CLSID` registry key associates it with a .zip file. So you have a hard fact, it really is the Explorer extension that falls over. Exceedingly little you can do about that of course. Only remaining doubt that it might be the Zip library you use that fumbles the spanned files content and thus causes the extension to fall over. That is significantly reduced by seeing more than one library tripping this error, the odds that both Ionic and Dotnetzip have the exact same bug is rather low. Not zero, programmers do tend to have a "how did they do that" peek at other programmer's code for inspiration. The fact that this error is spurious puts the nail in the coffin, you'd expect bad zip archive content to trip an error repeatedly. You *might* be able to reverse-engineer the underlying problem, you'd do so with SysInternals' Process Monitor. You'll see Explorer reading and writing files. Probably in the TEMP directory, I speculate that you'd get an error like this one if a .zip file already exists in that directory. TEMP is a very messy folder on most machines, too many programs don't clean up properly after themselves. Including zip libraries, an attractive theory not otherwise backed-up by proof :) If that doesn't pan out then the ultimate fallback is Microsoft. They have a 1-800 telephone number where you can get support for problems with their products. I've used it several times, they always solved my problem and refunded the upfront fee. This is a Windows problem however, a product that has a billion users. You'll, at best, get a workaround, an actual software fix is exceedingly unlikely. Not entirely impossible, it has been done. But very high odds that their recommended workaround is "use a 3rd party utility like Winzip". Not what you want to hear.
59400
``` ;WITH cte_Date ( DateCode_FK ) AS ( SELECT DATEADD( DAY, 1 - ROW_NUMBER() OVER ( ORDER BY so1.object_id ), GETDATE() ) FROM sys.objects so1 CROSS APPLY sys.objects so2 ) SELECT TOP 10 d.DateCode_FK FROM cte_Date d ORDER BY d.DateCode_FK DESC; ``` Nothing an overly interesting query, but i'm receiving an error message if I run it with the `ORDER BY` clause: > > Msg 517, Level 16, State 1, Line 4 > > > Adding a value to a 'datetime' column caused an overflow. > > > However, without the `ORDER BY` clause, it runs just fine. In addition, if I run the query on other catalogs contained in the same instance on the same server, the query runs fine with or without the `ORDER BY` clause. I've taken a look at the configuration options and compatibility levels between the affected catalog and a catalog on which the query runs as expected, but have not found anything that might warrant the difference. Has anybody else run into a similar issue? I can work around it for now, but would ideally need to be able to fix the problem, whatever it is. Potential hint - if you have a relatively large number of objects in a catalog ( > 5000 ), you -may- be able to reproduce the error... This is occurring on my largest catalog and it appears that if I include a TOP in the CTE, the ORDER BY issue goes away.
SQL Server does not guarantee the timing or number of evaluations for scalar expressions. This means that a query that *might* throw an error *depending on the order of operations* in an execution plan might (or might not) do so at runtime. The script uses `CROSS APPLY` where `CROSS JOIN` was probably intended, but the point is that the potential number of rows over which the `ROW_NUMBER` is calculated depends on the size of the `sys.objects` cross product. For a database with sufficient objects, an overflow for the `DATEADD` result is an expected risk. For example, this is reproducible using the *AdventureWorks* sample database, which has 637 entries in `sys.objects`. The size of the cross product is 637 \* 637 = 405,769; the following throws an overflow error: ``` SELECT DATEADD(DAY, 1 - 405769, GETDATE()); ``` One might argue that there is no need to materialize the result of an expression [for rows that are not returned](http://connect.microsoft.com/SQLServer/feedbackdetail/view/537419/sql-server-should-not-raise-illogical-errors) (and therefore not throw an error), but that is not the ways things work today. Consider: * The *highest* `ROW_NUMBER` will give the *lowest* value for `DateCode_FK` in the `DATEADD(DAY, 1 - ROW_NUMBER()...` expression * The presentation `ORDER BY` is `DateCode_FK DESC` * Only the first 10 rows in presentation order are required If the optimizer contained logic to reason that *lower* row numbers lead to *higher* `DateCode_FK` values, an explicit Sort would not be needed. Only ten rows would need to flow through the execution plan. The ten lowest row numbers are guaranteed to produce the ten highest `DateCode_FK` values. Regardless, even where a Sort is present, the argument is that SQL Server should not throw an error because none of the ten rows actually returned are associated with an overflow error. As I said above, *"that is not the ways things work today"*. --- An alternative formulation that avoids the error (though it is still not *guaranteed* to do so - see my opening remark), makes the row numbering deterministic, and uses `CROSS JOIN`: ``` WITH cte_Date (DateCode_FK) AS ( SELECT TOP (10) DATEADD ( DAY, 1 - ROW_NUMBER() OVER ( ORDER BY so1.[object_id], so2.[object_id]), GETDATE() ) FROM sys.objects AS so1 CROSS JOIN sys.objects AS so2 ORDER BY ROW_NUMBER() OVER ( ORDER BY so1.[object_id], so2.[object_id]) ASC ) SELECT TOP (10) -- Redundant TOP d.DateCode_FK FROM cte_Date AS d ORDER BY d.DateCode_FK DESC; ``` [Paste the Plan](https://www.brentozar.com/pastetheplan/?id=r1WxakzBl) [![Plan](https://i.stack.imgur.com/n1GlF.png)](https://i.stack.imgur.com/n1GlF.png) [![Results](https://i.stack.imgur.com/oLbMB.png)](https://i.stack.imgur.com/oLbMB.png)
59528
Is there some URL from which I can download a given package from npm (as a tarball or something)? I need the exact files that were originally uploaded to npm. Using `npm install` gets a different, generated package.json for example. I want the exact original set of files that was published.
You can use [`npm view`](https://docs.npmjs.com/cli/view) to get the URL to the registry's tarball (in this example for the module `level`): ``` $ npm view level dist.tarball ``` And to download tarball, you can use [`npm pack`](https://docs.npmjs.com/cli/pack): ``` $ npm pack level ```
59651
I need to load 100 images in cells. If I use this method in tableView cellForRowAt: ``` cell.cardImageView.image = UIImage(named: "\(indexPath.row + 1).jpg") ``` and start scrolling fast my `tableView` freezes. I use this method to load the image data in background that fix freezes: ``` func loadImageAsync(imageName: String, completion: @escaping (UIImage) -> ()) { DispatchQueue.global(qos: .userInteractive).async { guard let image = UIImage(named: imageName) else {return} DispatchQueue.main.async { completion(image) } } } ``` in `tableView cellForRowAt` call this: ``` loadImageAsync(imageName: "\(indexPath.row + 1).jpg") { (image) in cell.cardImageView.image = image } ``` But I have one bug may arise in this approach, such that while scrolling fast I may see old images for a while. How to fix this bug?
Your cells are being reused. When cell goes out of screen it gets to internal `UITableView`s reuse pool, and when you `dequeueReusableCell(withIdentifier:for:)` in `tableView(_:cellForRowAt:)` you get this cell again (see, "reusable" in name). It is important to understand `UITableViewCell`'s life cycle. `UITableView` does not hold 100 living `UITableViewCell`s for 100 rows, that would kill performance and leave apps without memory pretty soon. **Why do you see old images in your cells?** Again, cells are being reused, they keep their old state after reuse, you'll need to reset the image, they won't reset it by themselves. You can do that when you configure a new cell or detect when the cell is about to be reused. As simple as: ``` cell.cardImageView.image = nil // reset image loadImageAsync(imageName: "\(indexPath.row + 1).jpg") { (image) in cell.cardImageView.image = image } ``` The other way is detecting reuse and resetting. In your cell subclass: ``` override func prepareForReuse() { super.prepareForReuse() self.cardImageView.image = nil // reset } ``` **Why do you see wrong images in your cells?** By the time `completion` closure sets image into `cardImageView`, `UITableViewCell` has been reused (maybe, even, more than once). To prevent this you could test if you're setting image in the same cell, for example, store image name with your cell, and then: ``` // naive approach let imageName = "\(indexPath.row + 1).jpg" cell.imageName = imageName loadImageAsync(imageName: imageName) { (image) in guard cell.imageName == imageName else { return } cell.cardImageView.image = image } ``` There is a lot of stuff to take care of when designing lists, I won't be going into much detail here. I'd suggest to try the above approach and investigate the web on how to handle performance issues with lists.
60601
I want to create a HashMap to store data to firestore database. I want store the name and a boolean value based on the pressed button. But the **"put()"** in hashmap **replaces** the previous values, i.e the name and the boolean value. And i get only the last value in the database. Here is the use of put to store data in the Map. ``` @Override public void onClick(View v) { switch (v.getId()) { case R.id.present: attendance.put(name, true); nextCard(); break; case R.id.absent: attendance.put(name, false); nextCard(); break; } } ``` And the firestore store method.. ``` public void storeAttendance(String batch) { String date = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date()); db.collection(batch+"sheet").document(date) .set(attendance) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Log.d("TAG", "DocumentSnapshot successfully written!"); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w("TAG", "Error writing document", e); } }); } ``` I want the values for all the students attendance in the database but i get only the single value for the last student. [The Database structure i get.](https://i.stack.imgur.com/Q7Ixg.png)
Try and identify what makes a number even. In your head, what could you do to the number to prove it is even? You divide it by 2 and see if the remainder is 0. In programming, we use the modulo operator (%) to get the remainder of an equation. Try and think of a way that you can iterate over the items in your list and see if they are even using the above method.
60938
So, here is my XML file for my user layout ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="15dp" android:orientation="horizontal"> <de.hdodenhof.circleimageview.CircleImageView android:id="@+id/users_profile_image" android:layout_width="70dp" android:layout_height="70dp" android:src="@drawable/profile_image" app:civ_border_color="#696969" app:civ_border_width="1dp"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_gravity="center" android:layout_marginLeft="5dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20dp" android:id="@+id/username_layout" android:padding="5dp" android:text="username" android:textColor="#353758" android:textStyle="bold" /> <ImageView android:id="@+id/user_item_online" android:layout_width="12dp" android:layout_height="12dp" android:layout_gravity="center_vertical" android:src="@drawable/user_state" android:visibility="visible" /> </LinearLayout> </LinearLayout> </RelativeLayout> ``` and this is how it looks : [![user_layout](https://i.stack.imgur.com/ULZM8.png)](https://i.stack.imgur.com/ULZM8.png) but I want it just like facebook or messenger, I mean when a user is online the dot is attached to his profile picture.
I'll suggest unsing `ConstraintLayout` for this. It's easier! For `ConstraintLayout` you need to add this dependency into your `build.gradle` app file: `implementation 'androidx.constraintlayout:constraintlayout:1.1.3'` Then you can do it like this: ```xml <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="15dp" android:orientation="vertical"> <de.hdodenhof.circleimageview.CircleImageView android:id="@+id/users_profile_image" android:layout_width="70dp" android:layout_height="70dp" android:src="@drawable/profile_image" app:civ_border_width="1dp" app:civ_border_color="#696969" app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent"/> <TextView android:id="@+id/username_layout" android:layout_width="0dp" android:layout_height="wrap_content" android:padding="5dp" android:text="username" android:textColor="#353758" android:textSize="20dp" android:textStyle="bold" android:layout_marginStart="5dp" android:layout_marginLeft="5dp" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toEndOf="@id/users_profile_image" app:layout_constraintEnd_toEndOf="parent"/> <ImageView android:id="@+id/user_item_online" android:layout_width="12dp" android:layout_height="12dp" android:src="@drawable/user_state" android:visibility="visible" android:translationX="-14dp" android:translationY="-14dp" app:layout_constraintEnd_toEndOf="@id/users_profile_image" app:layout_constraintBottom_toBottomOf="@id/users_profile_image" app:layout_constraintStart_toEndOf="@id/users_profile_image" app:layout_constraintTop_toBottomOf="@id/users_profile_image"/> </androidx.constraintlayout.widget.ConstraintLayout> ```
61301
I installed pip using `$ python get-pip.py` and I set PATH ``` C:\Program Files\Python\Scripts ``` then I restarted the command prompt so that path would take effect. Then I run `$ pip` I get this ``` Traceback (most recent call last): File "D:\obj\Windows- Release\37amd64_Release\msi_python\zip_amd64\runpy.py", line 193, in _run_module_as_main File "D:\obj\Windows- Release\37amd64_Release\msi_python\zip_amd64\runpy.py", line 85, in _run_code File "C:\Program Files\Python\Scripts\pip.exe\__main__.py", line 5, in <module> ModuleNotFoundError: No module named 'pip ' ```
Did you try: `$ pip -V`? Or `$ pip help`? Just guessing, but trying checking the version since pip probably requires an argument.
61310
So I'm trying to put all numbered domains into on element of a hash doing this: ``` ### Domanis ### my $dom = $name; $dom =~ /(\w+\.\w+)$/; #this regex get the domain names only my $temp = $1; if ($temp =~ /(^d+\.\d+)/) { # this regex will take out the domains with number my $foo = $1; $foo = "OTHER"; $domain{$foo}++; } else { $domain{$temp}++; } ``` where `$name` will be something like: ``` something.something.72.154 something.something.72.155 something.something.72.173 something.something.72.175 something.something.73.194 something.something.73.205 something.something.73.214 something.something.abbnebraska.com something.something.cableone.net something.something.com.br something.something.cox.net something.something.googlebot.com ``` My code currently print this: ``` 72.175 73.194 73.205 73.214 abbnebraska.com cableone.net com.br cox.net googlebot.com lstn.net ``` but I want it to print like this: ``` abbnebraska.com cableone.net com.br cox.net googlebot.com OTHER lstn.net ``` where `OTHER` is all the numbered domains, so any ideas how?
``` if(mt_rand(0,1)) { echo 3; } else { echo 5; } ``` Or reverse it, your choice.
61634
I have `AViewController` which is a rootViewController in it's navigationController. In `AViewController`, i have a `objectA`, i declare it like this: ``` @interface AViewController : ParentVC @property (strong, nonatomic) ObjectA *objectA; @end ``` I also have a `BViewController`, declared similar like this: ``` @interface BViewController : ParentVC @property (strong, nonatomic) ObjectA *objectA; @end ``` --- What i did is, in `AViewController`: ``` if (!_objectA) { _objectA = [ObjectA new]; } BViewController *bViewController = [[BViewController alloc] init]; bViewController.ojectA = _objectA; [self.navigationController pushViewController:bViewController animated:YES]; ``` While in `BViewController`, when i do this: ``` [self.navigationController popToRootViewControllerAnimated:NO]; self.objectA = nil; ``` --- But the problem is, when i back into `AViewController`, the `objectA` is still not nil. It seems that i niled the objectA just in `BViewController`. These two objectA are separated. What i really want to do is, in `BViewController` just keep a point to the objectA in `AViewController`. How can i reach this? Thanks in advance.
You should set it to weak rather than strong in BViewController, BViewController does not own the object, AViewController does... Is there a good reason to nil out AViewcontrollers pointer to this object? This is not safe object management IMHO edit addition.. ok after reading your comments i really think you should write a protocol, your design can be improved {or, as this is subjective, lets say more 'apple-like' :) } i think you should add a protocol in BViewController.h ``` @protocol <NSObject> BViewControllerDelegate -(void)viewControllerDidLogout:(BViewController *)controller; @end ``` and inside BViewController's interface ``` @property id <BViewControllerDelegate> delegate ``` AViewController can adopt this protocol, set BViewControllers delegate to self before pushing it, then BViewController can use this to communicate back. Alternatively you could post a notification..
61885
I have a kendo grid on Cordova app. Here on the grid, the scrolling is jagged due to the css rule 'k-grid tr:hover' in kendo css. If I disable this rule from developer tools, scrolling is smooth. Is there any way to disable this hover rule? I don't want to override hover behaviour. I want to disable it. Edit: The problem is due to hover the scrolling is not smooth on the grid. The scroll starts after touchend of the swipe but instead it should move with touchmove. This causes the scrolling to be jagged. Removing the hover rule solves this and makes scroll smooth. Do ask for further clarification if necessary.
You can use pointer-events: none property on the DOM element. <https://developer.mozilla.org/en/docs/Web/CSS/pointer-events> ``` .k-grid tr { pointer-events: none; } ``` With this property, the hover event on that element will be completely ignored.
62152
I know that the best way to upload to the blobstore is to use the blobstore API, so I tried to implement that, but I'm getting some weird errors that seem to suggest that I can't just embed a blobstore handler in my views.py file. Am I just going about this incorrectly? ETA: I *am* using Django for all of my other views and templates, in case that wasn't clear. Just wanted to make sure no one thought I was importing Django stuff for no reason. I'm kinda stuck using it for this project. Here is the error I'm currently getting: ``` AttributeError at /fileupload 'PhotoUploadHandler' object has no attribute 'status_code' Request Method: GET Request URL: http://localhost:8080/fileupload Django Version: 1.5.4 Exception Type: AttributeError Exception Value: 'PhotoUploadHandler' object has no attribute 'status_code' Exception Location: C:\Program Files (x86)\Google\google_appengine\lib\django-1.5\django\middleware\common.py in process_response, line 106 ``` Here is the file upload section in my views.py file: ``` from django import http from django.core.context_processors import csrf from django.views.decorators.csrf import csrf_protect from django.template import RequestContext from django.shortcuts import render_to_response from models import Contact from google.appengine.ext.webapp import blobstore_handlers from google.appengine.ext import blobstore from google.appengine.ext import webapp class PhotoUploadHandler(blobstore_handlers.BlobstoreUploadHandler): def post(self): upload = self.get_uploads()[0] photo = Photo(blob_key=upload.key()) db.put(photo) self.response.out.write('<html><body><img class="imgpreview" src="/photo/%d"></body></html>' % photo.key().id()) def get(self): upload_url = blobstore.create_upload_url('/photo') self.response.out.write('<html><body>') self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url) self.response.out.write('Upload File: <input type="file" name="file">') self.response.out.write('<br><input type="submit" value="Upload"></form>') self.response.out.write('</body></html>') ```
It might be simpler to use the django toolkit to enable support for storing files in GCS by default in django. In your settings.py: ``` APPENGINE_TOOLKIT = { # ..., 'BUCKET_NAME': 'your-bucket-name', } DEFAULT_FILE_STORAGE = 'appengine_toolkit.storage.GoogleCloudStorage' ``` <https://github.com/masci/django-appengine-toolkit> Files will then be saved/served from Google Cloud Storage automatically and transparently.
62163
I am an Android Developer. Yesterday I opened my current project at Android Studio and the project could not start. An error was shown: ``` Gradle sync failed: Unable to start the daemon process. This problem might be caused by incorrect configuration of the daemon. For example, an unrecognized jvm option is used. Please refer to the user guide chapter on the daemon at https://docs.gradle.org/4.4/userguide/gradle_daemon.html Please read the following process output to find out more: ----------------------- Consult IDE log for more details (Help | Show Log) (4s 245ms) ``` * I already edited `graddle.properties` to `org.gradle.jvmargs=-Xmx1024m` but its still not work * I already reinstalled my android studio with its gradle but this bug still persists * I already deleted `.gradle` folder on my computer but its still stuck * I already set build process heap size in Android studio but it still not work * I already checked my antivirus and my firewall (even turn it off) but nothing happens I need help here, because I can't run my project at all. Here is the gradle log: ``` at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) Caused by: org.gradle.api.GradleException: Unable to start the daemon process. This problem might be caused by incorrect configuration of the daemon. For example, an unrecognized jvm option is used. Please refer to the user guide chapter on the daemon at https://docs.gradle.org/4.4/userguide/gradle_daemon.html Please read the following process output to find out more: ``` and this is log from daemon log ``` 20:37:16.805 [DEBUG] [org.gradle.internal.remote.internal.inet.InetAddresses] Adding loopback multicast interface Microsoft Wi-Fi Direct Virtual Adapter-QoS Packet Scheduler-0000 20:37:16.805 [DEBUG] [org.gradle.internal.remote.internal.inet.InetAddresses] Adding IP addresses for network interface Microsoft Wi-Fi Direct Virtual Adapter-WFP 802.3 MAC Layer LightWeight Filter-0000 20:37:16.806 [DEBUG] [org.gradle.internal.remote.internal.inet.InetAddresses] Is this a loopback interface? false 20:37:16.808 [DEBUG] [org.gradle.internal.remote.internal.inet.InetAddresses] Is this a multicast interface? true 20:37:16.808 [DEBUG] [org.gradle.internal.remote.internal.inet.InetAddresses] Adding loopback multicast interface Microsoft Wi-Fi Direct Virtual Adapter-WFP 802.3 MAC Layer LightWeight Filter-0000 20:37:16.814 [ERROR] [system.err] 20:37:16.814 [ERROR] [system.err] FAILURE: Build failed with an exception. 20:37:16.815 [ERROR] [system.err] 20:37:16.815 [ERROR] [system.err] * What went wrong: 20:37:16.815 [ERROR] [system.err] java.net.BindException: Address already in use: bind 20:37:16.815 [ERROR] [system.err] 20:37:16.815 [ERROR] [system.err] * Try: 20:37:16.815 [ERROR] [system.err] Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. 20:37:16.816 [ERROR] [system.err] 20:37:16.816 [ERROR] [system.err] * Get more help at https://help.gradle.org Daemon vm is shutting down... The daemon has exited normally or was terminated in response to a user interrupt. ```
I resolved this by turning off Hotspot on my pc. Found the solution [here](https://www.programmersought.com/article/67033172684/)
62787
I'm trying to pull a string from my URL in WordPress, and create a function around it in the functions file. The URL is: "<https://made-up-domain.com/?page_id=2/?variables=78685,66752>" My PHP is: ``` $string = $_GET("variables"); echo $string; ``` So I'm trying to return "78685,66752". Nothing happens. Is the first question mark a problem? Or what am I doing incorrectly? Thanks!
`$_GET` should be in the form ``` $string = $_GET["variables"]; ``` and not ``` $string = $_GET("variables"); ```
63035
I'm trying to add placeholder text to my ckeditor screen like for example `Type here ...` . You can do this with the [configuration helper plugin](http://ckeditor.com/addon/confighelper). I've placed the ckeditor library in `sites/all/libries`. I've pasted the plugin in `sites/all/libraries/ckeditor/plugins`. Then I've added the following code to my **config.js** (in ckeditor folder). ``` CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. For example: // config.language = 'fr'; // config.uiColor = '#AADC6E'; config.extraPlugins='confighelper'; config.placeholder = 'Type here...'; }; ``` But this doesn't work. The **config.js** isn't added to my page when there's a ckeditor. The code is also not in **ckeditor.js** (which is loaded on the page, I thought that the plugin maybe added it to the file). I've also tried to add the code to my **script.js** which is **always** loaded like this: ``` (function ($, Drupal, window, document, undefined) { Drupal.behaviors.my_custom_behavior = { attach: function(context, settings) { CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. For example: // config.language = 'fr'; // config.uiColor = '#AADC6E'; config.extraPlugins='confighelper'; config.placeholder = 'Type here...'; }; } }; })(jQuery, Drupal, this, this.document); ``` But still no result... . I'm using `CKEditor 4.4.2.1567b48` . Text format is filtered html. The ckeditor works but I can't add any plugins (I would also like youtube plugin). Also cleared my cache a couple of times. Am I doing something wrong?
A solution that avoids patching the wysiwyg module is the following: You can use the hook `hook_wysiwyg_plugin($editor, $version)` that wysiwyg offers, in order to add the ckeditor plugin, as follows: ``` function custom_wysiwyg_plugin($editor, $version) { $plugins = array(); switch ($editor) { case 'ckeditor': $plugins['confighelper'] = array( 'extensions' => array('confighelper' => t('Configuration Helper')), 'url' => 'http://ckeditor.com/addon/confighelper', 'load' => TRUE, 'internal' => TRUE, ); break; } return $plugins; } ``` Then, go to the wysiwig profile edit page and enable the Configuration Helper plugin. After that, placeholder text will be shown in the wysiwyg ckeditor.
63574
I would like to take some JSON, convert it into a dictionary and then change some of the values in that dictionary. I've tried a few things as shown below but I can't get it to work as intended. My JSON is as follows: ``` { "9":[ { "09_000":{ "name":"Wyatt Feldt", "1":"R", "2":"L", "w":1, "h_t":1 } }, { "09_001":{ "name":"Clayton Friend", "1":"R", "2":"R", "w":0, "h_t":0 } } ], "10":[ { "09_000":{ "name":"Wyatt Feldt", "1":"R", "2":"L", "w":1, "h_t":1 } }, { "09_001":{ "name":"Clayton Friend", "1":"R", "2":"R", "w":0, "h_t":0 } } ], "11":[ { "09_000":{ "name":"Wyatt Feldt", "1":"R", "2":"L", "w":1, "h_t":1 } }, { "09_001":{ "name":"Clayton Friend", "1":"R", "2":"R", "w":0, "h_t":0 } } ] } ``` And then in Python I have written `print(my_data["9"][0])` which returns {'09\_000': {'name': 'Wyatt Feldt', '1': 'R', '2': 'L', 'w': 1, 'h\_t': 1}}. However, I just want it to return {'name': 'Wyatt Feldt', '1': 'R', '2': 'L', 'w': 1, 'h\_t': 1} because I don't just want to print it, I want to set some of the values e.g. the name. And I know I can do that by doing `my_data["9"][0]["09_000"]` but I don't want to use that ID in order to get it (only the outer group, the index and then the key e.g. "name"). Since I'm already returning {'09\_000': {'name': 'Wyatt Feldt', '1': 'R', '2': 'L', 'w': 1, 'h\_t': 1}} I'm sure there must be a way to just get the nested part ({'name': 'Wyatt Feldt', '1': 'R', '2': 'L', 'w': 1, 'h\_t': 1}) so I can change the values. EDIT: I think it's a different issue. My `my_data` variable is already in dictionary format, and this is a special case of indexing.
If you have your JSON text in a string, say its name is `my_json`, then you can use Python's `json.loads` to convert it to a dictionary. ``` import json register = json.loads(my_json) ``` In side your dictionary, you have keys "9", "10", "11". For each of those, you have a list of two items you can iterate through. And each of the items in the list is a dictionary of one key. You could just iterate through these last keys without knowing what they are: ``` for k in register: for block in register[k]: for block_key in block: print(block[block_key]) ``` The output I get from this is: ``` {u'1': u'R', u'h_t': 1, u'2': u'L', u'name': u'Wyatt Feldt', u'w': 1} {u'1': u'R', u'h_t': 0, u'2': u'R', u'name': u'Clayton Friend', u'w': 0} {u'1': u'R', u'h_t': 1, u'2': u'L', u'name': u'Wyatt Feldt', u'w': 1} {u'1': u'R', u'h_t': 0, u'2': u'R', u'name': u'Clayton Friend', u'w': 0} {u'1': u'R', u'h_t': 1, u'2': u'L', u'name': u'Wyatt Feldt', u'w': 1} {u'1': u'R', u'h_t': 0, u'2': u'R', u'name': u'Clayton Friend', u'w': 0} ``` If you know that your lists are always going to contain items of one key, then another way to do it is use `block.keys()` to generate the list of dictionary keys, then take the first (and only) item in the list: ``` for k in register: for block in register[k]: print(block[block.keys()[0]]) ``` In any case, you can replace the `print` statement I've used with some command to change whatever you need. Though to make it easier to get to the right location, try using the index numbers of the list: ``` for k in register: for i in range(len(register[k])): for key in register[k][i]: original_name = register[k][i][key][u'name'] if original_name == u'Wyatt Feldt': register[k][i][key][u'name'] = 'Wyatt Erp' ```
63684
As the question says, do I have to do in order to print Unicode characters to the output console? And what settings do I have to use? Right now I have this code: ``` wchar_t* text = L"the 来"; wprintf(L"Text is %s.\n", text); return EXIT_SUCCESS; ``` and it prints: `Text is the ?.` I've tried to change the output console's font to MS Mincho, Lucida Console and a bunch of others but they still don't display the japanese character. So, what do I have to do?
This is code that works for me (VS2017) - project with Unicode enabled ``` #include <stdio.h> #include <io.h> #include <fcntl.h> int main() { _setmode(_fileno(stdout), _O_U16TEXT); wchar_t * test = L"the 来. Testing unicode -- English -- Ελληνικά -- Español." ; wprintf(L"%s\n", test); } ``` This is console [![output](https://i.stack.imgur.com/ZDf9q.png)](https://i.stack.imgur.com/ZDf9q.png) After copying it to the Notepad++ I see the proper string **the 来. Testing unicode -- English -- Ελληνικά -- Español.** OS - Windows 7 English, Console font - Lucida Console Edits based on comments ======================= I tried to fix the above code to work with VS2019 on Windows 10 and best I could come up with is this ``` #include <stdio.h> int main() { const auto* test = L"the 来. Testing unicode -- English -- Ελληνικά -- Español."; wprintf(L"%s\n", test); } ``` When run it "as is" I see [![Default console settings](https://i.stack.imgur.com/TNVu4.png)](https://i.stack.imgur.com/TNVu4.png) When it is run with console set to Lucida Console fond and UTF-8 encoding I see [![Console switched to UTF-8](https://i.stack.imgur.com/g8WNO.png)](https://i.stack.imgur.com/g8WNO.png) As the answer to 来 character shown as empty rectangle - I suppose is the limitation of the font which does not contain all the Unicode gliphs When text is copied from the last console to Notepad++ all characters are shown correctly
64031
I recently started developing my first serious project in PHP, a MVC completely build by myself, which is quite a challenge, when being new to OOP. So the main struggle of the whole project has, and is, my router. It's really important, so I want to have a... great?... router, that just works - but without compromising functionality. Creating a router in itself wasn't really a challenge (Might be because I do it a wrong way), but after having made a basic router that did the job, I realized the 2 main problems. GET functionality and folders. The challenge is pretty URLs AND being able to load controllers from specific folder (or subfolders of it), executing specific method and passing in GET values. I tried, and it works. But it's really just a mess: ``` class router { /** * Contains the path of the controller to be loaded. * This will be extended if the "bit" does not exist as a file. * This makes it possible to put controllers into folder. * */ public static $path = null; /** * Contains the name of the file to be loaded. * This is also used when instantiating the controller, as the name of the class inside the file, and the name of the file, should be identical. * */ public static $file = null; /** * Contains the name of the method to be run inside the controller * */ public static $method = null; /** * This function is run at the index file, and should only be run once. Running it twice serves no purpose, and will just result in errors. * It fetches the controller, and runs specified method inside the controller - or shows error 'notfound'. * If more parameters are specified than just the path of the controller, the controllers name and the method to be run, it will pass theese to the * get helper, if loaded. * * The get helper must be autoloaded though, because the get parameters are passed to the get helper before running the content of the controller. */ public static function dispatch() { // Remove Simple MVC's location from request $request = str_replace(config::get('routes/path'), '', $_SERVER['REQUEST_URI']); if(!$request) { $request = config::get('routes/defaultController'); } // Split request into array $path = explode('/', $request); // Go trough array foreach($path as $bit) { // Check whether the method already has been set if(self::$method == null) { // Check whether to file to load already has been set if(self::$file == null) { // Check if a file exists at the already defined 'path' with the name of bit if(file_exists('app/controllers/' . self::$path . $bit . '.php')) { // Set file name self::$file = $bit; // Require in the file require('app/controllers/' . self::$path . self::$file . '.php'); // Instantiate controller $controller = new self::$file(); // If file does not exist } else { // Add the bit to the path self::$path .= $bit . '/'; } // If file already has been loaded } else { // Check whether 'bit' method exists in the controller if(method_exists($controller, $bit)) { // Set method to 'bit' self::$method = $bit; } } // If method already has been defined, check whether the 'get' helper has been loaded } elseif(helper::isLoaded('get')) { // Push 'bit' to the 'get' helper array_push(get::$values, $bit); } } // Check whether the controller has been instantiated if(isset($controller)) { // Check whether the method has been set if(self::$method == null) { // If method has not been set, run defaultFunction $controller->defaultFunction(); // If method has been set } else { // Run defined method $method = self::$method; $controller->$method(); } // If controller is not set } else { // Show 'notfound' error error::show('notfound'); } } } ``` The `dispatch()` method is simply run at the index file, which the .htaccess file just redirects all requests to. The request is then split into an array, which a `foreach` then go through and first of it tries to find a file with the name of 'bit', if it does not exist it add the 'bit' to the path from the controllers folder. This makes subfolders possible. When it has the file, it continues until it has a method. When a method is defined, all remaining 'bits' get passed to an array in the 'GET' helper. But this being such a mess, I'm hoping for opinions and advice.
Unfortunately, this is a very large question to ask. So there will be gaps in my answer but i will answer it best i can using code where possible. You do not want to couple your router with the controllers. They both do different things. If you do combine them, you end up with a mess (as you have found out). ``` class Router { private $routes = array(); public function addRoute($pattern, $tokens = array()) { $this->routes[] = array( "pattern" => $pattern, "tokens" => $tokens ); } public function parse($url) { $tokens = array(); foreach ($this->routes as $route) { preg_match("@^" . $route['pattern'] . "$@", $url, $matches); if ($matches) { foreach ($matches as $key=>$match) { // Not interested in the complete match, just the tokens if ($key == 0) { continue; } // Save the token $tokens[$route['tokens'][$key-1]] = $match; } return $tokens; } } return $tokens; } } ``` That class (which i quickly wrote just now so it's not perfect and may need adjusting to suit your use case). Then to use the class you would register your "routes" and then parse something through them (i.e. the URL) ``` $router = new Router(); $router->addRoute("/(profile)/([0-9]{1,6})", array("profile", "id")); $router->addRoute("/(.*)", array("catchall")); print_r($router->parse($_SERVER['REQUEST_URI'])); ``` If you browse to `/profile/23232` It will return: `Array ( [profile] => profile [id] => 23232 )` If you browse to `/asdasd` Array ( [catchall] => asdasd ) That's your router done. Next step. Execute the controller. First step, is to create a factory (i've spoken about this in more detail on my blog "[Practical use of the Factory Pattern, Polymorphism and Interfaces in PHP](https://www.coderprofile.com/coder/VBAssassin/blog/2/practical-use-of-the-factory-pattern-polymorphism-and-interfaces-in-php)"). The factory will then take the router and combine it with your logic to construct the correct controller instance which it then returns. This code (using the Router class above): ``` $router = new Router(); $router->addRoute("/(profile)/([0-9]{1,6})", array("profile", "id")); $router->addRoute("/Controller/(Login)", array("Controller")); $router->addRoute("/(.*)", array("catchall")); abstract class Controller { abstract public function execute(); } class ControllerLogin extends Controller { public function execute() { print "Logged in..."; } } class ControllerFactory { public function createFromRouter(Router $router) { $result = $router->parse($_SERVER['REQUEST_URI']); if (isset($result['Controller'])) { if (class_exists("Controller{$result['Controller']}")) { $controller = "Controller{$result['Controller']}"; return new $controller(); } } } } $factory = new ControllerFactory(); $controller = $factory->createFromRouter($router); if ($controller) { $controller->execute(); } else { print "Controller Not Found"; } ``` Will output `Logged in...` if you enter `/Controller/Login` in the URL. `Controller Not Found` if you enter any other URL. If you fully understand the above and mix it in with your own custom style and requirements. You will be able to create a very flexible code design :) Who says routes must come from the URL (they could come from the command line). No problem if you decouple the router from the controllers (which was achieved by using the factory as the middle man). There is still much you can add to refine it such as the way the controllers are loaded is very "raw" to say the least. You would also want to tweak the error reporting if the router/controller can't be found and create the routes in the format you desire. Have fun :)
64557
I am trying to copy a file into another folder, here is my code. ```cs private static void CopyDirectory(DirectoryInfo source, DirectoryInfo target) { foreach (var sourceFilePath in Directory.GetFiles(source.FullName)) { FileInfo file; if(IsAccesable(sourceFilePath, out file)) { file.CopyTo(target.FullName); //ERROR HERE } else { //DO WORKAROUND } } foreach(var sourceSubDirectoryPath in Directory.GetDirectories(source.FullName)) { DirectoryInfo directory; if(IsAccesable(sourceSubDirectoryPath, out directory)) { var targetSubDictionary = target.CreateSubdirectory(Path.Combine(target.FullName, sourceSubDirectoryPath)); CopyDirectory(directory, targetSubDictionary); } else { //DO WORKAROUND } } } ``` I keep getting the error message: The target path "" is a directory and not a file Full sourcePath: ``` "c:\\Hypixel Bots Interface\\.gitattributes" ``` Full targetPath: ``` "C:\\Users\\wout\\source\\repos\\FileCloner\\FileCloner\\bin\\Debug\\net5.0\\Target\\Hypixel Bots Interface" ```
``` def product_index(request): title = "My Products" products = Product.objects.all() order = get_cart(request) cart = Order.objects.get(id=order.id, complete=False) items = cart.orderitem_set.all() # Changes for product in products: qty = 0 if items.filter(product=product).exists(): qty = items.get(product=product).quantity setattr(product, 'quantity_in_cart', qty) context = { 'title' : title, 'products' : products, 'cart' : cart, 'items': items } return render(request, "store/product_index.html", context) ```
64770
I have an array of complex objects, which may contain arrays of more objects. I want to convert these to a CSV file. Whenever there's a list of objects, the data is parsed as `[object Object]`. If a person has two emails, for example, I want to print these emails in two lines, and so on for each object. Addresses may be concatenated to one string, for example "France, Paris, someStreet 15". The code is in this [pen](https://codepen.io/anon/pen/ewajNy). Here's the data: ``` var names = [ { Name: [{First: "Peter", Last:"john"}], WorkPlace: [{Company: "Intel", emails: ["jack@intell.com","admin@intell.com"]}], Age: 33.45, Adress: [{Country:"UK", city: "London", street:"Oak", strtNumber:16}, {Country:"Italy", city: "MIlan", street:"Zabin", strtNumber:2}] }, { Name: [{First: "jack", Last:"Smith"}], WorkPlace: [{Company: "Intel", emails: ["jack@intell.com","admin@intell.com"]}], Age: 30, Adress: [{Country:"Portugal", city: "Lisbon", street:"crap", strtNumber:144}, {Country:"Greece", city: "Athenes", street:"Hercules", strtNumber:55}] }, { Name: [{First: "jon", Last:"snow"}], WorkPlace: [{Company: "Intel", emails: ["jack@intell.com","admin@intell.com"]}], Age: 50, Adress: [{Country:"Middle earth", city: "Winterfell", street:"raven", strtNumber:4345}, {Country:"Narnia", city: "Jacksonvile", street:"Great crap", strNumber:34}] }, ]; ``` Right now this is the output: [![enter image description here](https://i.stack.imgur.com/Xjh7t.png)](https://i.stack.imgur.com/Xjh7t.png)
You can use [`setdefault()`](https://docs.python.org/3/library/stdtypes.html#dict.setdefault) to set the initial values. As you loop through just set the appropriate default or use `get` to get the inner values or zero: ``` d = {} with open('data.txt') as table: next(table) for line in table: (AAA, BBB, CCC) = map(str.strip, line.split("|")) outer = d.setdefault(AAA, {}) outer[CCC] = outer.get(CCC, 0) + int(BBB) ``` **result:** ``` {'zzz': {'xy': 150, 'xz': 700}, 'xxx': {'xy': 300, 'xz': 900}} ```
64813
I'm interested what's the **average** line number per **method or class**. Programming language is **JAVA** and it's an **Android** project. I know there is no specific number, but I'm interested what's the ***good programming practice***? **EDIT:** For example in android I have 10 buttons *(3 for action bar, 7 for every day of the week so I can quickly choose some day of the week and get relevant information and so on, doesn't really matter what the application is about)* and only this "type of code" needs ~100 lines of code (per button I need at least 10 lines of code to **initialize** it and set up a **onClick listener**), is there a way to shrink this down a bit? ``` someButton = (Button) findViewById(R.id.button); someButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // do something } }); ```
Since we're talking Java we're implicitly discussing OOP. Your primary concern is therefore creating highly cohesive classes with low coupling. The number of lines in a method or methods in a class is not an indicator of either. It is however a by-product of achieving both. Your classes is much more likely to have concise well defined method that have a sole purpose if you design with these principles in mind. In other words, don't go chasing metrics, focus on good design and principles. If you want some hard facts then [this question](https://stackoverflow.com/questions/312642/how-many-classes-per-package-methods-per-class-lines-per-method) follows a similar track.
65135
I am getting the below error in JMeter log while running via jenkins. I am using JMeter version 2.11r. ``` The logs are: 2017/09/14 17:00:16 INFO - jmeter.util.JMeterUtils: Setting Locale to en_US 2017/09/14 17:00:16 INFO - jmeter.JMeter: Loading user properties from: E:\J-Meter\bin\user.properties 2017/09/14 17:00:16 INFO - jmeter.JMeter: Loading system properties from: E:\J-Meter\bin\system.properties 2017/09/14 17:00:16 INFO - jmeter.JMeter: Copyright (c) 1998-2014 The Apache Software Foundation 2017/09/14 17:00:16 INFO - jmeter.JMeter: Version 2.11 r1554548 2017/09/14 17:00:16 INFO - jmeter.JMeter: java.version=1.8.0_121 2017/09/14 17:00:16 INFO - jmeter.JMeter: java.vm.name=Java HotSpot(TM) 64-Bit Server VM 2017/09/14 17:00:16 INFO - jmeter.JMeter: os.name=Windows 8.1 2017/09/14 17:00:16 INFO - jmeter.JMeter: os.arch=amd64 2017/09/14 17:00:16 INFO - jmeter.JMeter: os.version=6.3 2017/09/14 17:00:16 INFO - jmeter.JMeter: file.encoding=Cp1252 2017/09/14 17:00:16 INFO - jmeter.JMeter: Default Locale=English (United States) 2017/09/14 17:00:16 INFO - jmeter.JMeter: JMeter Locale=English (United States) 2017/09/14 17:00:16 INFO - jmeter.JMeter: JMeterHome=E:\J-Meter 2017/09/14 17:00:16 INFO - jmeter.JMeter: user.dir =C:\Program Files (x86)\Jenkins\workspace\J-meter 2017/09/14 17:00:16 INFO - jmeter.JMeter: PWD =C:\Program Files (x86)\Jenkins\workspace\J-meter 2017/09/14 17:00:16 INFO - jmeter.JMeter: IP: 10.150.246.100 Name: NOD-AF1-lo-D1N FullName: NOD-AF1-lo-D1N.timesgroup.com 2017/09/14 17:00:16 INFO - jmeter.JMeter: Loaded icon properties from org/apache/jmeter/images/icon.properties 2017/09/14 17:00:17 INFO - jmeter.engine.util.CompoundVariable: Note: Function class names must contain the string: '.functions.' 2017/09/14 17:00:17 INFO - jmeter.engine.util.CompoundVariable: Note: Function class names must not contain the string: '.gui.' 2017/09/14 17:00:17 INFO - jmeter.gui.action.LookAndFeelCommand: Using look and feel: javax.swing.plaf.metal.MetalLookAndFeel [Metal, CrossPlatform] 2017/09/14 17:00:17 INFO - jmeter.util.BSFTestElement: Registering JMeter version of JavaScript engine as work-round for BSF-22 2017/09/14 17:00:18 INFO - jmeter.protocol.http.sampler.HTTPSamplerBase: Cannot find .className property for htmlParser, using default 2017/09/14 17:00:18 INFO - jmeter.protocol.http.sampler.HTTPSamplerBase: Parser for text/html is 2017/09/14 17:00:18 INFO - jmeter.protocol.http.sampler.HTTPSamplerBase: Parser for application/xhtml+xml is 2017/09/14 17:00:18 INFO - jmeter.protocol.http.sampler.HTTPSamplerBase: Parser for application/xml is 2017/09/14 17:00:18 INFO - jmeter.protocol.http.sampler.HTTPSamplerBase: Parser for text/xml is 2017/09/14 17:00:18 INFO - jmeter.protocol.http.sampler.HTTPSamplerBase: Parser for text/vnd.wap.wml is org.apache.jmeter.protocol.http.parser.RegexpHTMLParser 2017/09/14 17:00:18 INFO - jmeter.gui.util.MenuFactory: Skipping org.apache.jmeter.protocol.http.control.gui.WebServiceSamplerGui 2017/09/14 17:00:18 INFO - jmeter.gui.util.MenuFactory: Skipping org.apache.jmeter.protocol.http.modifier.gui.ParamModifierGui 2017/09/14 17:00:18 INFO - jorphan.exec.KeyToolUtils: keytool found at 'C:\Program Files\Java\jre1.8.0_121\bin\keytool' 2017/09/14 17:00:18 INFO - jmeter.protocol.http.proxy.ProxyControl: HTTP(S) Test Script Recorder SSL Proxy will use keys that support embedded 3rd party resources in file E:\J-Meter\bin\proxyserver.jks 2017/09/14 17:00:18 WARN - jmeter.gui.util.MenuFactory: Could not instantiate org.apache.jmeter.protocol.smtp.sampler.gui.SmtpSamplerGui java.lang.NullPointerException at sun.awt.shell.Win32ShellFolder2.access$200(Unknown Source) at sun.awt.shell.Win32ShellFolder2$1.call(Unknown Source) at sun.awt.shell.Win32ShellFolder2$1.call(Unknown Source) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at sun.awt.shell.Win32ShellFolderManager2$ComInvoker$3.run(Unknown Source) ```
Some Java developers are a little bit relaxed when it comes to handling edge situations (or they simply don't have enough qualification) as it's evidenced by [JENKINS-37013](https://issues.jenkins-ci.org/browse/JENKINS-37013) (even [Workspace Whitespace Replacement Plugin](https://wiki.jenkins.io/display/JENKINS/Workspace+Whitespace+Replacement+Plugin) exists) I would recommend re-installing your Java, Jenkins and JMeter into folders without spaces and special characters in path and the issue should go away, for example: ``` c:\apps\java c:\apps\jenkins c:\apps\jmeter ``` Just in case check out [Continuous Integration 101: How to Run JMeter With Jenkins](https://www.blazemeter.com/blog/continuous-integration-101-how-run-jmeter-jenkins) article for more details.
65629
I am preparing for GRE MATH SUBJECT TEST, I have reviewed many problems, some of these problems are not in GRE Math Practice books, but they are in some other books. I found the following problem, but not sure if it can be a GRE problem or no. And I do not even know how to start; > > Let $P$ be a polynomial with integer coefficients satisfying $P(0)=1, P(1)=3, P'(0)=-1, P'(1)=10$. What is the minimum possible degree of $P$? > > > (A) $3$ > > > (B) $4$ > > > (C) $5$ > > > (D) $6$ > > > (E) No such $P$ exists. > > >
Yes, eigenvectors and eigenvalues are defined only for linear maps. And that map $f$ maps elements of $\Bbb R^2$ into elements of $\Bbb R^2$. In particular, it maps $(3,2)$ into $(4,3)$. Thinking about it as acting on vectors, by acting on their initial and final points, is misleading.
65661
Currently I have a table with schema as follows: ``` mData | CREATE TABLE `mData` ( `m1` mediumint(8) unsigned DEFAULT NULL, `m2` smallint(5) unsigned DEFAULT NULL, `m3` bigint(20) DEFAULT NULL, `m4` tinyint(4) DEFAULT NULL, `m5` date DEFAULT NULL, KEY `m_m1` (`m1`) USING HASH, KEY `m_date` (`m5`), KEY `m_m2` (`m2`), KEY `m_combined` (`m1`,`m2`,`m5`), KEY `m1_tradeday` (`m1`,`m5`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci /*!50100 PARTITION BY RANGE ( YEAR(m5)) SUBPARTITION BY HASH (MONTH(m5)) (PARTITION p2013 VALUES LESS THAN (2014) (SUBPARTITION dec_2013 ENGINE = InnoDB, SUBPARTITION jan_2013 ENGINE = InnoDB, SUBPARTITION feb_2013 ENGINE = InnoDB, SUBPARTITION mar_2013 ENGINE = InnoDB, SUBPARTITION apr_2013 ENGINE = InnoDB, SUBPARTITION may_2013 ENGINE = InnoDB, SUBPARTITION jun_2013 ENGINE = InnoDB, SUBPARTITION jul_2013 ENGINE = InnoDB, SUBPARTITION aug_2013 ENGINE = InnoDB, SUBPARTITION sep_2013 ENGINE = InnoDB, SUBPARTITION oct_2013 ENGINE = InnoDB, SUBPARTITION nov_2013 ENGINE = InnoDB), PARTITION p2014 VALUES LESS THAN (2015) (SUBPARTITION dec_2014 ENGINE = InnoDB, SUBPARTITION jan_2014 ENGINE = InnoDB, SUBPARTITION feb_2014 ENGINE = InnoDB, SUBPARTITION mar_2014 ENGINE = InnoDB, SUBPARTITION apr_2014 ENGINE = InnoDB, SUBPARTITION may_2014 ENGINE = InnoDB, SUBPARTITION jun_2014 ENGINE = InnoDB, SUBPARTITION jul_2014 ENGINE = InnoDB, SUBPARTITION aug_2014 ENGINE = InnoDB, SUBPARTITION sep_2014 ENGINE = InnoDB, SUBPARTITION oct_2014 ENGINE = InnoDB, SUBPARTITION nov_2014 ENGINE = InnoDB), PARTITION p2015 VALUES LESS THAN (2016) (SUBPARTITION dec_2015 ENGINE = InnoDB, SUBPARTITION jan_2015 ENGINE = InnoDB, SUBPARTITION feb_2015 ENGINE = InnoDB, SUBPARTITION mar_2015 ENGINE = InnoDB, SUBPARTITION apr_2015 ENGINE = InnoDB, SUBPARTITION may_2015 ENGINE = InnoDB, SUBPARTITION jun_2015 ENGINE = InnoDB, SUBPARTITION jul_2015 ENGINE = InnoDB, SUBPARTITION aug_2015 ENGINE = InnoDB, SUBPARTITION sep_2015 ENGINE = InnoDB, SUBPARTITION oct_2015 ENGINE = InnoDB, SUBPARTITION nov_2015 ENGINE = InnoDB), PARTITION p2016 VALUES LESS THAN (2017) (SUBPARTITION dec_2016 ENGINE = InnoDB, SUBPARTITION jan_2016 ENGINE = InnoDB, SUBPARTITION feb_2016 ENGINE = InnoDB, SUBPARTITION mar_2016 ENGINE = InnoDB, SUBPARTITION apr_2016 ENGINE = InnoDB, SUBPARTITION may_2016 ENGINE = InnoDB, SUBPARTITION jun_2016 ENGINE = InnoDB, SUBPARTITION jul_2016 ENGINE = InnoDB, SUBPARTITION aug_2016 ENGINE = InnoDB, SUBPARTITION sep_2016 ENGINE = InnoDB, SUBPARTITION oct_2016 ENGINE = InnoDB, SUBPARTITION nov_2016 ENGINE = InnoDB), PARTITION pmax VALUES LESS THAN MAXVALUE (SUBPARTITION dec_max ENGINE = InnoDB, SUBPARTITION jan_max ENGINE = InnoDB, SUBPARTITION feb_max ENGINE = InnoDB, SUBPARTITION mar_max ENGINE = InnoDB, SUBPARTITION apr_max ENGINE = InnoDB, SUBPARTITION may_max ENGINE = InnoDB, SUBPARTITION jun_max ENGINE = InnoDB, SUBPARTITION jul_max ENGINE = InnoDB, SUBPARTITION aug_max ENGINE = InnoDB, SUBPARTITION sep_max ENGINE = InnoDB, SUBPARTITION oct_max ENGINE = InnoDB, SUBPARTITION nov_max ENGINE = InnoDB)) */ | ``` m1, m2, and m5 are set as index in this table, unique/primary are not applicable in my case. As the data is getting bigger (100,000 new row a day), the update command is getting very slow. I would like to know if there are any ways to improve the following statement. ``` update mData as a join (select * from mData where m1 = 326 and m5 = '2015- 07-06' ) as b on a.m5 > b.m5 and a.m1 = b.m1 and a.m2 = b.m2 and a.m3 = b.m3 set a.m4 = 0; ``` I am quite sure that in select statement, if I replace `mData as a` to `(select * from mData where m1 = 326)`, the executive time could largely reduce (from 5 sec to less than 1 sec). However, it is not possible to do the same in `UPDATE` statement. Is there any solution for this, to speed up update? P.S. the table has been partitioned by month(m5) and year(m5) Here is the EXPLAIN partitions for my join query, very messy, hope you don't mind. Adding ' and a.m5 > '2015-07-06' does improve the perfomance, query time drops from 0.68 sec to 0.2 sec. ``` explain partitions (select * from (select * from mData where m1 = 326) as a join (select * from mData where m1 = 326 and m5= '2015-07-06') as b on a.m5 > b.m5 and a.m1 = b.m1 and a.m2 = b.m2 and a.m3 = b.m3 and a.m5 > '2015-07-06'); ``` | id | select\_type | table | partitions | type | possible\_keys | key | key\_len | ref | rows | Extra | +----+-------------+------------+----------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- ------------------------------+------+------------------------------------------ --------+--------------+---------+------+------+-------------------------------- + | 1 | PRIMARY | | NULL | ALL | NULL | NULL | NULL | NULL | 358 | | | 1 | PRIMARY | | NULL | ALL | NULL | NULL | NULL | NULL | 1073 | Using where; Using join buffer | | 3 | DERIVED | mData | p2015\_jul\_2015 | ref | m\_m1,m\_m5,m\_combined,m1\_m5 | m1\_m5 | 8 | | 357 | Using where | | 2 | DERIVED | mData | p2013\_dec\_2013,p2013\_jan\_2013,p2013\_feb\_2013,p 2013\_mar\_2013,p2013\_apr\_2013,p2013\_may\_2013,p2013\_jun\_2013,p2013\_jul\_2013,p2013\_ aug\_2013,p2013\_sep\_2013,p2013\_oct\_2013,p2013\_nov\_2013,p2014\_dec\_2014,p2014\_jan\_2 014,p2014\_feb\_2014,p2014\_mar\_2014,p2014\_apr\_2014,p2014\_may\_2014,p2014\_jun\_2014,p 2014\_jul\_2014,p2014\_aug\_2014,p2014\_sep\_2014,p2014\_oct\_2014,p2014\_nov\_2014,p2015\_ dec\_2015,p2015\_jan\_2015,p2015\_feb\_2015,p2015\_mar\_2015,p2015\_apr\_2015,p2015\_may\_2 015,p2015\_jun\_2015,p2015\_jul\_2015,p2015\_aug\_2015,p2015\_sep\_2015,p2015\_oct\_2015,p 2015\_nov\_2015,p2016\_dec\_2016,p2016\_jan\_2016,p2016\_feb\_2016,p2016\_mar\_2016,p2016\_ apr\_2016,p2016\_may\_2016,p2016\_jun\_2016,p2016\_jul\_2016,p2016\_aug\_2016,p2016\_sep\_2 016,p2016\_oct\_2016,p2016\_nov\_2016,pmax\_dec\_max,pmax\_jan\_max,pmax\_feb\_max,pmax\_ma r\_max,pmax\_apr\_max,pmax\_may\_max,pmax\_jun\_max,pmax\_jul\_max,pmax\_aug\_max,pmax\_sep\_ max,pmax\_oct\_max,pmax\_nov\_max | ref | m\_m1,m\_combined,m1\_m5 | m\_m1 | 4 | | 1074 | Using where | Below is the query explain asked by "Rick James" ``` EXPLAIN PARTITIONS select * from ccass_data where sid = 326 and trade_day = '2015-07-06'; | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+------------+----------------+------+--------------------------------------------------+--------------+---------+-------------+------+-------------+ | 1 | SIMPLE | mData | p2015_jul_2015 | ref | m_m1,m_m5,m_combined,m1_m5 | m1_m5 | 8 | const,const | 357 | Using where | ```
**DO** make relationships between tables explicit by declaring foreign key constraints. I do not see any good reason for not doing this. Why are foreign key constraints a good idea? * Foreign key constraints are a simple way to help safeguard data integrity/consistency. * Constraints (not just foreign key ones) can also be seen as a form of "living documentation" (making things explicit and therefore discoverable, without having to guess). * You might still want to validate inserts in code; in that case you can look at foreign key constraints as a "safety net", in case your code fails. (Regarding the second bullet point above: I have to work with one legacy database which is lacking some foreign key constraints that should by all means have been declared. This means that every time I have to make a change to it, I might inadvertently break an application that makes certain assumptions about the schema that aren't obvious by looking at the schema. Working with this database is very painful and error-prone. If I could change one thing about this database, it would be to add all missing constraints.)
65747
consider the following code: ``` class A { friend class B; friend class C; }; class B: virtual private A { }; class C: private B { }; int main() { C x; //OK default constructor generated by compiler C y = x; //compiler error: copy-constructor unavailable in C y = x; //compiler error: assignment operator unavailable in C } ``` The MSVC9.0 (the C++ compiler of Visual Studio 2008) does generate the default constructor but is unable to generate copy and assignment operators for C although C is a friend of A. Is this the expected behavior or is this a Microsoft bug? I think the latter is the case, and if I am right, can anyone point to an article/forum/... where this issue is discussed or where microsoft has reacted to this bug. Thank you in advance. P.S. Incidentally, if BOTH private inheritances are changed to protected, everything works P.P.S. I need a proof, that the above code is legal OR illegal. It was indeed intended that a class with a virtual private base could not be derived from, as I understand. But they seem to have missed the friend part. So... here it goes, my first bounty :)
Your code compiles fine with Comeau Online, and also with MinGW g++ 4.4.1. I'm mentioning that just an "authority argument". From a standards POV access is orthogonal to virtual inheritance. The only problem with virtual inheritance is that it's the most derived class that initializes the virtually-derived-from class further up the inheritance chain (or "as if"). In your case the most derived class has the required access to do that, and so the code should compile. MSVC also has some other problems with virtual inheritance. So, yes, * the code is valid, and * it's an MSVC compiler bug. FYI, that bug is still present in MSVC 10.0. I found a [bug report](https://connect.microsoft.com/VisualStudio/feedback/details/552586/inherting-noncopyable-base-allows-equal-sign-initialization) about a similar bug, confirmed by Microsoft. However, with just some cursory googling I couldn't find this particular bug.
65826
I use the function below to add CSS classes (blue, red, pink...) in a DIV `.container` from a select `#selcolor`. Is it possible to use the same function in other select tags with different IDs? In this case the classes (blue, red, pink...) would not be added to the DIV `.container` with it the variable "div\_action" function would have to be modified. ``` function select_changed() { jQuery('select#selcolor').each(function() { var selected = jQuery(this).val(); var div_action = '.container'; if(selected == '') { jQuery(div_action).addClass(''); } if(selected == 'blue') { jQuery(div_action).addClass('blue'); } else { jQuery(div_action).removeClass('blue'); } if(selected == 'pink') { jQuery(div_action).addClass('pink'); } else { jQuery(div_action).removeClass('pink'); }; if(selected == 'red') { jQuery(div_action).addClass('red'); } else { jQuery(div_action).removeClass('red'); }; }); } $('select#selcolor').change(function() { select_changed(); }); <!-- This is HTML --> <select name="selcolor" id="selcolor" class="form-control"> <option value=''>Select Color</option> <option value="blue">Blue</option> <option value="pink">Pink</option> <option value="red">Red</option> </select> ```
`event.currentTarget.id` is used to get the `id` of the current target. So you can use this function for other select box also. > > *Note: I have assumed the select box as a single select and simplified the code a bit.* > > > ``` function select_changed(id) { jQuery('select#'+id).each(function() { var selected = jQuery(this).val(); var div_action = '.container'; jQuery(div_action).removeClass("blue pink red"); jQuery(div_action).addClass(selected); }); } $('select').change(function(event) { select_changed(event.currentTarget.id); }); ```
66011
I do not see where `s` is defined. Guru will not tell me. All I get is "no object for identifier" but it knows about the `k` right beside it. Here is a snippet that is typical of the linked code: ``` func getIndexAndRemainder(k uint64) (uint64, uint64) { return k / s, k % s } ``` The one letter variable name definitely makes it harder to grep around for. I have looked for the usual suspects: `var s uint64`, `s := ...`, and nothing. Clearly it needs to be a global value defined somewhere. This leaves me with two questions: 1. Where is `s` coming from? 2. How would I find it without asking here? EDIT: For others who stumble on this. Guru failed me because I did not checkout the source for the package under a proper Go workspace by placing the git clone under /some/path/src and setting the `GOPATH` to /some/path. So while I thought `GOPATH=. guru definition s` would work, the `GOPATH` was ignored. guru could find `k` because it is in the file but it did not know how to look in other files. My grep failed cause `const` uses a simple `=` not a `:=`. I will remember this when grepping in the future.
It is defined in `go-datastructures/bitarray/block.go`: ``` // s denotes the size of any element in the block array. // For a block of uint64, s will be equal to 64 // For a block of uint32, s will be equal to 32 // and so on... const s = uint64(unsafe.Sizeof(block(0)) * 8) ``` As the variable `s` was not defined in the function, and it was not prefixed by a package name or alias, it had to be a global (variable or constant) of the `bitarray` package. Once that was known, I went through every file in the folder `go-datastructures/bitarray` that was not suffixed with `_test` and I looked for a top-level declaration for `s`.
66238
Got four tables; `users`, `company`, `company_branch` and `users_branch`. Users are people belonging to company. A company has got branches and a user can belong to a single branch at any given time. However, the users\_branch table exists to keep track of the history of changing from one branch to another. E.g. To get the current branch of a user with id 1, one would run a `SELECT company_id, company_branch_id FROM users_branch WHERE user_id = 1 ORDER BY created_at DESC LIMIT 1`. The challange I have is that am not able to figure out the correct not SQLAlchemy ORM syntax but also SQL raw to get list of users in a certain company at a given time and do so while returning the `users_id, users_email_address, company_id, company_name, compancy_branch_id and company_branch_name` for each entry. The queries I've tried so far either return nothing or they return repeated values in the users\_branch wheareas I only want the latest branch for each user [Here is the link](http://sqlfiddle.com/#!15/f47ba) to the sqlfiddle sample postgresql database. In SQAlchemy the models are `Users, Company, CompanyBranch, UsersBranch` as seen below: ``` class Users(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) email_address = Column(String(70), nullable=False, unique=True) class Company(Base): __tablename__ = 'company' id = Column(Integer, primary_key=True) created_at = Column(DateTime, server_default=text('NOW()'), nullable=False) created_by = Column(ForeignKey('users.id'), nullable=False) company_name = Column(String(100), nullable=False, unique=True) class CompanyBranch(Base): __tablename__ = 'company_branch' id = Column(Integer, primary_key=True) created_at = Column(DateTime, server_default=text('NOW()'), nullable=False) created_by = Column(ForeignKey('users.id'), nullable=False) company_id = Column(ForeignKey('company.id'), nullable=False) branch_name = Column(String(100), nullable=False, unique=True) class UsersBranch(Base): __tablename__ = 'users_branch' id = Column(Integer, primary_key=True) created_at = Column(DateTime, server_default=text('NOW()'), nullable=False) created_by = Column(ForeignKey('users.id'), nullable=False) user_id = Column(ForeignKey('users.id'), nullable=False) company_id = Column(ForeignKey('company.id'), nullable=False) company_branch_id = Column(ForeignKey('company_branch.id'), nullable=False) ```
The issue is that vba is very US-English centric. So either use `,` in place of `;` or use `.FormulaR1C1Local`: ``` Sub Call_Min() Dim i As Integer Dim limit As Integer limit = Sheets("AUX").Range("B6").Value Sheets("Sheet11").Activate 'ActiveSheet.Cells(6, 16).Select 'ActiveCell.Formula = "=SUM(Range("F6:I6"))" For i = 6 To limit 'MATCH(P6;F6:O6;0) Sheets("DATA").Range("P" & i).FormulaR1C1Local = "=MIN(R" & i & "C6:R" & i & "C15)" Sheets("DATA").Range("E" & i).FormulaR1C1Local = "=MATCH(R" & i & "C16;R" & i & "C6:R" & i & "C15;0)" Next i End Sub ``` See [here](https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba-macros) on how to avoid using `.Select` and why.
66567
I am scripting a ksh file where I am looking to return the file with the most number of lines in a directory. The script can only take one argument and must be a valid directory. I have the 2 error cases figured out but am having trouble with the files with max lines portion so far I have below: ``` #!/bin/ksh #Script name: maxlines.sh ERROR1="error: can only use 0 or 1 arguments.\nusage: maxlines.sh [directory]" ERROR2="error: argument must be a directory.\nusage: maxlines.sh [directory]\n" $1 if [[ $# -gt 1 ]] then printf "$ERROR1" exit 1 fi if [ ! -d "$1" ] then prinf "$ERROR2" fi for "$1" do [wc -l | sort -rn | head -2 | tail -1] ``` From what I have been finding the max lines will come from using wc, but am unsure of the formatting as I am still new to shell scripting. Any advice will help!
``` > for "$1" > do > [wc -l | sort -rn | head -2 | tail -1] ``` The `for` loop has a minor syntax error, and the square brackets are completely misplaced. You don't need a loop anyway, because `wc` accepts a list of file name arguments. ``` wc -l "$1"/* | sort -rn | head -n 1 ``` The top line, not the second line, will contain the file with the largest number of lines. Perhaps you'd like to add an option to trim off the number and return just the file name. If you wanted to loop over the files in `$1`, that would look like ``` for variable in list of items do : things with "$variable" done ``` where `list of items` could be the wildcard expression `"$1"/*` (as above}, and the `do` ... `done` take the place where you imagine you'd want square brackets. (Square brackets are used in comparisons; `[ 1 -gt 2 ]` runs the `[` command to compare two numbers. It can compare a lot of different things -- strings, files, etc. `ksh` also has a more developed variant `[[` which has some features over the traditional `[`.)
66903
I have found a basic URL structure for regular map tiles: ``` https://mts1.google.com/vt/lyrs=m@186112443&hl=x-local&src=app&x=1325&y=3143&z=13&s=Galile ``` What would be the URL structure to grab HYBRID map tiles from Google? I don't know why I can't find this information; it seems like it should be easy to find. Am I missing something simple? . I have been messing with the `lyrs` parameter, and I think that may be part of it. When pasting the above URL in a browser, Ive tried `lyrs=r`, `lyrs=h`,`lyrs=t` and they give different tiles. The closest I have come now is trying `lyrs=s`. It results in a Satellite tile being returned; but I do not know what I should put in for a HYBRID result. Maybe I am going about this all wrong.
You need an instance from the google map js class and an anonymous function then you can set the map object to give hybrid tiles:[How to get your image URL tiles? (google maps)](https://stackoverflow.com/questions/8241268/how-to-get-your-image-url-tiles-google-maps). Or maybe it's lyrs=y:<http://www.neongeo.com/wiki/doku.php?id=map_servers>. TRY: <http://mt1.google.com/vt/lyrs=y&x=1325&y=3143&z=13>
67357
I am currently writing a script in Python to log in on facebook and I want to send message to a friend. The script logs in to my facebook, and it manages to find my friend, but the message is not sent. I'm not 100% sure, but I think the problem is in the div tag/CSS on the text area (I commented out that piece of code). Screenshot: [Text doesn't appear here](https://i.stack.imgur.com/it9bZ.png) Here is my code: ``` from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome('C:\path\chromedriver.exe') driver.get('https://www.facebook.com/') username_box = driver.find_element_by_id('email') username_box.send_keys(USEREMAIL) passElem = driver.find_element_by_id("pass") passElem.send_keys(USERPASSWORD) passElem.send_keys(Keys.RETURN) userTargetUrl = "https://www.facebook.com/messages/t/" + "USERTAGET" driver.get(userTargetUrl) //The problem is here I think elem = driver.find_element_by_css_selector("div textarea.uiTextareaNoResize") while True: elem.send_keys("Test") elem.send_keys(Keys.RETURN) driver.find_element_by_id("u_0_t").click() ``` The error code i get is: ``` selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"div textarea.uiTextareaNoResize"} (Session info: chrome=63.0.3239.132) (Driver info: chromedriver=2.35.528161 (5b82f2d2aae0ca24b877009200ced9065a772e73),platform=Windows NT 10.0.15063 x86_64) ```
I solved this problem on [RU SO](https://ru.stackoverflow.com/questions/919234/%D0%9D%D0%B5-%D0%BC%D0%BE%D0%B3%D1%83-%D0%BD%D0%B0%D0%B9%D1%82%D0%B8-%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82-xpath-selenium-facebook-%D0%92%D0%B2%D0%B5%D0%B4%D0%B8%D1%82%D0%B5-%D1%81%D0%BE%D0%BE%D0%B1%D1%89%D0%B5%D0%BD%D0%B8%D0%B5/919670#919670)))) Briefly in steps: 1. Making the library import `from selenium.webdriver.common.action_chains import ActionChains` 2. Visited the site 3. Logged in 4. You have a friend list, you clicked on your friend's icon and a chat window has opened. *now what to do?))* 4. You need to place the cursor in the input line, in which the text is not written) Use for this `.click ()`, you can use any of your XPath, but here is a shorter one)) `driver.find_element_by_xpath("//*[@data-editor]").click()` 5. After pressing the `.click ()` method, the cursor is placed in the text input area. And now we need to enter the text, but use `.send_keys()` not with the pointer to the element, as you tried, but separately as an action (this is what the imported library is for)`actions = ActionChains(driver) actions.send_keys('HI') actions.perform()` Woo a la)))) [![enter image description here](https://i.stack.imgur.com/3i8mM.png)](https://i.stack.imgur.com/3i8mM.png) Well, after that `.click()` on the send icon or press Enter)))))
67407
I have a byte array: ``` private final static byte[][] ARRAY = { { (byte) 0xaa, (byte) 0xbb, (byte) 0xcc, (byte) 0xdd }, { (byte) 0x11, (byte) 0x22, (byte) 0x33, (byte) 0x44 } }; ``` Given an arbitrary byte array: ``` byte[] check = { (byte) 0x11, (byte) 0x22, (byte) 0x33, (byte) 0x44) }; ``` or ``` byte[] check2 = { (byte) 0x12, (byte) 0x23, (byte) 0x34, (byte) 0x45) }; ``` What's the best way to check if either `check` or `check2` is in `ARRAY` exactly as written (in the same order etc)? I can change `ARRAY` to any other data structure as needed but `check` and `check2` are provided as byte arrays.
You can use `Arrays.equals()` to compare two arrays. From the [javadoc](http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#equals(byte[],%20byte[])): > > Returns true if the two specified arrays of bytes are equal to one > another. Two arrays are considered equal if both arrays contain the > same number of elements, and all corresponding pairs of elements in > the two arrays are equal. > > > ``` byte[] check = { (byte) 0x11, (byte) 0x22, (byte) 0x33, (byte) 0x44 }; byte[] check2 = { (byte) 0x12, (byte) 0x23, (byte) 0x34, (byte) 0x45 }; int i = 0; for (; i < ARRAY.length; i++) { if (Arrays.equals(ARRAY[i], check)) { System.out.println("check[] found at index: " + i); break; } } if (i == ARRAY.length) { System.out.println("check[] not found"); } for (i = 0; i < ARRAY.length; i++) { if (Arrays.equals(ARRAY[i], check2)) { System.out.println("check2[] found at index: " + i); break; } } if (i == ARRAY.length) { System.out.println("check2[] not found"); } ``` ***Output :*** ``` check[] found at index: 1 check2[] not found ```
67589
I am using Entity Framework in order to create my models, but when I try to access the database from the *data connections* in Server Explorer, it does not work. I know the models are being created in the SQL Server Express instance running on my local machine, as I navigated to ``` Computer -> Program Files -> Microsoft SQL Server -> MSSQL10.SQLEXPRESS -> MSSQL -> DATA -> ``` and the database is in there. ![enter image description here](https://i.stack.imgur.com/lD7hw.png) Shouldn't my local instance of SQL Server Express show up in this window? ![enter image description here](https://i.stack.imgur.com/6yOA8.png) [I read over this article from Microsoft which explains where database is stored.](http://msdn.microsoft.com/en-us/data/jj591621.aspx)
Print quotes around it? ``` System.out.println("\"" + i + "\""); ```
68247
I have a table containing `positions` This table is as follows: ``` user_id | current | started_at | finished_at 2 | false | 10-07-2016 | 02-08-2016 1 | false | 19-07-2016 | 27-07-2016 1 | true | 29-07-2016 | null 3 | true | 20-07-2016 | null 3 | false | 01-07-2016 | 18-07-2016 ``` I'm sorting this table using a case to use either the `started_at` or `finished_at` date depending on whether `current` is true or false ``` SELECT * FROM positions ORDER BY CASE WHEN current = true THEN started_at ELSE finished_at END DESC ``` This works fine as expect but now I want to extract only the first row for each `user_id` So in my example data i'd like to only have the following returned. ``` user_id | current | started_at | finished_at 2 | false | 10-07-2016 | 02-08-2016 1 | true | 29-07-2016 | null 3 | true | 20-07-2016 | null ``` I was thinking this could be done with a `GROUP BY` but I can't get it to work without error or maybe I need a sub query, I'm not sure.
This is an excellent opportunity to use a window function. You can use the window function to create a query that looks like this: ``` SELECT user_id, current, started_at, finished_at, row_number() OVER (PARTITION BY user_id) AS row_number FROM positions ORDER BY CASE WHEN current = true THEN started_at ELSE finished_at END DESC ``` This will give you your original table with a new column "row\_number" that comes from the window function. You partition by user\_id because you want to get the row\_number by user. Use the ORDER clause you provided. To get the full answer just use this statement as a subquery, use the WHERE clause to only choose row\_number = 1, and pull all the fields you need. Window functions cannot be used in the WHERE clause, which is why you need the subquery. ``` SELECT user_id, current, started_at, finished_at FROM ( SELECT user_id, current, started_at, finished_at, row_number() OVER (PARTITION BY user_id) AS row_number FROM positions ORDER BY CASE WHEN current = true THEN started_at ELSE finished_at END DESC ) pos WHERE row_number= 1 ```
68694
I have a dataframe like this: ``` col1 col2 col3 col4 A W Z C F W P F E P Y C B C B C M A V C D O X A Y L Y D Q V R A ``` I want to filter if multiple columns have a certain value. For instance I want to filter the rows that contain `A`. As a result it should be: ``` col1 col2 col3 col4 A W Z C M A V C D O X A Q V R A ``` Since it is just a small representation of a large dataset, I cannot go with ``` df[(df['col1'].str.contains('A')) | (df['col2'].str.contains('A')) | (df['col3'].str.contains('A')) | (df['col4'].str.contains('A'))] ``` Is there any other way?
Here's a way you can do: ``` df[df.applymap(lambda x: x == 'A').any(1)] col1 col2 col3 col4 0 A W Z C 4 M A V C 5 D O X A 7 Q V R A ``` For multiple cases, you can do like `A`, `B`: ``` df[df.applymap(lambda x: x in ['A','B']).any(1)] ```
69199
I have a report I am doing with SSRS 2008 with some rows that have multiple elements inside them. On the preview the row automatically expands to support the extra elements but however when I export the report to Excel it appears only as a single row with just the one element displayed, although all the elements are there when I double click the row or manually expand it. I've checked everything...Can grow is set to true and the properties on the text box allows it's height to increase however it seems to ignore these. Here it is in the preview <http://tinypic.com/r/b4wbdg/8> In Excel <http://tinypic.com/r/r084g3/8> Sorry about the links to the pictures and not in this question
Came across this (again) recently and thought I'd share my take... Whether Excel correctly renders the height has to do with merged columns. Take note of your column alignments throughout all objects on the page. Any objects not tied to the data table itself (or embedded inside the data table) must be aligned with the columns of the table in question, at least for the cells that need to wrap text. If there is any overlap causing the table columns to be split and the cells of wrapped text to be re-merged, Excel will not recognize the row height by either setting the CanGrow to True or snapping the row to fit within Excel. In the original post, the user mentioned rows with multiple elements inside of them. It is possible that those elements caused the column to split for the surrounding subtotals or adjacent groups with wrapped text. Setting the CanGrow to False will simply prevent any automatic sizing of the row height by default for both the web view and Excel export, so I don't know if that's the ideal solution to this problem.
69669
I am trying to select some webelement on "<http://www.espncricinfo.com/england-v-new-zealand-2015/engine/match/743953.html>". Here I want to select total runs scored by the player and extras on first table except total runs. I have made below xpath but it is also taking total runs. may i know how to avoid "Total Runs" ``` //table[1][@class='batting-table innings']/tbody/tr/td[4] ``` Thanks in advance
Total runs has class `total-wrap` in the `<tr>` tag. You can look for element without this class using `not` ``` //table[1][@class='batting-table innings']/tbody/tr[not(@class='total-wrap')]/td[4] ```
69990
*Sorry for the long post, but I had to give as much info as possible to make this very vague question more specific.* My project's aim is to let users search a (huge) database of variety of products. * Each product is present under a category. * Each product will have 10 to 100 'specs' or 'features' by which the users will search. The most common usecase is: 1. User clicks on a category; then clicks various sub-categories if required. 2. User starts off with 1 or 2 criteria and searches for products. 3. User then keeps adding more criteria to the search to narrow down on the product. I have three main tables 'products', 'features\_enum' and 'features'. It is very important to let the data-entry users, create new 'features' on the fly, for the products - hence I am using EAV (anti)pattern. **Here are the structures of the tables:** ``` 'products' ID(PK), TITLE, CATEGORY (Indexed by CATEGORY) 'features_enum' ID(PK), TITLE 'features' P_ID, F_ID, VAL (Indexed by P_ID and then F_ID) ``` **A sample format of my main search query:** ``` SELECT p.ID, p.TITLE PROD_TITLE, fe.TITLE FEATURE_TITLE, f.VAL FROM products p, features f, features_enum fe WHERE p.CATEGORY = 57 AND p.ID = f.P_ID AND f.F_ID = fe.ID AND ( (f.F_ID = 1 AND f.VAL = 'Val1') AND (f.F_ID = 2 AND f.VAL = 'Val2') AND ... (f.F_ID = N AND f.VAL = 'ValN') AND ) ``` **My Experimentation So Far:** Due to my limited knowledge and experience in DBs, I hit a wall with theoretical planning. So, I generated a large set of test data to simply see what will work. All three tables had 500,000 test rows. Here are the avg. run times of the main search query: 1. InnoDB without indexing: 90s. 2. InnoDB with indexing: 15s. **0.3s after buffer pool size increase** 3. MyISAM without indexing: 9s. 4. MyISAM with indexing: 0.7s. 5. MyISAM with indexing + FIXED row type: 0.16s. Test machine - Pentium 4 1.9GHz, 1.5GB RAM, IDE HDD, Win7. I have basically not done anything to optimize other than indexing. So there might be a ton of things that I missed, that could have made InnoDB run faster. **InnoDB buffer pool size was set to 16M (!!); I incremented it to 128M. Now, InnoDB is really fast. So one big reason for me leaning toward MyISAM is now gone.** Maybe there is more that I can do. **Some points and long term usage estimates about the project:** * 20 new products added daily, at roughly 20 x 100'specs' = 2000 record writes per day. * 1,000,000 page visits, and in worst case - same amount of search query runs per day. * Total record count for the tables is expected to reach 5,000,000 each. * Writes will be made by a semi-controlled group of people, where as read is public. * There are no complex 'transaction' type writes. The most complex write I can think of right now is - [one product row + 100 feature rows max] - at one shot * Require only a couple of constraints, but if necessitated by choice of MyISAM, I can enforce them at the application level itself. * DB access from other parts of the app - user registration, authentication etc.. will be few and far in between, I don't think they will have much effect. Given all of that, I am biased towards MyISAM. But I need input from people already experienced in MySQL. **Questions:** 1. If the InnoDB run times are wrong/surprising, what have I missed in testing? Increasing buffer pool size dramatically increased performance. See above. 2. If not, considering all of the above, is MyISAM really good choice in the long run? 3. If MyISAM too turns out to be a bad choice later, how easily can I restructure the database? What options do I have? **On a side note:** 1. If choosing EAV was bad, what other architecture can I use for this project?
InnoDB and MyISAM each have their strengths and weaknesses. * `May 03, 2012` : [Which is faster, InnoDB or MyISAM?](https://dba.stackexchange.com/questions/17431/which-is-faster-innodb-or-myisam/17434#17434) * `Sep 20, 2011` : [Best of MyISAM and InnoDB](https://dba.stackexchange.com/questions/5974/best-of-myisam-and-innodb/6008#6008) If you have enough RAM, I would choose InnoDB because it caches data and index pages in the Buffer Pool. MyISAM only caches index pages in the Key Cache. MyISAM tables experience full table locks for each INSERT, UPDATE, and DELETE. MyISAM tables always require disk access for data. InnoDB tables always incur disk I/O in the following areas: * Double Write Buffer : Changes are posted in ibdata1 to avoid OS caching * Insert Buffer : Changes to Secondary (non-Unique) Indexes as posted in ibdata1 * Data and Indexes + With innodb\_file\_per\_table = 0, changes are written to ibdata1 + With innodb\_file\_per\_table = 1, changes are written to `.ibd` tablespace file. Read I/O against ibdata1 still necessary to crosscheck table metadata SUMMARY ======= In an environment with the following: * heavy writes * heavy reads * tons of RAM * heavy connections I would always choose InnoDB. Please check out my other post about InnoDB over MyISAM : [When to switch from MyISAM to InnoDB?](https://dba.stackexchange.com/questions/22678/when-to-switch-from-myisam-to-innodb/22680#22680) When would I every choose MyISAM? Under the following scenario * Using MySQL Replication * Master with all InnoDB * Slave with all tables converted to MyISAM * `ALTER TABLE ... ROW_FORMAT=Fixed` for all tables on the Slave Disk I/O wise, MyISAM has a slight edge with `ROW_FORMAT-Fixed` because you only interact with one file, the `.MYD` file. The row size is completely predictable because VARCHAR is treated as CHAR this shortening access time for data retrieval. * `May 10, 2011` : [What is the performance impact of using CHAR vs VARCHAR on a fixed-size field?](https://dba.stackexchange.com/questions/2640/what-is-the-performance-impact-of-using-char-vs-varchar-on-a-fixed-size-field/2643#2643) * `Mar 25, 2011` : [Performance implications of MySQL VARCHAR sizes](https://dba.stackexchange.com/questions/424/performance-implications-of-mysql-varchar-sizes/1915#1915) On the other hand, InnoDB has to interact with multiple files (ibdata1, serveral read/write threads upon the .ibd of the InnoDB table).
70042
I have a String = `'["Id","Lender","Type","Aging","Override"]'` from which I want to extract Id, Lender, Type and so on in an String array. I am trying to extract it using Regex but, the pattern is not removing the "[". Can someone please guide me. Thanks! Update: code I tried, ``` Pattern pattern = Pattern.compile("\"(.+?)\""); Matcher matcher = pattern.matcher(str); List<String> list = new ArrayList<String>(); while (matcher.find()) { // System.out.println(matcher.group(1));. list.add(matcher.group(1)); ``` (Ps: new to Regex)
I like @epascarello suggestion better, but if you want to use JavaScript, then just add the following line to your existing code: ``` function appendArrows() { var myDiv = document.getElementById('searchResult'); var list = myDiv.getElementsByTagName('div'); for (var i = 0; i <= list.length; i++) { var _img = document.createElement('img'); _img.src = "Images/navigation Icon.png"; _img.id = "arr"; list[i].appendChild(_img); var hzRule = document.createElement('hr');// make a hr list[i].appendChild(hzRule);// append the hr } ```
70357
I'm new to IntraWeb and have a problem. In order to implement a Login Form, i stored Datasets in the Usersession. But when it comes to access the Datasets i get an Access Violation Error. I figured out, that the Useresession is not created. Now i'm a bit confused, because in the Intraweb Documentary it is said, that the Usersession is created automatically by the ServerController. I access (respectively want to) the Dataset like this `UserSession.Dataset.open;` I use the IntraWeb Trial included in Rad Studio XE5. May that be the Problem? In case, that this is not the Problem, how can i create a Usersession manually? Thank you very much [Edit 13.4.16] The problem was the Evaluation Version I used. After installing the Full Version my problem vanished. They changed their Usersession.create procedure by adding another Parameter. So make sure you use the actual Version if u have the same Problem: Thanks for all the responses
You could do something like this: ``` class DataSource { static let sharedInstance = DataSource() var data: [AnyObject] = [] } ``` Usage: ``` DataSource.sharedInstance.data ```
70409
I am trying to upload a file, very much following the instructions on [Symfony's cookbook](https://symfony.com/doc/current/controller/upload_file.html), but it doesn't seem to work. The specific error is as follows, but the background reason is that the file as such does not seem to be ( or remain ) uploaded. > > Call to a member function guessExtension() on string > > > As it happens, the file is momentarily created at upload\_tmp\_dir, but gets deleted almost immediately ( I know that 'cause I kept that directory visible on my Finder). The file metadata is available on the var\_dump($\_FILES) command on the script below. So, for some reason the file is being discarded which, I believe, causes the specific error seen above. I believe $file ( from UploadedFile ), should receive the file as such, not the path to it, but not sure how to get there. Particularly is the file does not remain on upload\_tmp\_dir. For information, I tried the upload in a plain PHP project I have and it works fine. The file remains in upload\_tmp\_dir till is moved elsewhere. Thanks Here is the controller: ``` class ApiUserXtraController extends Controller { public function UserXtraAction(Request $request, ValidatorInterface $validator) { $is_logged = $this->isGranted('IS_AUTHENTICATED_FULLY'); if ($is_logged) { $user = $this->getUser(); } $em = $this->getDoctrine()->getManager(); $repo = $em->getRepository(UserXtra::class); $userxtra = new UserXtra(); $form = $this->createFormBuilder($userxtra) ->add('imgFile', FileType::class, array('label' => 'file')) ->add('save', SubmitType::class, array('label' => 'Create Task')) ->getForm(); var_dump($_FILES); // outputs file metadata, ie, name, type, tmp_name, size $form->handleRequest($request); $userxtra->setUser($user); if ($form->isSubmitted() && $form->isValid()) { /** * @var UploadedFile $file * */ $file = $userxtra->getImgFile(); var_dump('file', $file);// outputs full path to upload_tmp_dir $fileName = $this->generateUniqueFileName().'.'.$file->guessExtension(); // **THIS THROWS THE ERROR** $file->move( $this->getParameter('user_image_directory'), $fileName ); $userxtra->setImgFile($fileName); //$data = json_decode($data); return new JsonResponse(array( 'status' => 'ok', 'is_logged' => $is_logged, )); } return $this->render('upload.html.twig', array( 'form' => $form->createView(), )); } ```
Try setting the `precision` and `scale` properties of the @Column annotation. See: <https://docs.jboss.org/hibernate/jpa/2.1/api/javax/persistence/Column.html>
70789
**My scenario:** My application is a Web Api 2 app using a business logic and repository layer for data access. The web application uses ASP.NET Impersonation to login to the database as the user accessing the website (authenticated via PKI). I have several async controller methods. However, when I `await` on the data access methods, the database call may complete on a different thread which will then access the database under the identity of my application pool which is not allowed to connect to the database. **Example Controller**: ``` public class TestApiController : ApiController { private IBusinessLogicObject _myBlObject; public TestApiController(IBusinessLogicObject myBlObject){ _myBlObject = myBlObject; //Populated through Unity } public async Task<int> CountMyJobs(string name){ return await _myBlObject.CountMyJobsAsync(name); } } ``` **Example Business Logic Class**: ``` public class BusinessLogicObject : IBusinessLogicObject { private IGenericRepository<Job> _jobRepository; public BusinessLogicObject(IGenericRepository<Job> _jobRepository) { _jobRepository = jobRepository; //Populated with Unity } public Task<int> CountMyJobsAsync(string name) { using (WindowsIdentity.GetCurrent().Impersonate()) { //JobRepository is effectively a DbSet<Job> and this call returns IQueryable<Job> return _jobRepository.Where(i => i.Name == name).CountAsync(); } } } ``` If I move the `using` statement into the controller (wrapped around the await), it works fine. The issue seems to be that because the `await` is outside of the impersonation context, it does not impersonate the database call (the `CountAsync()`) and I am unable to open a connection to my database. **The Question**: Is there a way I could write an `ActionFilter` or some other attribute on my controller method so that the method itself (containing the await call) would be automatically wrapped in the using statement?
I don't believe there is a way to actually wrap a method in a using statement with an attribute, but you could essentially do the same thing by using the OnActionExecuting and OnResultExecuted methods in a custom ActionFilter. ``` public class IdentityImpersonateActionFilter : ActionFilterAttribute { IDisposable usingVaribale; public override void OnActionExecuting(ActionExecutingContext filterContext) { usingVaribale = WindowsIdentity.GetCurrent().Impersonate(); } public override void OnResultExecuted(ResultExecutedContext filterContext) { usingVaribale.Dispose(); } } ``` Then you could decorate your methods or your whole controller class with `[IdentityImpersonate]` ``` [IdentityImpersonate] public Task<int> CountMyJobsAsync(string name) { //JobRepository is effectively a DbSet<Job> and this call returns IQueryable<Job> return _jobRepository.Where(i => i.Name == name).CountAsync(); } ``` You could also access this using variable in your function if you wish ``` public override void OnActionExecuting(ActionExecutingContext filterContext) { usingVaribale = WindowsIdentity.GetCurrent().Impersonate(); filterContext.ActionParameters.Add("parameterName", usingVaribale); } ``` And add the parameter to your controller function ``` [IdentityImpersonate] public Task<int> CountMyJobsAsync(object parameterName, string name) { //JobRepository is effectively a DbSet<Job> and this call returns IQueryable<Job> return _jobRepository.Where(i => i.Name == name).CountAsync(); } ``` Hope this helps!
70831
On our development servers, we allow multiple developers access to the server to `git pull` their changes. Normally this requires running `sudo systemctl reload php-fpm` (or sending `USR2`, etc.). However, we want to allow them to reload the changed code in PHP-FPM without needing `sudo`. Way back when when I used to use Ruby, you could do exactly what I'm looking for by `touch`ing a file named `restart.txt` in the `tmp` directory. Does PHP-FPM support anything like that? Alternatively, is there anyway to allow the `reload` command (or any similar method of sending a `USR2`) without `sudo`?
You'll probably be there when whitelisting the command in your /etc/sudoers file: Start by editing the sudoers file: ``` sudo visudo ``` Add the following config line: ``` user ALL=(root) NOPASSWD: systemctl reload php-fpm ``` > > Replace *user* (at the beginning of the line) with the real username, for whom the command is executed. > > > This will privilege the user to call `sudo systemctl reload php-fpm` being executed as root (without password).
70877
I have associative table movies and their categories. ``` movie_id catagory_id 1 1 1 2 1 3 2 1 2 2 2 4 3 1 3 5 3 6 ``` How can i get movies that have category 1 and 2? Result: ``` movie_id 1 2 ```
If you want have `catagory_id` 1 and 2 use this: ```sql select movie_id from your_table group by movie_id having string_agg(catagory_id::text, ',' order by catagory_id) ~ '(1,)+(2)+' ``` If you want have `catagory_id` 1 or 2 use this: ```sql select distinct(movie_id) from your_table where catagory_id in (1, 2) ```
71143
I would like to know what im doing wrong cos i need persistent data from a service and get that data on my artist and album component. I don´t paste the album component 'cos it's the same. Im trying to get artist, albums, tracks, etc... Im sorry if it's a basic question but im new on angular and typescript. Thanks for reading anyaway!. ``` // artist.service.ts import { Injectable } from '@angular/core'; import { SpotifyService } from './spotify.service'; import { Observable } from 'rxjs'; @Injectable() export class ArtistService { artist: any; tracks: any; albums: any; artistRel: any; constructor(private _spotify: SpotifyService) {} getArtistDetail(id: string) { return new Promise((resolve, reject) => { resolve(this._spotify.getArtista(id).subscribe(artist => { console.log(artist, 'Artista'); return this.artist = artist; })); }).then(resp => { this._spotify.getTop(id).map((resp:any) => resp.tracks) .subscribe(tracks => { console.log(tracks, 'Tracks'); return this.tracks = tracks; }); }).then(resp => { this._spotify.getAlbumsArtist(id).map((resp: any) => resp.items) .subscribe(albums => { console.log(albums, 'Albums'); return this.albums = albums; }); }).then(resp => { this._spotify.getRelatedArtists(id).map((resp: any) => resp) .subscribe(related => { console.log(related, 'Artists related'); return this.artistRel = related; }); }).catch(error => console.log(error, 'Something Happened...')); } } ``` > > Blockquote > > > ``` // artist.component.ts import { Component, OnInit } from '@angular/core'; import { ArtistService } from '../../services/artist.service'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-artist', templateUrl: './artist.component.html' }) export class ArtistComponent implements OnInit { artist: {}; constructor(public _artistService: ArtistService, private route: ActivatedRoute) { this.route.params.map(params => params['id']).subscribe(id => { this._artistService.getArtistDetail(id); }); } ngOnInit() { // Im trying this way..but it doesn't work this.artist = this._artistService.artist; } } ``` > > Blockquote > > > ``` // artist.component.html <div class="container top30" *ngIf="artist"> <div class="row"> <div class="col-md-3"> <img [src]="artist.images | sinfoto" class="img-thumbnail rounded-circle"> </div> <div class="col-md-9"> <h1>{{ artist.name }}</h1> <hr> <a [href]="artist.external_urls.spotify" target="_blank" class="btn btn-outline-success">Abrir Spotify</a> <button [routerLink]="['/search']" type="button" class="btn btn-outline-danger">Regresar</button> </div> </div> <!-- Desplegar albumes --> <div class="container top30"> <div class="row"> <div class="col-md-3" *ngFor="let album of albums"> <img [src]="album.images | sinfoto" class="img-thumbnail puntero" [routerLink]="['/album', album.id]" > <p>{{ album.name }}</p> </div> </div> </div> ```
Do this: ``` npm install rxjs@6 rxjs-compat@6 --save ```
71323
I am trying to show a list of custom post types on a page template. When I view the page, instead of seeing the different posts, I see the actual page repeated. For example, If I have 5 posts, the actual page (head content footer) will be display five times. It seems like the query is working...in some way but I am not sure what is wrong. Here is the template code: ``` <?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?> <div id="post-<?php the_ID(); ?>" <?php post_class('page'); ?>> <h1><?php the_title(); ?></h1> <article> <div class="post-content page-content"> <?php the_content(); ?> <?php wp_link_pages('before=<div class="pagination">&after=</div>'); ?> </div><!--.post-content .page-content --> </article> </div><!--#post-# .post--> <?php endwhile; ?> <!-- Start search result code --> <?php //query_posts('post_type=listing&orderby=title&order=ASC&posts_per_page=9999'); ?> <?php $querystr = " SELECT * FROM $wpdb->posts, $wpdb->postsmeta WHERE wp_posts.ID = wp_postmeta.post_id AND wp_postmeta.meta_key = 'listing_open' AND wp_postmeta.meta_value = 'YES' AND wp_posts.post_status = 'publish' AND wp_posts.post_type = 'listing' ORDER BY post_title "; $pageposts = $wpdb->get_results($querystr, OBJECT); if ($pageposts): foreach ($pageposts as $postdata): setup_postdata($postdata); ?> <?php //if (have_posts()) : while (have_posts()) : the_post(); ?> <?php include_once(get_bloginfo('template_url')."/layout-listings.php?id=".$postdata->ID); ?> <?php //endwhile; endif; rewind_posts(); wp_reset_query(); ?> <?php endforeach; endif; ?> <?php $querystr = " SELECT * FROM $wpdb->posts, $wpdb->postmeta WHERE wp_posts.ID = wp_postmeta.post_id AND wp_postmeta.meta_key = 'listing_open' AND wp_postmeta.meta_value = 'NO' AND wp_posts.post_status = 'publish' AND wp_posts.post_type = 'listing' ORDER BY post_title "; $pageposts2 = $wpdb->get_results($querystr, OBJECT); if ($pageposts2): foreach ($pageposts2 as $postdata2): setup_postdata($postdata2); ?> <?php //if (have_posts()) : while (have_posts()) : the_post(); ?> <?php include_once(get_bloginfo('template_url')."/layout-listings.php?id=".$postdata2->ID); ?> <?php //endwhile; endif; rewind_posts(); wp_reset_query(); ?> <?php endforeach; endif; ?> <!-- End search result code --> ```
Refer to the Codex page for [`setup_postdata()`](https://codex.wordpress.org/Function_Reference/setup_postdata): > > Important: You must make use of the global $post variable to pass the post details into this function, otherwise functions like the\_title() don't work properly... > > > Also note that you can use [`WP_Query`](http://codex.wordpress.org/Class_Reference/WP_Query) to do these queries, rather than writing raw SQL.
71359
I have an excel document that contains multiple sheets. When I run the loop Jumping after returning from the first sheet to the second sheet. But on the second sheet does not open a new dictionary and I get an error like "run time error 9" at ln 16. `MySeries(Cnt, 2) = Dt(j, 2)` What can I do for each sheet in the opening of the new dictionary ? ``` Dim Cll As Object Dim j As Integer Dim y As Integer, MySeries, Dt, MySeries1, MySeries2, MySeries3, MySeries4 As Integer, sum As Double For y = 1 To (Worksheets.Count - 1) Sheets(y).Select Ln = Sheets(y).Range("a1").End(4).Row Sheets(y).Range("d2:H" & Ln).Interior.ColorIndex = xlNone Dt = Sheets(y).Range("d2:h" & Ln).Value Set Cll = CreateObject("Scripting.Dictionary") ReDim MySeries(1 To Ln, 1 To 5) For j = 1 To UBound(Dt, 1) Fnd = Dt(j, 1) If Not Cll.exists(Fnd) Then Cnt = Cnt + 1 Cll.Add Fnd, Cnt ReDim Preserve MySeries(1 To Ln, 1 To 5) MySeries(Cnt, 1) = Dt(j, 1) MySeries(Cnt, 2) = Dt(j, 2) MySeries(Cnt, 3) = Dt(j, 3) MySeries(Cnt, 4) = Dt(j, 4) End If MySeries(Cll.Item(Fnd), 5) = MySeries(Cll.Item(Fnd), 5) + Dt(j, 5) / 1000 Next j Sheets(y).Range("a2:h" & Ln).Clear Sheets(y).Range("d2").Resize(Cll.Count, 5) = MySeries Next y ``` Thank you for your help
``` t_stamp = int(time.mktime(datetime.datetime.strptime(date, "%Y-%m-%d").timetuple())) for h in range(24): 24 hours for i in range(60): # 60 minutes print t_stamp t_stamp += 60 # one minute ```
71500
In my system when users add a reservation to the database, a transaction ID will be automatically generated: ``` $insertID = mysql_insert_id() ; $transactionID = "RESV2014CAI00". $insertID ; $insertGoTo = "action.php?trans=" . $transact; ``` But it is very dangerous to pass the `$transactionID` via address bar. (GET Method) So I need to send transaction to `action.php` via the POST method. How can I pass this data using the POST method?
Another approach would be to hash the id as shown below. ``` $salt = 'your secret key here'; $hash = sha1(md5($transactionID.$salt)); ``` Now you can pass the hash along with the transaction id on the next page and check it match. If it matches then the id wasn't changed. If not then the id was changed. Something like. ``` $salt = 'your secret key here'; $hash = sha1(md5($_GET['transectionId'].$salt)); if($hash == $_GET['hash']){ //do something } else { //Error, id changed } ```
71502
I have two tables "Category" and "Movie" with 1-M relationship ('CategoryID' is a Foreign Key in the table "Movie"). I'm using a ListView to list all Categories. Inside of my ListView is Repeater that loops through all movies within each category. In my code-behind,I'm binding the ListView DataSource as follows: ``` MovieDBDataContext context = new MovieDBDataContext(); var categories = context.Categories.Select(x => x).OrderBy(x => x.Order).ToList(); ListView1.DataSource = categories; ListView1.DataBind(); ``` and I'm binding the Repeater DataSource in the markup as follows: ``` <asp:Repeater runat="server" ID="repeater" DataSource='<%# ((Category)Container.DataItem).CategoryItems.Where(p => p.Active == true).OrderBy(p => p.Name) %>'> ``` Now I'm having a requirement where I need sort my movie by name, but if a movie starts with "The " than I need to disregard that and sort on the rest of the name (so "The Lord of the rings" will be sorted as "Lord of the rings"). Is there a way to modify my Linq statement to manipulate strings in such a way on the fly?
``` ((Category)Container.DataItem).CategoryItems.Where(p => p.Active == true).OrderBy(p => p.Name.StartsWith("The ") ? p.Name.Substring(4): p.Name) ```
71956
I have a table: ``` T (Mon varchar(3)); INSERT INTO T VALUES ('Y'); ``` Case 1: ``` DECLARE @day varchar(3) = 'Mon' SELECT Mon FROM T; --result : Y (no problem) ``` Case 2: ``` DECLARE @day VARCHAR(3) = 'Mon' SELECT @day FROM T; --result : Mon ``` If I want to get result `Y` in second case, how can I do that without re-designing the solution completely.
``` exec('select '+@day+' from #T;') ```
72930
Is there an idiomatic way to apply a function to all items in a list ? For example, in Python, say we wish to capitalize all strings in a list, we can use a loop : ``` regimentNames = ['Night Riflemen', 'Jungle Scouts', 'The Dragoons', 'Midnight Revengence', 'Wily Warriors'] # create a variable for the for loop results regimentNamesCapitalized_f = [] # for every item in regimentNames for i in regimentNames: # capitalize the item and add it to regimentNamesCapitalized_f regimentNamesCapitalized_f.append(i.upper()) ``` But a more concise way is: ``` capitalizer = lambda x: x.upper() regimentNamesCapitalized_m = list(map(capitalizer, regimentNames)); regimentNamesCapitalized_m ``` What is an equivalent way to call a function on all items in a list in Dart ?
The answer seems to be to use anonymous functions, or pass a function to a lists `forEach` method. Passing a function: ``` void capitalise(var string) { var foo = string.toUpperCase(); print(foo); } var list = ['apples', 'bananas', 'oranges']; list.forEach(capitalise); ``` Using an anonymous function: ``` list.forEach((item){ print(item.toUpperCase()); }); ``` If the function is going to be used only in one place, I think its better to use the anonymous function, as it is easy to read what is happening in the list. If the function is going to be used in multiple places, then its better to pass the function instead of using an anonymous function.
72962
In our angular 5.2 project, we keep getting the below errors in scss files, [![SCSS erros related to spaces](https://i.stack.imgur.com/B9cED.png)](https://i.stack.imgur.com/B9cED.png) do we have a VS code plugin OR a Scss formatter which can take care these space issues in the scss??
These errors seem to be from the `stylelint` linting tool. You'll have to either modify your `stylelint` config and turn off these rules or you have to fix them in your `scss` file. To help you with detecting these errors on VS code as you code, you can use an extension. 1. Go to `View > Extensions`. 2. Search for a `stylelint` extension (Recommendation: `shinnn.stylelint` by Shinnosuke Watanabe). 3. Install the extension. Now open your `scss` file and VS code should indicate your lint errors. (This might require you to restart VS code).
74377
My admin URL redirecting to homepage, I have did lot of efforts to fix admin login link but still it migrating to homepage, my website link <https://www.muzikhausberlin.de/index.php> my admin link <https://www.muzikhausberlin.de/admin>
after hard hurdle i got it fixed. i replace htaccess file with this code and working perfect ``` ############################################ ## uncomment the line below to enable developer mode # SetEnv MAGE_MODE developer ############################################ ## uncomment these lines for CGI mode ## make sure to specify the correct cgi php binary file name ## it might be /cgi-bin/php-cgi # Action php5-cgi /cgi-bin/php5-cgi # AddHandler php5-cgi .php ############################################ ## GoDaddy specific options # Options -MultiViews ## you might also need to add this line to php.ini ## cgi.fix_pathinfo = 1 ## if it still doesn't work, rename php.ini to php5.ini ############################################ ## this line is specific for 1and1 hosting #AddType x-mapp-php5 .php #AddHandler x-mapp-php5 .php ############################################ ## default index file DirectoryIndex index.php <IfModule mod_php5.c> ############################################ ## adjust memory limit php_value memory_limit 768M php_value max_execution_time 18000 ############################################ ## disable automatic session start ## before autoload was initialized php_flag session.auto_start off ############################################ ## enable resulting html compression #php_flag zlib.output_compression on ########################################### ## disable user agent verification to not break multiple image upload php_flag suhosin.session.cryptua off </IfModule> <IfModule mod_security.c> ########################################### ## disable POST processing to not break multiple image upload SecFilterEngine Off SecFilterScanPOST Off </IfModule> <IfModule mod_deflate.c> ############################################ ## enable apache served files compression ## http://developer.yahoo.com/performance/rules.html#gzip # Insert filter on all content ###SetOutputFilter DEFLATE # Insert filter on selected content types only #AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript # Netscape 4.x has some problems... #BrowserMatch ^Mozilla/4 gzip-only-text/html # Netscape 4.06-4.08 have some more problems #BrowserMatch ^Mozilla/4\.0[678] no-gzip # MSIE masquerades as Netscape, but it is fine #BrowserMatch \bMSIE !no-gzip !gzip-only-text/html # Don't compress images #SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary # Make sure proxies don't deliver the wrong content #Header append Vary User-Agent env=!dont-vary </IfModule> <IfModule mod_ssl.c> ############################################ ## make HTTPS env vars available for CGI mode SSLOptions StdEnvVars </IfModule> <IfModule mod_rewrite.c> ############################################ ## enable rewrites Options +FollowSymLinks RewriteEngine on ############################################ ## you can put here your magento root folder ## path relative to web root #RewriteBase /magento/ ############################################ ## workaround for HTTP authorization ## in CGI environment RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] ############################################ ## TRACE and TRACK HTTP methods disabled to prevent XSS attacks RewriteCond %{REQUEST_METHOD} ^TRAC[EK] RewriteRule .* - [L,R=405] ############################################ ## redirect for mobile user agents #RewriteCond %{REQUEST_URI} !^/mobiledirectoryhere/.*$ #RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC] #RewriteRule ^(.*)$ /mobiledirectoryhere/ [L,R=302] ############################################ ## never rewrite for existing files, directories and links RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-l ############################################ ## rewrite everything else to index.php RewriteRule .* index.php [L] </IfModule> ############################################ ## Prevent character encoding issues from server overrides ## If you still have problems, use the second line instead AddDefaultCharset Off #AddDefaultCharset UTF-8 <IfModule mod_expires.c> ############################################ ## Add default Expires header ## http://developer.yahoo.com/performance/rules.html#expires ExpiresDefault "access plus 1 year" ExpiresByType text/html A0 ExpiresByType text/plain A0 </IfModule> ########################################### ## Deny access to root files to hide sensitive application information RedirectMatch 404 /\.git <Files composer.json> order allow,deny deny from all </Files> <Files composer.lock> order allow,deny deny from all </Files> <Files .gitignore> order allow,deny deny from all </Files> <Files .htaccess> order allow,deny deny from all </Files> <Files .htaccess.sample> order allow,deny deny from all </Files> <Files .php_cs> order allow,deny deny from all </Files> <Files .travis.yml> order allow,deny deny from all </Files> <Files CHANGELOG.md> order allow,deny deny from all </Files> <Files CONTRIBUTING.md> order allow,deny deny from all </Files> <Files CONTRIBUTOR_LICENSE_AGREEMENT.html> order allow,deny deny from all </Files> <Files COPYING.txt> order allow,deny deny from all </Files> <Files Gruntfile.js> order allow,deny deny from all </Files> <Files LICENSE.txt> order allow,deny deny from all </Files> <Files LICENSE_AFL.txt> order allow,deny deny from all </Files> <Files nginx.conf.sample> order allow,deny deny from all </Files> <Files package.json> order allow,deny deny from all </Files> <Files php.ini.sample> order allow,deny deny from all </Files> <Files README.md> order allow,deny deny from all </Files> ################################ ## If running in cluster environment, uncomment this ## http://developer.yahoo.com/performance/rules.html#etags #FileETag none ```
75091
This is driving me crazy! measured layout is always 0 when i try to build layout programmatically using constraint layout and constraint set. I tried `requestLayout`, `forceLayout`, `invalidate` on all child and parents. but width and height is 0 rendering whole view invisible. here is my layout builder. my problem is that views are rendering invisible when i apply constraints. ``` public final class FormBuilder { private Context context; private ArrayList<ArrayList<TextInputLayout>> fields; private FormBuilder(Context context) { this.context = context; fields = new ArrayList<>(); fields.add(new ArrayList<TextInputLayout>()); } private ArrayList<TextInputLayout> getLastRow() { return fields.get(fields.size() - 1); } public static FormBuilder newForm(Context context) { return new FormBuilder(context); } public FormBuilder addField(@NonNull String hint) { TextInputLayout field = newTextField(context, hint); getLastRow().add(field); return this; } public FormBuilder nextRow() { if (getLastRow().size() > 0) fields.add(new ArrayList<TextInputLayout>()); return this; } public FormView build() { FormView formView = new FormView(context); ConstraintSet constraints = new ConstraintSet(); int topId = ConstraintSet.PARENT_ID; for (ArrayList<TextInputLayout> row : fields) { if (row.size() == 0) continue; int[] rowIds = new int[row.size()]; for (int i = 0; i < row.size(); i++) { // constraint top TextInputLayout field = row.get(i); rowIds[i] = field.getId(); ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams( ConstraintLayout.LayoutParams.WRAP_CONTENT, ConstraintLayout.LayoutParams.WRAP_CONTENT ); formView.addView(field, params); if (topId == ConstraintSet.PARENT_ID) { constraints.connect(rowIds[i], ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP); } else { constraints.connect(rowIds[i], ConstraintSet.TOP, topId, ConstraintSet.BOTTOM); } } if (row.size() >= 2) { // constraint start and end constraints.createHorizontalChainRtl( ConstraintSet.PARENT_ID, ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.END, rowIds, null, ConstraintSet.CHAIN_SPREAD); } else { // row.size = 1 constraints.connect(rowIds[0], ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START); constraints.connect(rowIds[0], ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END); } topId = rowIds[0]; } constraints.applyTo(formView); // this turns layout size to zero return formView; } private static TextInputLayout newTextField(Context context, String hint) { TextInputLayout.LayoutParams layoutParams = new TextInputLayout.LayoutParams( TextInputLayout.LayoutParams.MATCH_PARENT, TextInputLayout.LayoutParams.WRAP_CONTENT ); TextInputLayout inputLayout = new TextInputLayout(context); TextInputEditText editText = new TextInputEditText(context); inputLayout.addView(editText, layoutParams); inputLayout.setHint(hint); inputLayout.setId(ViewCompat.generateViewId()); return inputLayout; } } ``` --- MainActivity.java ``` public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FormView form = FormBuilder.newForm(this) .addField("First name").addField("Last name") .nextRow() .addField("Phone numnber") .build(); FrameLayout layout = findViewById(R.id.main_content); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT ); layout.addView(form, params); } } ``` --- FormView.java ``` public class FormView extends ConstraintLayout { public FormView(Context context) { super(context); } } ``` --- main\_activity.xml ``` <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/main_content" android:layout_width="match_parent" android:layout_height="match_parent" /> ```
I had to clone `ConstraintSet`. not only that, cloning must be done **after** views are added. after adding views and cloning `ConstraintSet`, it knows size of the views and can set constraints accordingly. ``` private FormViewBuilder(Context context) { this.context = context; formView = new FormView(context); // initialize // ... } // ... public FormViewBuilder addField(int id, @NonNull String key, @NonNull String hint, String requiredMessage) { TextInputLayout field = newTextField(context, id, key, hint, requiredMessage); getLastRow().add(field); // add views before build <<================ important ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams( ConstraintLayout.LayoutParams.CHAIN_SPREAD, ConstraintLayout.LayoutParams.WRAP_CONTENT ); formView.addView(field, params); return this; } public FormView build() { ConstraintSet constraints = new ConstraintSet(); constraints.clone(formView); // clone after views are added <<================ important // only set constraints. do not add or remove views constraints.applyTo(formView); return formView; } ```
75121
I've been researching this and I am trying to use a VF page method of invoking an Apex class through a custom button. The method I am attempting to use is this : [Invoking Apex Code With a Custom Button Using a Visual Force Page](http://sfdc.arrowpointe.com/2009/01/08/invoke-apex-from-a-custom-button-using-a-visualforce-page/) Right now, my code looks like this. ``` public class VFController { // Constructor - this only really matters if the autoRun function doesn't work right private final Contract_Overview__c o; public VFController(ApexPages.StandardController stdController) { this.o = (Contract_Overview__c)stdController.getRecord(); } // Code we will invoke on page load. public PageReference autoRun() { String theId = ApexPages.currentPage().getParameters().get('id'); if (theId == null) { // Display the Visualforce page's content if no Id is passed over return null; } for (Contract_Overview__c o:[select id, name from Contract_Overview__c where id =:theId]) { // Do all the dirty work we need the code to do public void CreateOpportunityWithChildren(Id accountId) { // Query the countries related to this account List<Client_Profile__c> countryProfiles = [SELECT Id , Name FROM Client_Profile__c WHERE Account_Name__c = :accountId]; // Lists for DML operations List<Opportunity> OpportunitiesToInsert = new List<Opportunity>(); List<Country_by_Country__c> OppyChildrenToInsert = new List<Country_by_Country__c>(); // create an opportunity to dangle opportunity children from Opportunity oppy = new Opportunity(Name = 'Your Oppy Name' , AccountId = accountId , StageName = 'Prospecting' , CloseDate = Date.today().addDays(7)); // add it to the list for later DML OpportunitiesToInsert.add(oppy); // for each countryProfile queried earlier, create an OpportunityChild for (Client_Profile__c countryProfile: countryProfiles) { // set the fields on the OpportunityChild Country_by_Country__c oppyChild = new Country_by_Country__c(); //oppyChild.Stage__c = 'Prospecting'; oppyChild.Account_Name__c = accountId; oppyChild.Client_Country_Profile__c = countryProfile.Id; // presumably there's a name like 'Argentina' in the name field //oppyChild.Name = 'CBC ' + countryProfile.Name; // set a reference between this child object and it's parent // (presuming there is a relationship between the two named Opportunity) oppyChild.Opportunity__r = oppy; // add this child to the list for later DML OppyChildrenToInsert.add(oppyChild); } // set up a transaction so that we can roll back in the event anything fails System.Savepoint sp1 = Database.setSavepoint(); // try / catch around all of this DML try { // if any exist, first insert the parents if (!OpportunitiesToInsert.isEmpty()) { insert OpportunitiesToInsert; } // if any exist, insert the children // ( Note: probably wouldn't do this work if there weren't any parents ) if (!OppyChildrenToInsert.isEmpty()) { // for all of the children that we are inserting, reach through the // relationship between the two objects and get the ID assigned // on the parent earlier during that DML operation for (Country_by_Country__c oppyChild : OppyChildrenToInsert) { // is there a relationship to a parent? if (oppyChild.Opportunity__r != null) { // reach through the relationship and get the ID from the parent // and set that id value on the child oppyChild.Opportunity__c = oppyChild.Opportunity__r.Id; } } // now that all of the children have the ID values of their parents insert OppyChildrenToInsert; } } catch (Exception ex) { // log the exception system.debug(ex); // something failed, roll back the entire transaction Database.rollback(sp1); } } } // Redirect the user back to the original page PageReference pageRef = new PageReference('/' + theId); pageRef.setRedirect(true); return pageRef; } } ``` I am currently getting this error on that code : **Save error: expecting a semi-colon, found '('** for line 22 which is this : ``` public void CreateOpportunityWithChildren(Id accountId) { ``` That happens to be the very first line of my Apex class which I inserted into this code. I took out the line which originally went ahead of that line which was this : ``` public class MyControllerOppAndCBC { ``` I didn't think I needed it since it was now being put inside this code. I also took out the right curly bracket which went with that first line, but I don't think those changes would be cause for the error, but I could be very wrong. I can't figure out what is up with this. Anybody got any ideas on this ? Does the rest of the code look proper to you ? I haven't gotten to my VF page yet. Thank you very much for your help ahead of time.
``` public class VFController { // This is where you want to declare your public getter and private setter methods // String theId = ApexPages.currentPage().getParameters().get('id'); // The above gets passed to you by reference. Its part of your getter method and is // superfluous. You do the same below at Opportunity o = (Contract_Overview__c)... // the line below **does** belong here! public VFController(ApexPages.StandardController stdController) { Opportunity o = (Contract_Overview__c)stdController.getRecord(); try { opp = [SELECT Id, AccountId, Amount, Name, Owner.Id, Any other fields you want to add, FROM Opportunity WHERE Id =: o.AccountId = Contract_Overview__r.Account.Id]; } catch(Exception e) { ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL, e.getMessage())); } ``` I'm not certain of the relationship between Contract\_Overview\_\_c and Opportunity or Accounts. If the opp doesn't already exist, then you need to be querying on Account or Contract\_Overview\_\_c and fully understand the relationships between them. (I don't know your org, so can't determine exactly how an opportunity is related to Contract\_Overview\_\_c.) ``` // Code we will invoke on page load. public PageReference autoRun() { ``` From your original post, I understood that you were using a button to invoke this page?? If so and the Id is null, I suggest you add code to abort the button rather than adding this code into the controller! You can add code in the try/catch block to exit gracefully such as redirecting back to the original page as you've mentioned at the bottom of your code. I think that would be a better way of handling it if doing it **on the controller**, but everyone has their coding preferences. ``` try { // if any exist, first insert the parents if (!OpportunitiesToInsert.isEmpty()) { insert OpportunitiesToInsert; } ``` This should be followed by it's own catch block before moving onto the next insert operation. Further, I'd suggest adding code that allows partial success. Here's an example of what I'm speaking of: ``` // after insertion (failures allowed), check for failures and debug if(OpportunitiesToInsert.IsEmpty() == false){ list<Database.SaveResult> InsertResults = Database.Insert(OpportunitiesToInsert,false); } ``` Doing that allows you to add debug code following the insertion on the InsertResults list (before the closing bracket) which can be very helpful when trying to debug your code or if you want to create a log of any and all errors that occurred while also allowing the records to still be created with non-fatal errors. I believe your lack of catch blocks is very likely the source of many of your error messages. Your class is public, will have public get methods, but you'll probably want to have private setter methods which are declared as follows immediately below your class declaration in the portion of your code where I noted it above: ``` public Opportunity opp {get; private set;} ``` I hope this gets you pointed down the right path and HIGHLY recommend you go through the [VisualForce Workbook](http://www.salesforce.com/us/developer/docs/workbook_vf/workbook_vf.pdf), particularly chapters 12 and 13 from the SalesForce Developer site and chapter 17 of the [Apex Workbook](http://www.salesforce.com/us/developer/docs/apex_workbook/apex_workbook.pdf). I think you'll find that working through the tutorials in both will go a long way towards helping you in your endeavors. :)
75716
Presently I have the following setup where the controller `ReminderViewController` has a container view which refers to a `UITableViewController` with the three static cells:![enter image description here](https://i.stack.imgur.com/cDMOi.png) Beyond this [answer](https://stackoverflow.com/questions/8945728/how-to-visually-create-and-use-static-cells-in-a-uitableview-embedded-in-a-uivie), I have not found any other resources on what to do so that when a user toggles one of the `UISwitch` within the cells, my `SetReminderController` would be notified and act accordingly. How would I be able to accomplish this? Thanks!
From the action methods for your switches, you can access the ReminderViewController with self.parentViewController, and then call any method or set any property in that controller that you want to.
75937
I want to move an imageview along with finger using onTouchListener() in android...... I have created an xml --> ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <RelativeLayout android:id="@+id/rel_slide" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@android:color/background_dark" > <ImageView android:id="@+id/img_arrow" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher"/>" </RelativeLayout> </RelativeLayout> ``` Now in Activity file I implemented onTouchListener to this imageView: **img\_arrow** here is the code: ``` ((ImageView) findViewById(R.id.img_arrow)).setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View arg0, MotionEvent arg1) { switch (arg1.getAction()) { case MotionEvent.ACTION_MOVE: LayoutParams layoutParams = (LayoutParams)v.getLayoutParams(); layoutParams.leftMargin=(int)arg1.getX(); layoutParams.topMargin=(int)arg1.getY(); v.setLayoutParams(layoutParams); break; } return true; } }); ``` **But this results in flikering of imageView** showing 2 at a time may be because of very fast setting of layoutParams when **ACTION\_MOVE** called.....plz help
Hey I would suggest you to not to play with the view. Its better to set an animation on the view and play with that animation object to performing all the actions. Just invisible the view on onTouchEvent and let the animation object work done for u. You can see the example of swipeToDismiss in list view <https://github.com/47deg/android-swipelistview> or any other swiping examples of top developers. Happy Coding!! [New] I also done trick. I wanna make an swipe to unlock feature so I used a seekbar and customized it. It worked great or me.
76373
I need to find the ratio of one floating-point number to another, and the ratio needs to be two integers. For example: * input: `1.5, 3.25` * output: `"6:13"` Does anyone know of one? Searching the internet, I found no such algorithm, nor an algorithm for the least common multiple or denominator of two floating-point numbers (just integers). Java implementation: -------------------- --- This is the final implementation that I will use: ```java public class RatioTest { public static String getRatio(double d1, double d2)//1.5, 3.25 { while(Math.max(d1,d2) < Long.MAX_VALUE && d1 != (long)d1 && d2 != (long)d2) { d1 *= 10;//15 -> 150 d2 *= 10;//32.5 -> 325 } //d1 == 150.0 //d2 == 325.0 try { double gcd = getGCD(d1,d2);//gcd == 25 return ((long)(d1 / gcd)) + ":" + ((long)(d2 / gcd));//"6:13" } catch (StackOverflowError er)//in case getGDC (a recursively looping method) repeats too many times { throw new ArithmeticException("Irrational ratio: " + d1 + " to " + d2); } } public static double getGCD(double i1, double i2)//(150,325) -> (150,175) -> (150,25) -> (125,25) -> (100,25) -> (75,25) -> (50,25) -> (25,25) { if (i1 == i2) return i1;//25 if (i1 > i2) return getGCD(i1 - i2, i2);//(125,25) -> (100,25) -> (75,25) -> (50,25) -> (25,25) return getGCD(i1, i2 - i1);//(150,175) -> (150,25) } } ``` * `->` indicates the next stage in the loop or method call Mystical's implementation as Java: ---------------------------------- --- Though I did not end up using this, it more than deserves to be recognized, so I translated it to Java, so I could understand it: ```java import java.util.Stack; public class RatioTest { class Fraction{ long num; long den; double val; }; Fraction build_fraction(Stack<long> cf){ long term = cf.size(); long num = cf[term - 1]; long den = 1; while (term-- > 0){ long tmp = cf[term]; long new_num = tmp * num + den; long new_den = num; num = new_num; den = new_den; } Fraction f; f.num = num; f.den = den; f.val = (double)num / (double)den; return f; } void get_fraction(double x){ System.out.println("x = " + x); // Generate Continued Fraction System.out.print("Continued Fraction: "); double t = Math.abs(x); double old_error = x; Stack<long> cf; Fraction f; do{ // Get next term. long tmp = (long)t; cf.push(tmp); // Build the current convergent f = build_fraction(cf); // Check error double new_error = Math.abs(f.val - x); if (tmp != 0 && new_error >= old_error){ // New error is bigger than old error. // This means that the precision limit has been reached. // Pop this (useless) term and break out. cf.pop(); f = build_fraction(cf); break; } old_error = new_error; System.out.print(tmp + ", "); // Error is zero. Break out. if (new_error == 0) break; t -= tmp; t = 1/t; }while (cf.size() < 39); // At most 39 terms are needed for double-precision. System.out.println();System.out.println(); // Print Results System.out.println("The fraction is: " + f.num + " / " + f.den); System.out.println("Target x = " + x); System.out.println("Fraction = " + f.val); System.out.println("Relative error is: " + (Math.abs(f.val - x) / x));System.out.println(); System.out.println(); } public static void main(String[] args){ get_fraction(15.38 / 12.3); get_fraction(0.3333333333333333333); // 1 / 3 get_fraction(0.4184397163120567376); // 59 / 141 get_fraction(0.8323518818409020299); // 1513686 / 1818565 get_fraction(3.1415926535897932385); // pi } } ``` One MORE thing: --------------- --- The above mentioned implemented way of doing this works **IN THEORY**, however, due to floating-point rounding errors, this results in alot of unexpected exceptions, errors, and outputs. Below is a practical, robust, but a bit dirty implementation of a ratio-finding algorithm (Javadoc'd for your convenience): ```java public class RatioTest { /** Represents the radix point */ public static final char RAD_POI = '.'; /** * Finds the ratio of the two inputs and returns that as a <tt>String</tt> * <h4>Examples:</h4> * <ul> * <li><tt>getRatio(0.5, 12)</tt><ul> * <li>returns "<tt>24:1</tt>"</li></ul></li> * <li><tt>getRatio(3, 82.0625)</tt><ul> * <li>returns "<tt>1313:48</tt>"</li></ul></li> * </ul> * @param d1 the first number of the ratio * @param d2 the second number of the ratio * @return the resulting ratio, in the format "<tt>X:Y</tt>" */ public static strictfp String getRatio(double d1, double d2) { while(Math.max(d1,d2) < Long.MAX_VALUE && (!Numbers.isCloseTo(d1,(long)d1) || !Numbers.isCloseTo(d2,(long)d2))) { d1 *= 10; d2 *= 10; } long l1=(long)d1,l2=(long)d2; try { l1 = (long)teaseUp(d1); l2 = (long)teaseUp(d2); double gcd = getGCDRec(l1,l2); return ((long)(d1 / gcd)) + ":" + ((long)(d2 / gcd)); } catch(StackOverflowError er) { try { double gcd = getGCDItr(l1,l2); return ((long)(d1 / gcd)) + ":" + ((long)(d2 / gcd)); } catch (Throwable t) { return "Irrational ratio: " + l1 + " to " + l2; } } } /** * <b>Recursively</b> finds the Greatest Common Denominator (GCD) * @param i1 the first number to be compared to find the GCD * @param i2 the second number to be compared to find the GCD * @return the greatest common denominator of these two numbers * @throws StackOverflowError if the method recurses to much */ public static long getGCDRec(long i1, long i2) { if (i1 == i2) return i1; if (i1 > i2) return getGCDRec(i1 - i2, i2); return getGCDRec(i1, i2 - i1); } /** * <b>Iteratively</b> finds the Greatest Common Denominator (GCD) * @param i1 the first number to be compared to find the GCD * @param i2 the second number to be compared to find the GCD * @return the greatest common denominator of these two numbers */ public static long getGCDItr(long i1, long i2) { for (short i=0; i < Short.MAX_VALUE && i1 != i2; i++) { while (i1 > i2) i1 = i1 - i2; while (i2 > i1) i2 = i2 - i1; } return i1; } /** * Calculates and returns whether <tt>d1</tt> is close to <tt>d2</tt> * <h4>Examples:</h4> * <ul> * <li><tt>d1 == 5</tt>, <tt>d2 == 5</tt> * <ul><li>returns <tt>true</tt></li></ul></li> * <li><tt>d1 == 5.0001</tt>, <tt>d2 == 5</tt> * <ul><li>returns <tt>true</tt></li></ul></li> * <li><tt>d1 == 5</tt>, <tt>d2 == 5.0001</tt> * <ul><li>returns <tt>true</tt></li></ul></li> * <li><tt>d1 == 5.24999</tt>, <tt>d2 == 5.25</tt> * <ul><li>returns <tt>true</tt></li></ul></li> * <li><tt>d1 == 5.25</tt>, <tt>d2 == 5.24999</tt> * <ul><li>returns <tt>true</tt></li></ul></li> * <li><tt>d1 == 5</tt>, <tt>d2 == 5.1</tt> * <ul><li>returns <tt>false</tt></li></ul></li> * </ul> * @param d1 the first number to compare for closeness * @param d2 the second number to compare for closeness * @return <tt>true</tt> if the two numbers are close, as judged by this method */ public static boolean isCloseTo(double d1, double d2) { if (d1 == d2) return true; double t; String ds = Double.toString(d1); if ((t = teaseUp(d1-1)) == d2 || (t = teaseUp(d2-1)) == d1) return true; return false; } /** * continually increases the value of the last digit in <tt>d1</tt> until the length of the double changes * @param d1 * @return */ public static double teaseUp(double d1) { String s = Double.toString(d1), o = s; byte b; for (byte c=0; Double.toString(extractDouble(s)).length() >= o.length() && c < 100; c++) s = s.substring(0, s.length() - 1) + ((b = Byte.parseByte(Character.toString(s.charAt(s.length() - 1)))) == 9 ? 0 : b+1); return extractDouble(s); } /** * Works like Double.parseDouble, but ignores any extraneous characters. The first radix point (<tt>.</tt>) is the only one treated as such.<br/> * <h4>Examples:</h4> * <li><tt>extractDouble("123456.789")</tt> returns the double value of <tt>123456.789</tt></li> * <li><tt>extractDouble("1qw2e3rty4uiop[5a'6.p7u8&9")</tt> returns the double value of <tt>123456.789</tt></li> * <li><tt>extractDouble("123,456.7.8.9")</tt> returns the double value of <tt>123456.789</tt></li> * <li><tt>extractDouble("I have $9,862.39 in the bank.")</tt> returns the double value of <tt>9862.39</tt></li> * @param str The <tt>String</tt> from which to extract a <tt>double</tt>. * @return the <tt>double</tt> that has been found within the string, if any. * @throws NumberFormatException if <tt>str</tt> does not contain a digit between 0 and 9, inclusive. */ public static double extractDouble(String str) throws NumberFormatException { try { return Double.parseDouble(str); } finally { boolean r = true; String d = ""; for (int i=0; i < str.length(); i++) if (Character.isDigit(str.charAt(i)) || (str.charAt(i) == RAD_POI && r)) { if (str.charAt(i) == RAD_POI && r) r = false; d += str.charAt(i); } try { return Double.parseDouble(d); } catch (NumberFormatException ex) { throw new NumberFormatException("The input string could not be parsed to a double: " + str); } } } } ```
This is a fairly non-trivial task. The best approach I know that gives reliable results for any two floating-point is to use [continued fractions](http://en.wikipedia.org/wiki/Continued_fraction). First, divide the two numbers to get the ratio in floating-point. Then run the continued fraction algorithm until it terminates. If it doesn't terminate, then it's irrational and there is no solution. If it terminates, evaluate the resulting continued fraction back into a single fraction and that will be the answer. Of course, there is no reliable way to determine if there is a solution or not since this becomes the halting problem. But for the purposes of limited precision floating-point, if the sequence doesn't terminate with a reasonable number of steps, then assume there's no answer. **EDIT 2: Here's an update to my original solution in C++. This version is much more robust and seems to work with any positive floating-point number except for `INF`, `NAN`, or extremely large or small values that would overflow an integer.** ``` typedef unsigned long long uint64; struct Fraction{ uint64 num; uint64 den; double val; }; Fraction build_fraction(vector<uint64> &cf){ uint64 term = cf.size(); uint64 num = cf[--term]; uint64 den = 1; while (term-- > 0){ uint64 tmp = cf[term]; uint64 new_num = tmp * num + den; uint64 new_den = num; num = new_num; den = new_den; } Fraction f; f.num = num; f.den = den; f.val = (double)num / den; return f; } void get_fraction(double x){ printf("x = %0.16f\n",x); // Generate Continued Fraction cout << "Continued Fraction: "; double t = abs(x); double old_error = x; vector<uint64> cf; Fraction f; do{ // Get next term. uint64 tmp = (uint64)t; cf.push_back(tmp); // Build the current convergent f = build_fraction(cf); // Check error double new_error = abs(f.val - x); if (tmp != 0 && new_error >= old_error){ // New error is bigger than old error. // This means that the precision limit has been reached. // Pop this (useless) term and break out. cf.pop_back(); f = build_fraction(cf); break; } old_error = new_error; cout << tmp << ", "; // Error is zero. Break out. if (new_error == 0) break; t -= tmp; t = 1/t; }while (cf.size() < 39); // At most 39 terms are needed for double-precision. cout << endl << endl; // Print Results cout << "The fraction is: " << f.num << " / " << f.den << endl; printf("Target x = %0.16f\n",x); printf("Fraction = %0.16f\n",f.val); cout << "Relative error is: " << abs(f.val - x) / x << endl << endl; cout << endl; } int main(){ get_fraction(15.38 / 12.3); get_fraction(0.3333333333333333333); // 1 / 3 get_fraction(0.4184397163120567376); // 59 / 141 get_fraction(0.8323518818409020299); // 1513686 / 1818565 get_fraction(3.1415926535897932385); // pi system("pause"); } ``` **Output:** ``` x = 1.2504065040650407 Continued Fraction: 1, 3, 1, 152, 1, The fraction is: 769 / 615 Target x = 1.2504065040650407 Fraction = 1.2504065040650407 Relative error is: 0 x = 0.3333333333333333 Continued Fraction: 0, 3, The fraction is: 1 / 3 Target x = 0.3333333333333333 Fraction = 0.3333333333333333 Relative error is: 0 x = 0.4184397163120567 Continued Fraction: 0, 2, 2, 1, 1, 3, 3, The fraction is: 59 / 141 Target x = 0.4184397163120567 Fraction = 0.4184397163120567 Relative error is: 0 x = 0.8323518818409020 Continued Fraction: 0, 1, 4, 1, 27, 2, 7, 1, 2, 13, 3, 5, The fraction is: 1513686 / 1818565 Target x = 0.8323518818409020 Fraction = 0.8323518818409020 Relative error is: 0 x = 3.1415926535897931 Continued Fraction: 3, 7, 15, 1, 292, 1, 1, 1, 2, 1, 3, 1, 14, 3, The fraction is: 245850922 / 78256779 Target x = 3.1415926535897931 Fraction = 3.1415926535897931 Relative error is: 0 Press any key to continue . . . ``` The thing to notice here is that it gives `245850922 / 78256779` for `pi`. Obviously, **pi is irrational**. But as far as double-precision allows, `245850922 / 78256779` isn't any different from `pi`. Basically, any fraction with 8 - 9 digits in the numerator/denominator has enough entropy to cover nearly all DP floating-point values (barring corner cases like `INF`, `NAN`, or extremely large/small values).
76953
A Zabbix server I am currently started showing an alert like this: ``` /etc/passwd has been changed on Router ``` Now, on this Router machine I don't have a history of the passwd file so I cannot see exactly what changed, but what I know is that the time of the alert roughly coincided with this `Router` machine being rebooted. As soon as the router came back up, Zabbix started throwing this alert. Running `ls -l /etc/passwd` on the `Router` device shows that the last modified timestamp is roughly the same as the time of the reboot. This could be pure coincidence, but I'd rather double check here since I could not find anything online: can a simple device reboot cause the `/etc/passwd` file to be updated (if not in the contents, at least in the timestamp)?
Move the second folder one step up, move the contents, then move the second folder back. Like so: ``` cd folder1 mv folder2 .. mv * ../folder2/ mv ../folder2 . ```
76993
[Array.prototype.splice()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) allows to remove multiple elements from array but if and only if theese elements are siblings. But what if no? Suppose, we need to remove 2th, 5th and 8th elements from array (cont from 0). ```js const targetArray = [ "alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india" ]; const indexesOfArrayElementWhichMustBeRemoved = [ 2, 5, 8 ]; for (const [ index, element ] of targetArray.entries()) { if (indexesOfArrayElementWhichMustBeRemoved.includes(index)) { // remove } } ``` Once we removed one element, the array will change and 5th element will not be 5th anymore. Other approach is make elements empty first, and then remove empty elements: ```js for (const i = 0; i < targetArray.length; i++) { if (indexesOfArrayElementWhichMustBeRemoved.includes(i)) { delete targetArray[i] } } for (const [ index, element ] of targetArray.entries()) { if (typeof element === "undefined") { targetArray.splice[index, 1] } } ``` But this methodology does not match with "one pass" requirement and also will delete the element which had "undefined" value initially.
You could use [filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter), like this: ```js const sample = ['a', 'b', 'c', 'd', 'e', 'f'] const idx = [1, 3, 5]; const result = sample.filter((x, i) => idx.includes(i)); console.log(result); ``` Or if you want to specify which elements to remove, just do `!idx.includes(i)`. If mutating the original array is a requirement, then the best technique is usually to iterate over the array backwards, and remove as you go. That changing indexes don't matter as much. ``` for(let i=array.length-1;i>=0;i--){ // if ... array.splice } ```
77154
Two separate Flask applications, running on two different subdomains, however the login sessions are not persisting between the subdomains. For example; logging into a.example.co.uk will result in the user being logged in. However, visiting b.example.co.uk - the user will not be logged in. Running Apache, Flask (with Flask-Login), Ubuntu 18, Python 3. App secret is the same on both applications. Tried playing with SERVER\_NAME configuration setting. Cookies are correctly being set to .example.co.uk Cookies are configured to be used on any subdomain. ``` SESSION_COOKIE_NAME="example", SESSION_COOKIE_DOMAIN=".example.co.uk", REMEMBER_COOKIE_DOMAIN=".example.co.uk", ``` Logging into either subdomain should mean the user is logged into the other.
Managed to solve it! Turns out I was setting the Flask application secret keys in the wsgi files, like so; ``` from App import app as application application.secret_key = 'xxxxxxx' ``` And both the applications had different secret keys in their wsgi files! Completely forgot I was setting the secret keys in both the wsgi file and the main python file. Removing setting the secret keys from the wsgi files solved my problem
77658
What are the unit elements of $R/I$ where $I$ = {all cont. functions on $[0,1]$ |$ f(0) = f(1) = 0$} where $I$ is an Ideal w.r.t pointwise addition and multiplication.[![enter image description here](https://i.stack.imgur.com/OiZv5.jpg)](https://i.stack.imgur.com/OiZv5.jpg) I am little bit confused about it. Can you please help me out?
Here's another way to picture things. $A=\{f\in R\mid f(0)=0\}$ and $B=\{f\in R\mid f(1)=0\}$ are both maximal ideals of $R$. For example, the first one is the kernel of the epimorphism $\phi:R\to \mathbb R$ which maps $f\mapsto f(0)$. Your ideal $I$ is equal to $A\cap B$. By the Chinese remainder theorem, $\frac{R}{I}\cong R/A\times R/B\cong \mathbb R\times \mathbb R$. It is easy to see that the only units of the rightmost ring are ordered pairs with both entries nonzero, and this corresponds to elements of the quotient which are nonzero at both $0$ and $1$ on $[0,1]$. This takes care of the title question. Now for an $h$ which is nonzero on $0$ and $1$, if $h(c)=0$ for some $c\in (0,1)$, it is still a unit in the quotient, even though $h$ itself is not a unit in $R$. I think the method you're pursuing in the notes is to attempt to show that $h\equiv l \pmod I$ where $l$ is another thing in $R$ which you're sure is a unit (i.e. something which is nonzero *everywhere* on $[0,1]$) since you know that the homomorphic image of a unit is also a unit. So the only real mistake above is saying that $h(x)+I$ does not have a multiplicative inverse in $R/I$. It *does* have a multiplicative inverse: $l(x)+I$'s inverse. Of course $h$ doesn't have an inverse in $R$, but that is a separate matter.
77777
I'm making a little linear PSU for my lab. Based on the good ol' LM338K. I fried one last night and I'm still trying to figure out why. I think it might be EMF from my transformer. I have a transformer, a toroidal 220V to 12V 200W. I noticed it was built as two coils in parallel, so I figured i could connect the coils in series to make it 24V 100W. Indeed, this seems to work (when they're in the right phase, of course). Now, to reduce dissipation on the LM338K, I decided to add a small relay and connect it like this (let's call the point where the two coils are joined together the "center tap"). * "Right" transformer leg: Diode Bridge ~ input. * Relay common contact: Diode bridge ~ input. * "Left" Transformer leg: Relay NO. * "Center tap": Relay NC. This allows my PSU to start at 12VAC -> diode bridge + capacitor -> LM338K (I added all the suggested external components, especially the discharge diodes from Vout to Vin). To control the relay, I have a PIC (which also serves as voltmeter and current meter). I programmed the PIC so that when the output is over 9V, it switches to the full 24V. When it's below 8V, it switches back to 12V coil. To recap: here's the schematic for the relevant part. ![Switchover](https://i.stack.imgur.com/VUl63.jpg) Now, I was testing this last night. Something weird happened. I dialed my pot to 12V, I heard the clicking of the relay and I had effectively 12VDC at the output. When I loaded it with a 120R resistor, all was fine. Then I used a 12V 50W lamp. I gave it 6V. it was working good, regulated excellent. So i started dialing the voltage up to 12V and it started clicking like crazy (I suppose the hysteresis on my program was too quick), it switched 12/24 a few tens of times and then the voltage output went to 0.3V. I quickly shut everything down. Discharged the 2x4700uF caps at the diode bridge output, and turned it back on. It was working again. Then I noticed the voltage was a little off and smelled of "heat": it was the potentiometer glowing inside! The voltage output was = Vin. My LM338K was dead (this is not a fake 338K as the autopsy revealed the component is genuine: i took the cap off and it had a proper copper heatsink and several bond wires for high current pins). I'm thinking I didn't do anything wrong with this. All current and voltages were within spec of the regulator. The 338 has enough protections (my dad's 30 year old power supply has seen worse and the 338 never burned. Only that time when he accidentally hit a TV's B+ ..60V). The only thing I can think went wrong is that, when the coil is switched over, I have an open circuit on the transformer for a few milliseconds. Then the other coil is connected. I **think** what could have happened is EMF from the coil switching making a very high voltage spike appear on the 338 and frying it. Does this make sense? If EMF could be the problem, how could I solve this? I suppose a snubber network somewhere should do the work, but I'm not sure where. In my schematic, should a snubber network go between: - A and C? - A-B and B-C - AB, BC and AC? Also: how would I calculate the value for an RC network of this type? The relay specs 10mS "Operate time" and 5mS "release time".
Switching an inductor may make it work like a boost converter, and thus temporarily generate a higher voltage. One way of making sure that the input voltage to the LM338 converter is no higher than allowed, is to wire a high-wattage (between 600W and 5 kW) TVS diode with an appropriate clamping max voltage biased against the input voltage and ground. Also, if you're switching on the measured/actual output voltage, then you can get into oscillation. It would be safer to switch on "desired" output voltage, and let the regulator make sure it gets there. You could perhaps feed the bias voltage from the regulator ADJ into your microcontroller with a resistive divider to achieve this. Or you could just use a comparator with a pre-set trip point to drive/un-drive the relay.
77869
is there any way to convert this to a recursion form? how to find the unknown prime factors(in case it is a semiprime)? ``` semiPrime function: bool Recursividad::semiPrimo(int x) { int valor = 0; bool semiPrimo = false; if(x < 4) { return semiPrimo; } else if(x % 2 == 0) { valor = x / 2; if(isPrime(valor)) { semiPrimo = true; } } return semiPrimo; } ``` Edit: i've come to a partial solution(not in recursive form). i know i have to use tail recursion but where? ``` bool Recursividad::semiPrimo(int x){ bool semiPrimo=false; vector<int> listaFactores= factorizarInt(x); vector<int> listaFactoresPrimos; int y = 1; for (vector<int>::iterator it = listaFactores.begin(); it!=listaFactores.end(); ++it) { if(esPrimo(*it)==true){ listaFactoresPrimos.push_back(*it); } } int t=listaFactoresPrimos.front(); if(listaFactoresPrimos.size()<=1){ if(t*t==x){ semiPrimo=true; } }else{ int f=0; #pragma omp parallel { #pragma omp for for (vector<int>::iterator it = listaFactoresPrimos.begin(); it!=listaFactoresPrimos.end(); ++it) { f=*it; int j=0; for (vector<int>::iterator ot = listaFactoresPrimos.begin(); ot!=listaFactoresPrimos.end(); ++ot) { j=*ot; if((f * j)==x){ semiPrimo=true; } } } } } return semiPrimo; } ``` any help would be appreciated
@porterhouse91, have you checked your csproj file to make sure it has been set up with the appropriate build target? I haven't yet tried the new built-in Package Restore feature, but I'm assuming it works at least somewhat like the previous workflows out there on the interwebs. If that's the case, enabling Package Restore in your solution only affects the projects in your solution at the time you enable it. If you've added a new project (having NuGet dependencies) to the solution since enabling Package Restore, you're gonna need to enable it again. Another possibility: the previous workflows involved having a .nuget folder that you needed to check in to VCS, so you might need to check that in if it hasn't been checked in yet (if the built-in Package Restore feature does indeed use this approach). BTW, if this answer is at all helpful, thank Stephen Ritchie -- he asked me to give it a shot for you.
77874
I'm working with calendar application and basically idea behind this: I have a ListView of added events in particular date and what I would like to do is when I click on particular event of the day in ListView, onClick method would take that event's ID from database and start new activity with it. So I would need to pass that ID into the onClick method. I have found similar problem [HERE](https://stackoverflow.com/questions/27702638/how-can-i-get-the-row-id-of-the-a-table-in-the-sqlite-database-when-an-item-is-c), but cannot quite understand it for my case.. I have this `createBookings` method, it goes in the loop for each day where there are added events and returns list of events for the day. ``` public List<Booking> createBookings(Date data) { if(data!=null) { ..... ArrayList<Booking> events = new ArrayList<>(); if (c.moveToFirst()) { do { Integer eventID; String eventTitle, start_date, start_time, end_date, color; eventID = c.getInt(0); eventTitle = c.getString(1);start_time = c.getString(4); color = "•"+c.getString(7); if(eventTitle.isEmpty())eventTitle="(no title)"; Booking event = new Booking(eventID,color+" "+eventTitle+" "+start_time, data); events.add(event); } while (c.moveToNext()); } return events; } ``` I would assume passing `eventID` like this would be fine: `Booking event = new Booking(eventID,color+" "+eventTitle+" "+start_time, data);` but how do I get it later when onClickListener is called for the list view? All I managed to do is getText value of selected item.. ``` final List<String> mutableBookings = new ArrayList<>(); final ListView bookingsListView = (ListView) findViewById(R.id.bookings_listview); final ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mutableBookings); bookingsListView.setAdapter(adapter); bookingsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> bookingsListView, View view, int position, long id) { String item = ((TextView)view).getText().toString(); Toast.makeText(getApplicationContext()," "+item, Toast.LENGTH_SHORT).show(); } }); ``` My Booking class : ``` public class Booking { private Integer id; private String title; private Date date; public Booking(Integer id, String title, Date date) { this.id = id; this.title = title; this.date = date; } //lets say I had this method here.. would it return the correct event id //when called in onClickListener above? public String getBookingId() { return ""+id; } } ```
Yes the method you have written in your model class will return you the id of the clicked object but for that you will need to get the object first,so what you can do is , inside your `onItemClick()` method get your object like below ``` Booking booking = mutableBookings.get(position); // This will return you the object. ``` Now to get the `id` you can use your method like below ``` String id = booking.getBookingId(); // Now you can use this as per your needs ``` and yes i would like to recommend to use `int` instead of `Integer` in your model class.
77984
I want to show / hide my dropdown field against each selection of my radio button: HTML & PHP ``` <?php $Sr = 1; $FPSTopics = mysqli_query($con, "SELECT * FROM table"); for($i=0; $i< $FPSData = mysqli_fetch_array($FPSTopics); $i++){ ?> <tr> <td style="min-width:50px;"><?php echo $Sr; ?></td> <td><input type="text" value="<?php echo $FPSData['PFS_topic']; ?>" readonly required="required" size="58" ></td> <input type="hidden" name="FPSTopic[]" value="<?php echo $FPSData['PFS_topic_id']; ?>" /> <td style="min-width:50px;text-align:center; font-weight:bold"> <label>Yes</label> <input type="radio" name="Suitability[<?php echo $i; ?>]" value="Y" id="YesCheck" /> <label>No</label> <input type="radio" name="Suitability[<?php echo $i; ?>]" value="N" id="NoCheck" /></td> <td style="min-width:50px; color:blue; font-weight:bold" class="ShowPriority"> <select class="form-control my-1 mr-sm-2" id="Priority[]" name="Priority[]" > <option selected disabled value="">Choose Priority...</option> <option value="1">1 - High</option> <option value="2">2 - Intermediate</option> <option value="3">3 - Low</option> </select> </td> </tr> <?php $Sr++; } ?> ``` If One Select YES From Radio Button. The Field Of Priority should show. And if someone selects NO then the priority field should hide. Following is my JS Code. But upon selection, it hides the whole column instead of one field. ``` $('#NoCheck').click(function () { $('.ShowPriority').hide(); }) $('#YesCheck').click(function () { $('.ShowPriority').show(); }) ```
IDs need to be unique You likely will find this works more reliably since I navigate relative to the row ```js $('[name^=Suitability]').on("click", function() { // any button that starts with Suitablility $(this).closest('tr') .find('.ShowPriority') .toggle(this.value==="Y"); // show if "Y", Hide if not }) ``` ```css .ShowPriority { display:none;} ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr> <td style="min-width:50px;"> Row 1 </td> <td><input type="text" value="topic" readonly required="required" size="58"></td> <input type="hidden" name="FPSTopic[]" value="topic" /> <td style="min-width:50px;text-align:center; font-weight:bold"> <label>Yes</label> <input type="radio" name="Suitability1" value="Y" /> <label>No</label> <input type="radio" name="Suitability1" value="N"/> </td> <td style="min-width:50px; color:blue; font-weight:bold" class="ShowPriority"> <select class="form-control my-1 mr-sm-2" id="Priority[]" name="Priority[]"> <option selected disabled value="">Choose Priority...</option> <option value="1">1 - High</option> <option value="2">2 - Intermediate</option> <option value="3">3 - Low</option> </select> </td> </tr> <tr> <td style="min-width:50px;"> Row 2 </td> <td><input type="text" value="topic" readonly required="required" size="58"></td> <input type="hidden" name="FPSTopic[]" value="topic" /> <td style="min-width:50px;text-align:center; font-weight:bold"> <label>Yes</label> <input type="radio" name="Suitability2" value="Y" /> <label>No</label> <input type="radio" name="Suitability2" value="N" /> </td> <td style="min-width:50px; color:blue; font-weight:bold" class="ShowPriority"> <select class="form-control my-1 mr-sm-2" id="Priority[]" name="Priority[]"> <option selected disabled value="">Choose Priority...</option> <option value="1">1 - High</option> <option value="2">2 - Intermediate</option> <option value="3">3 - Low</option> </select> </td> </tr> </table> ```
78329
I am displaying some text in a JLabel. Basically I am generating that text dynamically, and then I apply some HTML tags (e.g., `BR` and `B`) to format the text. Finally I assign this formatted text to my JLabel. Now I want my Jlabel to automatically wrap the text to the next line when it reaches the end of screen, like the "Word Wrap" feature in Note Pad. How can I do that?
Should work if you wrap the text in `<html>...</html>` **UPDATE:** You should probably set maximum size, too, then.
78448
I just play a little with Go to learn the handling. I have a main go program. I created a sub-folder for a database module, in that I want to do database operations. For the parameters I have a struct type with credentials etc. How can I pass the struct to the module? I want all of the configuration and global variables needed in an configuration struct and pass it to the modules if needed. Is this a good method to achieve the goal? Thanks for the help. `./main.go`: ```golang package main import ( //... "github.com/wyrdnixx/go-server/src/go-server/dbapi" ) func handlerTest(w http.ResponseWriter, r *http.Request) { log.Println("INFO: /test was requested...") dbapi.Test(&AppConfig) } func main() { http.HandleFunc("/test", handlerTest) AppConfig = ReadConfig() log.Fatal(http.ListenAndServe(AppConfig.ApiPort, nil)) } type Configuration struct { ApiPort string DBHost string DBPort string DBUser string DBPassword string DBName string Info string } var AppConfig = Configuration{} func ReadConfig() Configuration { err := gonfig.GetConf("./config.development.json", &AppConfig) if err != nil { fmt.Println("ERROR: Config konnte nicht geladen werden: ", err.Error()) } return AppConfig } ``` `./dbapi/test.go`: ```golang package dbapi import ( // ... ) func Test (w http.ResponseWriter, Appconfig /* ?!? */) error { fmt.Println("Test: " + Appconfig.DBUser) } ```
I don't think the TypeScript compiler has enough support for higher order type analysis to do this for you. The problems I see: * There's no good way for the compiler to infer that the function `const mapper = (v: 1 | 2) => v === 1 ? "aaa" : "bbb"` is of a conditional generic type like `<V extends 1 | 2>(v: V) => V extends 1 ? "aaa" : "bbb"` or of an overloaded function type like `{(v: 1): "aaa", (v: 2): "bbb"}`. If you want the compiler to treat the function like that you will have to assert or annotate the type manually. * Even if it *could* infer that, there's no way to write a type function like `Apply<typeof f, typeof x>` where `f` is an overloaded or generic function of one argument, and `x` is an acceptable argument for it so that `Apply<typeof f, typeof x>` is the type of `f(x)`. Shorter: [there's no `typeof f(x)` in TypeScript](https://github.com/microsoft/TypeScript/issues/6606). So while you can *call* `mapper(1)` and the compiler knows the result is of type `"aaa"`, you can't represent that knowledge in the type system. That prevents you from doing something like [overloaded function resolution](https://github.com/microsoft/TypeScript/issues/29732) or [generic function resolution](https://github.com/microsoft/TypeScript/issues/14400) in the type system. --- The most straightforward typing I can imagine for `_.mapValues` would give you the wide `Record`-like type, and you'd have to [assert](https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions) a narrower type if you want that: ``` declare namespace _ { export function mapValues<T, U>( obj: T, fn: (x: T[keyof T]) => U ): Record<keyof T, U>; } const obj = { a: 1, b: 2 } as const; type ExpectedRet = { a: "aaa"; b: "bbb" }; _.mapValues(obj, v => (v === 1 ? "aaa" : "bbb")); // Record<"a"|"b", "aaa"|"bbb"> const ret = _.mapValues(obj, v => (v === 1 ? "aaa" : "bbb")) as ExpectedRet; ``` --- Otherwise you have to jump through many flaming hoops (manually specifying types, manually declaring functions as overloads) and you end up with something not much safer than a type assertion and a lot more complicated: ``` type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never; declare namespace _ { export function mapValues<T, U extends Record<keyof T, unknown>>( obj: T, fn: UnionToIntersection<{ [K in keyof T]: (x: T[K]) => U[K] }[keyof T]> ): U; } function mapper(v: 1): "aaa"; function mapper(v: 2): "bbb"; function mapper(v: 1 | 2): "aaa" | "bbb" { return v === 1 ? "aaa" : "bbb"; } const obj = { a: 1, b: 2 } as const; type ExpectedRet = { a: "aaa"; b: "bbb" }; const ret = _.mapValues<typeof obj, ExpectedRet>(obj, mapper); ``` Not sure if that's even worth explaining... you have to manually specify the input and expected output types in the call to `_.mapValues` because there's no way the compiler can infer the output type (as mentioned above). You have to manually specify that `mapper` is an overloaded function. The typing for `_.mapValues` is complicated and uses [`UnionToIntersection`](https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type) to describe the required overloaded function as the intersection of function types taking input values to output values. So, I'd stay away from this and just use a type assertion. --- Hope that helps; sorry I don't have a more satisfying answer. Good luck! [Link to code](https://www.typescriptlang.org/play/#code/HYQwtgpgzgDiDGEAEAlC8D2AnAJgGQEsBrZAbwFgAoJJHdAGxC2VElgWQH0kLqakIADxjYALkgBmAV2DxRBDMCRgQMAGoh6U6AB4AKgBokAVQB8ACir9+GAEYArAFxJDV65ODPzg53oDaJACeGBIuALoAlEgAvKYmbjQRzmiYuDpBIS5GZgDcbgC+bpjAUOJ29jE8SCDOAIxGts4ATEj51VBIxaV5fKKBMMgAosLoohA4aOLRVTVIAEQgi3M5SI3zthtzrT00nAB0Kuqa2lDm5UYAbjFx5lfR90i1SAD884sgW85zG7ZzERErAD0gNQ6GwOB0CzmAB9vnMjAslrCfnNTEVFKUkMwpkh9ocNFpoGcHJdrkhbjEHk9XoiPkgvij-u0kMMBnJxpMeoVKFRWNA4IgkABlURYRQAc3ogT0-XGACEpKIAIIAd2k9B4bj6AxMwAUwD0GAAksAxlgoKN9TozJVzMYBIIxsAcB0QMBAgkXuSiM5jFFYkgLhgCDhPc5gBALhAsFEhE6XeTzD6kARgBJo0gjf64kGQxFPa8jWGkBGo1gem46PBGMwS+B+RxcZq+DQhCIsOJpLJ5IplKoCSd9NkHfGOilwekIMFQoYkDIiMAMCrgKYLJ6aOVfAZ1x5fXrFIaTWaLXIraQkH4ANIppQZGdhLw+FxXyJk4wv1oBKeZPRhNEtpAkhMHZWioNwu1PXtDgGLBbjqIDaWWcCZEgpRoOjOCkCaBCURAiCezQ1QYMwp5oSwhD3i2Mjvk2ZtrGxKQsCUO4qS9RD6XWTYQO5dESjKBxKnPWZ6lWZpWmZLpRBA7UhhGdkJggHEhK+SiVjWGjfm2XjMWxSo8X7Y5dBkzJzhZOSxgU0QLFM9CYy5KggA)
78655
I'm looking for the EV3-G control block for the HiTechnic Color Sensor V2, previously distributed by HiTechnic (<https://www.hitechnic.com/cgi-bin/commerce.cgi?key=NCO1038&preadd=action>), apparently now distributed by Modern Robotics (<https://modernroboticsinc.com/product/hitechnic-nxt-color-sensor-v2/>). Many websites and online installation guides claim that the block is available from the downloads and support website from the original supplier (<https://www.hitechnic.com/downloadnew.php?category=38>). However, that site has been down for at least the past week and perhaps longer. Emails to both HiTechnic and Modern Robotics have gone unanswered, thus it appears that the sites are no longer maintained. :-( A similar question was recently asked and answered ([Anyone have the control block for the hitechnic color sensors?](https://bricks.stackexchange.com/questions/11079/anyone-have-the-control-block-for-the-hitechnic-color-sensors)), however, the direct download link suggested there (<https://www.hitechnic.com/upload/306-Color%20Sensor%20V2.zip>) is for the older NXT control block only. Unfortunately, the NXT block is not compatible with EV3-G and the current EV3 brick. I'm seeking the EV3 block, not the NXT block. I hope that someone here can help.
Hitechnic.com now points to modernroboticsinc.com. You can find the Hitechnic EV3 color sensor block here: <https://modernroboticsinc.com/download/hitechnic-ev3-color-sensor-block/> All available downloads are available and searchable here: <https://modernroboticsinc.com/downloads/>
78720
I am trying to delete the nodes that has a relationship to each other node if the relationship exist. If the relationship doesnt exist delete the first node. Example: I am using UNWIND because that is the data provided by the user. ``` UNWIND [{name:'John'}] as rows IF EXISTS(u:Person)-[r:OWNS]->(c:Car), THEN MATCH (u:Person)-[r:OWNS]->(c:Car) WHERE u.user_name = rows.name DETACH DELETE u,c OTHERWISE MATCH (u:Person) WHERE u.user_name = rows.name DETACH DELETE u ``` I tried using apoc.do.when however they dont allow EXISTS(u:User)-[r:OWNS]->(c:Car) as a conditional statement.
I have faced the same issue. Don't pacnic. Open Windows `cmd` or Ubuntu/MacOS/Linux `terminal` and run `flutter upgrade -v` . It takes time to download and sometimes if failed error doesn't appear in IDE. In terminal/cmd you can see the progress. Restart your IDE once the upgrade finishes.
78757
Running the following ``` poetry shell ``` returns the following error ``` /home/harshagoli/.poetry/lib/poetry/_vendor/py2.7/subprocess32.py:149: RuntimeWarning: The _posixsubprocess module is not being used. Child process reliability may suffer if your program uses threads. "program uses threads.", RuntimeWarning) The currently activated Python version 2.7.17 is not supported by the project (^3.7). Trying to find and use a compatible version. Using python3 (3.7.5) Virtual environment already activated: /home/harshagoli/.cache/pypoetry/virtualenvs/my-project-0wt3KWFj-py3.7 ``` How can I get past this error? Why doesn't this command work?
`poetry shell` is a really buggy command, and this is often talked about among the maintainers. A workaround for this specific issue is to activate the shell manually. It might be worth aliasing the following ``` source $(poetry env info --path)/bin/activate ``` so you need to paste this into your `.bash_aliases` or `.bashrc` ``` alias acpoet="source $(poetry env info --path)/bin/activate" ``` Now you can run `acpoet` to activate your poetry env (don't forget to source your file to enable the command)
78821
I need to use collections as below, but want to print the output dynamically instead of specifying PL01, PL02, PL03...as this is going to be bigger list. If not possible using RECORD type, how can this be achieved using collections. Business scenario : Having a item price list in an excel sheet as price list code in the first row (each column refers to a price list) and different items in each row. The number of price list and the items will differ every time. Now i need to populate this excel in collections in same format (Table with items in rows and price list code as columns) and use it to update the correct price list. ``` DECLARE TYPE RT IS RECORD (ITEM VARCHAR2(20), PL01 NUMBER, PL02 NUMBER, PL03 NUMBER, PL04 NUMBER, PL05 NUMBER); TYPE TT IS TABLE OF RT; MY_REC RT; MY_TAB TT := TT(); BEGIN MY_TAB.EXTEND; MY_TAB(1).ITEM := 'ABC'; MY_TAB(1).PL01 := '40'; MY_TAB(1).PL02 := '42'; MY_TAB(1).PL03 := '44'; MY_TAB(1).PL04 := '46'; MY_TAB(1).PL05 := '48'; MY_TAB.EXTEND; MY_TAB(2).ITEM := 'DEF'; MY_TAB(2).PL01 := '60'; MY_TAB(2).PL02 := '62'; MY_TAB(2).PL03 := '64'; MY_TAB(2).PL04 := '66'; MY_TAB(2).PL05 := '68'; FOR I IN 1..2 LOOP Dbms_Output.PUT_LINE(MY_TAB(I).ITEM||' - '||MY_TAB(I).PL01||' - '||MY_TAB(I).PL02||' - '|| MY_TAB(I).PL03||' - '||MY_TAB(I).PL04||' - '||MY_TAB(I).PL05); END LOOP; END; / ```
One way is to create `TYPE` as objects and using a `TABLE` function to display by passing a `REFCURSOR`. ``` CREATE OR REPLACE TYPE RT AS OBJECT ( ITEM VARCHAR2(20), PL01 NUMBER, PL02 NUMBER, PL03 NUMBER, PL04 NUMBER, PL05 NUMBER ); / CREATE OR REPLACE TYPE TT AS TABLE OF RT; / ``` --- ``` VARIABLE x REFCURSOR; DECLARE MY_TAB TT := TT(); BEGIN MY_TAB.EXTEND(2); --allocate 2 elements MY_TAB(1) := RT ( 'ABC',40,42,44,46,48);--you can assign all once/index MY_TAB(2) := RT ( 'DEF',60,62,64,66,68); OPEN :x FOR SELECT * FROM TABLE(MY_TAB); END; / ``` --- ``` PRINT x ITEM PL01 PL02 PL03 PL04 PL05 -------------------- ---------- ---------- ---------- ---------- ---------- ABC 40 42 44 46 48 DEF 60 62 64 66 68 ```
78904
I'm working on an Objective-C app that is Mac OS X Lion only. I'm trying to accept drag & drops from Address Book. It looks like in Lion, Address Book vCard representations are not returning any data. Unfortunately I cannot test the code under a previous OS, though I had found sample code suggesting that it was possible before. I setup my table to receive `kUTTypeVCard` like the docs suggest for 10.6+ (though `NSVCardPboardType` works, too) and I do receive the drop event. So to debug I setup a loop to output the data types and their values from the drop: ``` - (BOOL)tableView:(NSTableView *)aTableView acceptDrop:(id <NSDraggingInfo>)info row:(NSInteger)row dropOperation:(NSTableViewDropOperation)operation { NSPasteboard *pb = [info draggingPasteboard]; NSArray *types = pb.types; for (NSString *type in types) { NSLog(@" "); NSLog(@"%@:", type); NSLog(@" property list = %@", [pb propertyListForType:type]); NSLog(@" data = %@", [pb dataForType:type]); NSLog(@" string = %@", [pb stringForType:type]); } NSLog(@" "); return YES; } ``` The results are as follows: ``` 2012-02-01 19:46:18.907 MyAppName[586:60b] 2012-02-01 19:46:18.907 MyAppName[586:60b] dyn.ah62d4rv4gu8ycuwftb2gc5xeqzwfg3pqqzv1k4ptr3m1k6xmr3xyc6xwqf6zk8puqy: 2012-02-01 19:46:18.909 MyAppName[586:60b] property list = (null) 2012-02-01 19:46:18.911 MyAppName[586:60b] data = (null) 2012-02-01 19:46:18.912 MyAppName[586:60b] string = (null) 2012-02-01 19:46:18.913 MyAppName[586:60b] 2012-02-01 19:46:18.913 MyAppName[586:60b] ABExpandedSelectionStringArrayType: 2012-02-01 19:46:18.914 MyAppName[586:60b] property list = (null) 2012-02-01 19:46:18.914 MyAppName[586:60b] data = (null) 2012-02-01 19:46:18.915 MyAppName[586:60b] string = (null) 2012-02-01 19:46:18.915 MyAppName[586:60b] 2012-02-01 19:46:18.915 MyAppName[586:60b] dyn.ah62d4rv4gu8ycuwxqz0gn25yrf106y5ysmy0634bsm3gc8nytf2gn: 2012-02-01 19:46:18.917 MyAppName[586:60b] property list = (null) 2012-02-01 19:46:18.918 MyAppName[586:60b] data = (null) 2012-02-01 19:46:18.918 MyAppName[586:60b] string = (null) 2012-02-01 19:46:18.918 MyAppName[586:60b] 2012-02-01 19:46:18.919 MyAppName[586:60b] ABSelectionStringArrayType: 2012-02-01 19:46:18.919 MyAppName[586:60b] property list = (null) 2012-02-01 19:46:18.921 MyAppName[586:60b] data = (null) 2012-02-01 19:46:18.922 MyAppName[586:60b] string = (null) 2012-02-01 19:46:18.922 MyAppName[586:60b] 2012-02-01 19:46:18.922 MyAppName[586:60b] dyn.ah62d4rv4gu8yc6durvwwa3xmrvw1gkdusm1044pxqyuha2pxsvw0e55bsmwca7d3sbwu: 2012-02-01 19:46:18.922 MyAppName[586:60b] property list = ( vcf ) 2012-02-01 19:46:18.923 MyAppName[586:60b] data = <3c3f786d 6c207665 7273696f 6e3d2231 2e302220 656e636f 64696e67 3d225554 462d3822 3f3e0a3c 21444f43 54595045 20706c69 73742050 55424c49 4320222d 2f2f4170 706c652f 2f445444 20504c49 53542031 2e302f2f 454e2220 22687474 703a2f2f 7777772e 6170706c 652e636f 6d2f4454 44732f50 726f7065 7274794c 6973742d 312e302e 64746422 3e0a3c70 6c697374 20766572 73696f6e 3d22312e 30223e0a 3c617272 61793e0a 093c7374 72696e67 3e766366 3c2f7374 72696e67 3e0a3c2f 61727261 793e0a3c 2f706c69 73743e0a> 2012-02-01 19:46:18.923 MyAppName[586:60b] string = <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <array> <string>vcf</string> </array> </plist> 2012-02-01 19:46:18.923 MyAppName[586:60b] 2012-02-01 19:46:18.923 MyAppName[586:60b] Apple files promise pasteboard type: 2012-02-01 19:46:18.923 MyAppName[586:60b] property list = ( vcf ) 2012-02-01 19:46:18.924 MyAppName[586:60b] data = <3c3f786d 6c207665 7273696f 6e3d2231 2e302220 656e636f 64696e67 3d225554 462d3822 3f3e0a3c 21444f43 54595045 20706c69 73742050 55424c49 4320222d 2f2f4170 706c652f 2f445444 20504c49 53542031 2e302f2f 454e2220 22687474 703a2f2f 7777772e 6170706c 652e636f 6d2f4454 44732f50 726f7065 7274794c 6973742d 312e302e 64746422 3e0a3c70 6c697374 20766572 73696f6e 3d22312e 30223e0a 3c617272 61793e0a 093c7374 72696e67 3e766366 3c2f7374 72696e67 3e0a3c2f 61727261 793e0a3c 2f706c69 73743e0a> 2012-02-01 19:46:18.924 MyAppName[586:60b] string = <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <array> <string>vcf</string> </array> </plist> 2012-02-01 19:46:18.924 MyAppName[586:60b] 2012-02-01 19:46:18.925 MyAppName[586:60b] dyn.ah62d4rv4gu8ycuwuqz11a5dfnzeyk64uqm10c6xenv61a3k: 2012-02-01 19:46:18.925 MyAppName[586:60b] property list = ( "C9786D5F-157A-4A65-A95E-C61752D2B4E3:ABPerson" ) 2012-02-01 19:46:18.925 MyAppName[586:60b] data = <3c3f786d 6c207665 7273696f 6e3d2231 2e302220 656e636f 64696e67 3d225554 462d3822 3f3e0a3c 21444f43 54595045 20706c69 73742050 55424c49 4320222d 2f2f4170 706c652f 2f445444 20504c49 53542031 2e302f2f 454e2220 22687474 703a2f2f 7777772e 6170706c 652e636f 6d2f4454 44732f50 726f7065 7274794c 6973742d 312e302e 64746422 3e0a3c70 6c697374 20766572 73696f6e 3d22312e 30223e0a 3c617272 61793e0a 093c7374 72696e67 3e433937 38364435 462d3135 37412d34 4136352d 41393545 2d433631 37353244 32423445 333a4142 50657273 6f6e3c2f 73747269 6e673e0a 3c2f6172 7261793e 0a3c2f70 6c697374 3e0a> 2012-02-01 19:46:18.926 MyAppName[586:60b] string = <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <array> <string>C9786D5F-157A-4A65-A95E-C61752D2B4E3:ABPerson</string> </array> </plist> 2012-02-01 19:46:18.926 MyAppName[586:60b] 2012-02-01 19:46:18.926 MyAppName[586:60b] ABPeopleUIDsPboardType: 2012-02-01 19:46:18.927 MyAppName[586:60b] property list = ( "C9786D5F-157A-4A65-A95E-C61752D2B4E3:ABPerson" ) 2012-02-01 19:46:18.927 MyAppName[586:60b] data = <3c3f786d 6c207665 7273696f 6e3d2231 2e302220 656e636f 64696e67 3d225554 462d3822 3f3e0a3c 21444f43 54595045 20706c69 73742050 55424c49 4320222d 2f2f4170 706c652f 2f445444 20504c49 53542031 2e302f2f 454e2220 22687474 703a2f2f 7777772e 6170706c 652e636f 6d2f4454 44732f50 726f7065 7274794c 6973742d 312e302e 64746422 3e0a3c70 6c697374 20766572 73696f6e 3d22312e 30223e0a 3c617272 61793e0a 093c7374 72696e67 3e433937 38364435 462d3135 37412d34 4136352d 41393545 2d433631 37353244 32423445 333a4142 50657273 6f6e3c2f 73747269 6e673e0a 3c2f6172 7261793e 0a3c2f70 6c697374 3e0a> 2012-02-01 19:46:18.937 MyAppName[586:60b] string = <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <array> <string>C9786D5F-157A-4A65-A95E-C61752D2B4E3:ABPerson</string> </array> </plist> 2012-02-01 19:46:18.937 MyAppName[586:60b] 2012-02-01 19:46:18.937 MyAppName[586:60b] public.vcard: 2012-02-01 19:46:18.942 MyAppName[586:60b] property list = (null) 2012-02-01 19:46:18.944 MyAppName[586:60b] data = (null) 2012-02-01 19:46:18.945 MyAppName[586:60b] string = (null) 2012-02-01 19:46:18.945 MyAppName[586:60b] 2012-02-01 19:46:18.945 MyAppName[586:60b] Apple VCard pasteboard type: 2012-02-01 19:46:18.945 MyAppName[586:60b] property list = (null) 2012-02-01 19:46:18.946 MyAppName[586:60b] data = (null) 2012-02-01 19:46:18.946 MyAppName[586:60b] string = (null) 2012-02-01 19:46:18.948 MyAppName[586:60b] 2012-02-01 19:46:18.949 MyAppName[586:60b] dyn.ah62d4rv4gu8z82xqqz1gk3penm11swpsqvw1u3px: 2012-02-01 19:46:18.949 MyAppName[586:60b] property list = (null) 2012-02-01 19:46:18.949 MyAppName[586:60b] data = <040b7374 7265616d 74797065 6481e803 84014084 8484114e 534d7574 61626c65 496e6465 78536574 0084840a 4e53496e 64657853 65740084 84084e53 4f626a65 63740085 84014901 96817c01 960186> 2012-02-01 19:46:18.949 MyAppName[586:60b] string = (null) 2012-02-01 19:46:18.949 MyAppName[586:60b] 2012-02-01 19:46:18.950 MyAppName[586:60b] _blendedRowIndexes: 2012-02-01 19:46:18.950 MyAppName[586:60b] property list = (null) 2012-02-01 19:46:18.950 MyAppName[586:60b] data = <040b7374 7265616d 74797065 6481e803 84014084 8484114e 534d7574 61626c65 496e6465 78536574 0084840a 4e53496e 64657853 65740084 84084e53 4f626a65 63740085 84014901 96817c01 960186> 2012-02-01 19:46:18.950 MyAppName[586:60b] string = (null) 2012-02-01 19:46:18.950 MyAppName[586:60b] 2012-02-01 19:46:18.950 MyAppName[586:60b] com.apple.pasteboard.promised-file-content-type: 2012-02-01 19:46:18.951 MyAppName[586:60b] property list = public.vcard 2012-02-01 19:46:18.951 MyAppName[586:60b] data = <7075626c 69632e76 63617264> 2012-02-01 19:46:18.951 MyAppName[586:60b] string = public.vcard 2012-02-01 19:46:18.952 MyAppName[586:60b] 2012-02-01 19:46:18.952 MyAppName[586:60b] com.apple.pasteboard.promised-file-url: 2012-02-01 19:46:18.954 MyAppName[586:60b] property list = (null) 2012-02-01 19:46:18.954 MyAppName[586:60b] data = <> 2012-02-01 19:46:18.954 MyAppName[586:60b] string = 2012-02-01 19:46:18.955 MyAppName[586:60b] 2012-02-01 19:46:18.955 MyAppName[586:60b] dyn.ah62d4rv4gu8y6y4usm1044pxqzb085xyqz1hk64uqm10c6xenv61a3k: 2012-02-01 19:46:18.955 MyAppName[586:60b] property list = (null) 2012-02-01 19:46:18.956 MyAppName[586:60b] data = <> 2012-02-01 19:46:18.956 MyAppName[586:60b] string = 2012-02-01 19:46:18.956 MyAppName[586:60b] 2012-02-01 19:46:18.956 MyAppName[586:60b] NSPromiseContentsPboardType: 2012-02-01 19:46:18.956 MyAppName[586:60b] property list = (null) 2012-02-01 19:46:18.957 MyAppName[586:60b] data = <> 2012-02-01 19:46:18.957 MyAppName[586:60b] string = 2012-02-01 19:46:18.957 MyAppName[586:60b] ``` Most of the types looks like private Address Book data types. But you can see that the vCard representations are null. And I'm thinking that even if I used `ABPeopleUIDsPboardType`, it would get rejected from the App Store because it's not available in any header file. Any suggestion in how to handle a drag & drop from Address Book under Lion? Thanks. **\* Edit 2/5/12 \*** Tried researching promised drags and promised contents, but still coming up empty: ``` - (BOOL)tableView:(NSTableView *)aTableView acceptDrop:(id <NSDraggingInfo>)info row:(NSInteger)row dropOperation:(NSTableViewDropOperation)operation { NSPasteboard *pb = [info draggingPasteboard]; // Supposed to call this before readFileContentsType:toFile: for some reason NSArray *types = pb.types; NSString *destPath = NSTemporaryDirectory(); NSURL *destURL = [NSURL fileURLWithPath:destPath isDirectory:YES]; NSArray *fileNames = [info namesOfPromisedFilesDroppedAtDestination:destURL]; NSLog(@"fileNames = %@", fileNames); NSString *afile = [pb readFileContentsType:nil toFile:@"random_filename"]; // Tried with (NSString *)kUTTypeVCard as well, same results NSLog(@"afile = %@", afile); // What do I do with this result? NSString *card = [NSString stringWithContentsOfFile:afile]; NSLog(@"card = %@", card); NSFileWrapper *wrapper = [pb readFileWrapper]; NSLog(@"wrapper = %@", wrapper); return YES; } ``` Results: ``` 2012-02-05 12:36:58.419 MyAppName[3650:60b] fileNames = (null) 2012-02-05 12:36:58.419 MyAppName[3650:60b] afile = random_filename 2012-02-05 12:36:58.419 MyAppName[3650:60b] card = (null) 2012-02-05 12:36:58.420 MyAppName[3650:60b] wrapper = (null) ```
Sorry about this, I'm the culprit :) Hopefully we will be able to push the next version soon. Not the time to mention this, but there is an upside to this accident: it means we can definitely kill the current serial form of BF and its related supporting code (which was an accident itself), which I'm trying to fix [for a month now](https://groups.google.com/group/guava-discuss/browse_thread/thread/7b114767ee312e9e?pli=1) - incidentally the fix to that also fixes this problem. Edit: more information [here](https://groups.google.com/group/guava-discuss/browse_thread/thread/32549c2cd5fea94b#) (and in Louis' filed issue)
79381
> > **Question 1**$\;\;\;$Let $(\Omega,\mathcal A,(\mathcal F\_t)\_{t\ge 0},\operatorname P)$ be a given filtered probability space. Can we prove that there is a Brownian motion on $(\Omega,\mathcal A,\mathcal F,\operatorname P)$? > > > All I know is that we can find some $(\Omega,\mathcal A,(\mathcal F\_t)\_{t\ge 0},\operatorname P)$ such that a Brownian motion on this filtered probability space exists. For example, we can choose $\Omega=\mathbb R^{[0,\infty)}$, $\mathcal A=\mathcal B(\mathbb R)^{\otimes[0,\infty)}$ and $$X\_t(\omega):=\omega(t)\;\;\;\text{for }(\omega,t)\in\Omega\times[0,\infty)\;.$$ Then, it's possible to construct a probability measure $\operatorname P$ on $(\Omega,\mathcal A)$ such that $X$ has independent, stationary and normally distributed increments (so, $\mathcal F$ will be the $\sigma$-algebra generated by $X$). The continuity can be concluded by the Kolmogorov-Chentsov theorem. > > **Question 2**$\;\;\;$I suppose the answer to question 1 will be *no*. In that case, I'm curious about the role of $\mathcal F$. As I said above, we can show the existence of a probability space such that there is a Brownian motion with respect to their generated $\sigma$-algebra. If that's all we can prove, then the role of $\mathcal F$ seems to be very negligible . > > >
It is known that a probability space is atomless if and only if there exists a random variable with continuous distribution. Therefore, in particular, a probability space with atoms cannot have a normal random variable. Thus, the answer is no. On the other hand, the Levy-Ciesielski construction of the Brownian motion relies on the existence of a sequence of independent standard normal random variables. It is also known that if a probability space is atomless, then for any non-degenate probability distribution there exists a sequence of independent random variables with that distribution (see, for instance the book "Monetary Utility Functions" by Delbaen, where is stated a characterization of atomless probability spaces) and therefore a Brownian motion can be constructed by using the Levy-C. method. As conclusion, for a given probability space it has a Brownian motion if and only if it is atomless.
79752
I ran into an impasse trying to automate the creation of new git repositories using powershell. As I understand one creates new repos using the POST Method on the url ``` /rest/api/1.0/projects/$ProjectKey/repos ``` <https://developer.atlassian.com/static/rest/stash/3.0.1/stash-rest.html#idp1178320> Because you have to be admin to modify stuff I add an authorization header field to the webrequest. ```powershell $ByteArr = [System.Text.Encoding]::UTF8.GetBytes('admin:pwd') $Base64Creds = [Convert]::ToBase64String($ByteArr) $ProjectKey = 'SBOX' $CreateRepoUri = "$BaseUri/rest/api/1.0/projects/$ProjectKey/repos/" Invoke-RestMethod -Method Post ` -Headers @{ Authorization="Basic $Base64Creds" } ` -Uri $CreateRepoUri ` -ContentType 'application/json' ` -Body @{ slug='test'; name='RestCreatedRepo';} ``` But when executing I get an Internal Server Error (500). No more details or InnerExceptions on why exactly. Retrieving a list of repositories with GET worked so authentication works (at least for the Get requests) According to this, it should be a correct statement: * <https://answers.atlassian.com/questions/127261/create-project-using-rest> * [powershell http post REST API basic authentication](https://stackoverflow.com/questions/8919414/powershell-http-post-rest-api-basic-authentication) What exactly is this slug or scmId (Anybody heard of it)? It would be greate if one of you geniuses could point me in the right direction as I just gotten into using webservises. Thanks, Michael
The [REST API documentation](https://developer.atlassian.com/static/rest/stash/3.0.1/stash-rest.html#idp1178320) is a little vague around it, but I don't think you can set the repository slug based on [this section](https://developer.atlassian.com/static/rest/stash/3.0.1/stash-rest.html#idp1207472). Neither specifically says you can or cannot change the slug, but demonstrate using name and hint that the slug could change if the name changes. > > The repository's slug is derived from its name. If the name changes the slug may also change. > > > In the example a repo is created with the name "My Repo", causing the slug to be "my-repo". So, I believe the slug is basically a "normalized" version of the repository's name. ScmId identifies what type of source control management to use for the repository (e.g. "git"). For the body of your request, I'm also not sure that `Invoke-RestMethod` will automatically convert that to JSON for you. You can use the `ConvertTo-Json` Cmdlet for this, or in smaller cases just manually create the JSON string. This works for me: ``` $baseUrl = 'http://example.com' $usernamePwd = 'admin:passwd' $project = 'SBOX' $repoName = 'RestCreatedRepo' $headers = @{} $headers.Add('Accept', 'application/json') $bytes = [System.Text.Encoding]::UTF8.GetBytes($usernamePwd) $creds = 'Basic ' + [Convert]::ToBase64String($bytes) $headers.Add('Authorization', $creds) $data = '{"name": "{0}","scmId": "git","forkable": true}' -f $repoName $url = '{0}/rest/api/1.0/projects/{1}/repos' -f $baseUrl,$project $response = try { Invoke-RestMethod -Method Post ` -Uri $url ` -Headers $headers ` -ContentType 'application/json' ` -Body $data } catch { $_.Exception.Response } ```
79893
I am currently trying to solve a problem where the input should be as following ``` int hours(int rows, int columns, List<List<Integer> > grid) ``` Where list grid is a Matrix of 0 and 1 ( 0 means not complete , 1 means complete ) as following: ``` 0 1 1 0 1 0 1 0 1 0 0 0 0 0 1 0 1 0 0 0 ``` Each value represent a machine in a network sending files to each other, So if the value is "1" then this node is able to send the files to **ALL NEIGHBORS** (Diagonal ones does not count only up/down/right/left).The issue is that once a 0 becomes a 1 ( affected by the neighbor cell ) it cannot send the file to any other neighbor before 1 HOUR. The goal of the problem is to return how many hours shall it take before all the nodes receive the files? ( in other words all the Matrix becomes 1. **Considering Run time complexity** For visual explanation: ( After the first hour this should be the state of the matrix which is considered as an iteration): ``` 1 1 1 1 1 1 1 1 1 1 0 1 0 1 1 1 1 1 0 1 ``` So, I followed an approach where I loop over the matrix looking in the provided grid and appending values in a temporary array ( as I don't know how to update or append the list values inside the main List). Then once the row index has reached the max i add 1 hour to an int variable and add values to the main grid. I know the below code is not still working/complete and may have syntax mistakes but you get the idea and the approach. My Question is, Is there any easier and efficient method than mine?? I also found a solution [here](https://stackoverflow.com/a/12744657/12582441) But that only works with 2D arrays if my idea is worth it. However, wouldn't these 4 nested loop mess up the complexity of the code? ``` List<List<Integer>> grid2 = grid1; boolean received= false; int hours=0; int rows_Temp = 0 ; int columsTemp = 0 ; int[][] grid2 = null ; while(rows_Temp<rows&&!received) { if(rows_Temp==rows-1) { rows_Temp=0; } if(rows_Temp==0) { //create an array with the grid dimention grid2= new int[rows][columns]; } //manage top left corner if(rows_Temp==0 && columsTemp == 0 ) { //find right & down int center= grid.get(rows_Temp).get(columsTemp); int right = grid.get(rows_Temp).get(columsTemp+1); int down = grid.get(rows_Temp+1).get(columsTemp); if(center==1) { if(right==0) { grid2[rows_Temp][columsTemp+1] = 1; } if(down==0) { grid2[rows_Temp+1][columsTemp]=1; } } } //manage top right corner else if(rows_Temp==0 && columsTemp == columns-1) { //find left and down int center= grid.get(rows_Temp).get(columsTemp); int left = grid.get(rows_Temp).get(columsTemp-1); int down = grid.get(rows_Temp+1).get(columsTemp); if(center==1) { if(left==0) { grid2[rows_Temp][columsTemp-1] = 1; } if(down==0) { grid2[rows_Temp+1][columsTemp]=1; } } } //mange down left corner of the array else if(rows_Temp==rows-1 && columsTemp == 0) { //find up and right int center= grid.get(rows_Temp).get(columsTemp); int right = grid.get(rows_Temp).get(columsTemp+1); int up = grid.get(rows_Temp-1).get(columsTemp); if(center==1) { if(right==0) { grid2[rows_Temp][columsTemp+1] = 1; } if(up==0) { grid2[rows_Temp-1][columsTemp]=1; } } } //manage down right corner else if(rows_Temp==rows-1 && columsTemp == columns-1) { //find left and up int center= grid.get(rows_Temp).get(columsTemp); int left = grid.get(rows_Temp).get(columsTemp-1); int up = grid.get(rows_Temp-1).get(columsTemp); if(center==1) { if(left==0) { grid2[rows_Temp][columsTemp-1] = 1; } if(up==0) { grid2[rows_Temp-1][columsTemp]=1; } } } //manage left sides but not corners else if(rows_Temp!=0&& rows_Temp!=rows-1&& columsTemp==0) { int center= grid.get(rows_Temp).get(columsTemp); int right = grid.get(rows_Temp).get(columsTemp+1); int up = grid.get(rows_Temp-1).get(columsTemp); int down = grid.get(rows_Temp+1).get(columsTemp); if(center==1) { if(right==0) { grid2[rows_Temp][columsTemp+1] = 1; } if(up==0) { grid2[rows_Temp-1][columsTemp]=1; } if(down==0) { grid2[rows_Temp+1][columsTemp]=1; } } } if(columsTemp==columns-1) { columsTemp=0; rows_Temp++; System.out.println(); } else { columsTemp++; } } System.out.println("------------"); return 0 ; } ```
If you're allowed to update `grid`, use `grid.get(y).get(x)` to check the grid and `grid.get(y).set(x, value)` to update the grid. If you're not allowed to update the grid, start by copying the values into a `int[][]` 2D array, then use that instead in the solution below. Scan the grid for `0` values, and add the coordinates to a `Queue<Point>`, e.g. an `ArrayDeque<Point>`, where `Point` is an object with two `int` fields, e.g. the [`java.awt.Point`](https://docs.oracle.com/javase/8/docs/api/java/awt/Point.html) class. We do that to ensure good performance, with run time complexity as *O(nm)*, where `n` and `m` are the width and height of the grid. Start a loop with `i = 1`. In the loop, iterate the queue. If the point has a neighboring value equal to `i`, set the points value to `i + 1`, otherwise add the point to a second queue. At the end, replace the first queue with the second queue, increase `i` by 1 and do it again, until the queue is empty. The result is a progression of the 2D matrix like this: ``` 0 1 1 0 1 → 2 1 1 2 1 → 2 1 1 2 1 → 2 1 1 2 1 0 1 0 0 0 → 2 1 2 0 2 → 2 1 2 3 2 → 2 1 2 3 2 0 0 0 0 1 → 0 2 0 2 1 → 3 2 3 2 1 → 3 2 3 2 1 0 0 0 1 0 → 0 0 2 1 2 → 0 3 2 1 2 → 4 3 2 1 2 ``` The highest value in the matrix is 4, so the answer is 3 hours, one less than highest value. --- **UPDATE** Here is the code, which copies the input to a 2D array, and lowers the values by 1, since it makes more sense that way. ``` static int hours(int rows, int columns, List<List<Integer>> grid) { // Build hourGrid, where value is the number of hours until the // node can send, with MAX_VALUE meaning the node cannot send. // Also build queue of nodes that cannot send. int[][] hourGrid = new int[rows][columns]; Queue<Point> pending = new ArrayDeque<>(); for (int y = 0; y < rows; y++) { for (int x = 0; x < columns; x++) { if (grid.get(y).get(x) == 0) { hourGrid[y][x] = Integer.MAX_VALUE; pending.add(new Point(x, y)); } } } // Keep iterating the queue until all pending nodes can send. // Each iteration adds 1 hour to the total time. int hours = 0; for (; ! pending.isEmpty(); hours++) { // Check all pending nodes if they can receive data Queue<Point> notYet = new ArrayDeque<>(); for (Point p : pending) { if ((p.x > 0 && hourGrid[p.y][p.x - 1] <= hours) || (p.x < columns - 1 && hourGrid[p.y][p.x + 1] <= hours) || (p.y > 0 && hourGrid[p.y - 1][p.x] <= hours) || (p.y < rows - 1 && hourGrid[p.y + 1][p.x] <= hours)) { // Node can receive from a neighbor, so will be able to send in 1 hour hourGrid[p.y][p.x] = hours + 1; } else { // Not receiving yet, so add to queue for next round notYet.add(p); } } pending = notYet; } return hours; } ``` For testing, building a `List<List<Integer>>`, and sending in separate `rows` and `columns` values, is cumbersome, so here is a helper method: ``` static int hours(int[][] grid) { final int rows = grid.length; final int columns = grid[0].length; List<List<Integer>> gridList = new ArrayList<>(rows); for (int[] row : grid) { List<Integer> rowList = new ArrayList<>(columns); for (int value : row) rowList.add(value); // autoboxes gridList.add(rowList); } return hours(rows, columns, gridList); } ``` *Test* ``` System.out.println(hours(new int[][] { // data from question { 0, 1, 1, 0, 1 }, { 0, 1, 0, 1, 0 }, { 0, 0, 0, 0, 1 }, { 0, 1, 0, 0, 0 }, })); System.out.println(hours(new int[][] { // data from answer { 0, 1, 1, 0, 1 }, { 0, 1, 0, 0, 0 }, { 0, 0, 0, 0, 1 }, { 0, 0, 0, 1, 0 }, })); ``` *Output* ```none 2 3 ```
79938
I have a set of files. The path to the files are saved in a file., say `all_files.txt`. Using apache spark, I need to do an operation on all the files and club the results. The steps that I want to do are: * Create an RDD by reading `all_files.txt` * For each line in `all_files.txt` (Each line is a path to some file), read the contents of each of the files into a single RDD * Then do an operation all contents This is the code I wrote for the same: ``` def return_contents_from_file (file_name): return spark.read.text(file_name).rdd.map(lambda r: r[0]) def run_spark(): file_name = 'path_to_file' spark = SparkSession \ .builder \ .appName("PythonWordCount") \ .getOrCreate() counts = spark.read.text(file_name).rdd.map(lambda r: r[0]) \ # this line is supposed to return the paths to each file .flatMap(return_contents_from_file) \ # here i am expecting to club all the contents of all files .flatMap(do_operation_on_each_line_of_all_files) # here i am expecting do an operation on each line of all files ``` This is throwing the error: > > line 323, in get\_return\_value py4j.protocol.Py4JError: An error > occurred while calling o25.**getnewargs**. Trace: py4j.Py4JException: > Method **getnewargs**([]) does not exist at > py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:318) > at > py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:326) > at py4j.Gateway.invoke(Gateway.java:272) at > py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132) > at py4j.commands.CallCommand.execute(CallCommand.java:79) at > py4j.GatewayConnection.run(GatewayConnection.java:214) at > java.lang.Thread.run(Thread.java:745) > > > Can someone please tell me what I am doing wrong and how I should proceed further. Thanks in advance.
Using `spark` inside `flatMap` or any transformation that occures on executors is not allowed (`spark` session is available on driver only). It is also not possible to create RDD of RDDs (see: [Is it possible to create nested RDDs in Apache Spark?](https://stackoverflow.com/questions/29760722/is-it-possible-to-create-nested-rdds-in-apache-spark)) But you can achieve this transformation in another way - read all content of `all_files.txt` into dataframe, use **local** `map` to make them dataframes and **local** `reduce` to union all, see example: ``` >>> filenames = spark.read.text('all_files.txt').collect() >>> dataframes = map(lambda r: spark.read.text(r[0]), filenames) >>> all_lines_df = reduce(lambda df1, df2: df1.unionAll(df2), dataframes) ```
80316
1. At least one lower case letter, 2. At least one upper case letter, 3. At least special character, 4. At least one number 5. At least 8 characters length problem is showing error at "/d" in regx pattern ``` private void txtpassword_Leave(object sender, EventArgs e) { Regex pattern = new Regex("/^(?=.*[a-z])(?=.*[A-Z])(?=.*/d)(?=.*[#$@!%&*?])[A-Za-z/d#$@!%&*?]{10,12}$/"); if (pattern.IsMatch(txtpassword.Text)) { MessageBox.Show("valid"); } else { MessageBox.Show("Invalid"); txtpassword.Focus(); } } ```
Try this instead : ``` ^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,}) ``` [Tests](https://regex101.com/r/3IHFOw/1)
80442
I have a location in my story, the design of which needs a reality check. **City Description:** > > As my ship cut across the waves a blurred grey smudge appeared in the distance, as the hours passed it became more distinct and it's true scope came into view. > > > As we neared the end of our voyage a great cliff of jagged granite rose hundreds of feet from the relentlessly pounding sea and spread as far as the eye could see in either direction. The tops of the tallest buildings shining brightly in the moonlight peered down from atop the cliff. The face of the cliff, littered with windows glowed like the eyes of fey forest creatures and large towers ascended at intervals striped like a barber pole apparently carved from the face of the cliff. > > > Directly before us a giant maw opened in the cliff the top jagged like the mouth of some vicious predator. On either side of the cliff massive braziers burned brightly in the night. > > > There is more to the poetic description but I think that is sufficient to set the feel for the place. **City Details:** * The city is built into, and on top of, a granite cliff. The cliff rises 500' (152 Meters) from the sea below. * The granite cliff extends perhaps a mile in either direction (this can be adjusted somewhat if it matters) and should extend at least 1500' (460 M) inland. * In the face of the cliff is a large cavern that can accommodate large two masted sailing ships. Tugs are used to tow the ships to docks within the cave. * Inside there are stairways and elevators (both for people and cargo) that lead up to the surface. * Inside the rock formation I am looking for enough space for approximately 1000 residents, each should be afforded 12'x 12' (.305 x .305 M) of floor space, dwellings are not all the same size. * Living spaces are reminiscent of Bag End from The Fellowship of the Ring, though scaled for a normal human to walk without doubling over (8' ceilings) The underground portion will also require space for cargo storage. * Atop the rock face is a city, where important structures are built from the excavated granite and lesser structures from both stone and wood from the surrounding forest. **Points of consideration for the reality check.** * Can this much granite exist in one place, are there real world examples? * Does the described amount of excavation seem possible or would it cause structural problems? (Faults can be set however structurally required) * Are there examples of dwellings carved into granite in the real world for the purpose of habitation? * Are there concerns with this setup that I have not considered?
Granite Massifs are common -------------------------- A granite block of the size you ask for is totally feasible. El Capitan in California is certainly taller. Getting the living spaces you want without explosives or magic is going to be sufficiently expensive to be impossible. Cutting stone by hand takes a long long time. From personal experience, with a hammer drill and modern drill bits, it took the better part of an hour to cut a single row of holes about 6" deep. Medieval miners with poor quality iron or steel will take days or weeks to cut the same set of holes. To excavate the amount of material described will take forever. Making granite "caves" is usually done artificially by cutting up the rock into blocks then forming it into buildings. As most caves are found in rock types that dissolve in water and granite does not, some other mechanism will need to be used to create the voids in the rock. Without a very secure bay to protect the cave mouth, no captain will risk their ship. The scene describes pounding surf indicating that the cliff face extends far below the water line. While the deep water will allow large ships to approach the cave mouth, and even enter, no one would dock their ship there. Depending on the shape of the cave and without a harbor, the waves in the cave could frequently be larger than the waves outside. Big waves on the open ocean aren't too bad. Big waves are really bad when your ship can be thrown against a cliff face, even if that face is in a cave. Compare paintings of the docking density between the Thames River in the 1800s vs Boston Harbor. The Thames is absolutely packed! Why? Because conditions on the Thames are very placid. The risk of one ship inadvertently running into another was low enough that the density of docked ships could increase. Boston harbor doesn't have those kind of conditions. Thus, to prevent accidents, boats are anchored much further away from each other. Ignoring the waves, the tides will put a limit on the maximum height of the ships that will fit in your cave. Assuming a normal earth-moon system, tides may vary by as much as 3 meters.
81015
I have an application which is developed in MVC .net. All the content in the application must be optimized for SEO. I am wondering if the content on the web page like (title, meta tags) are normally rendered as static context, Google can easily index that page. But if the site is developed in .net MVC where the main code dynamically loads from MVC how does Google indexes such pages for SEO and Ranking. Here is the code for my website. **A working static page**(without backend/dynamic content in MVC pure static HTML) ``` <!doctype html> <html> <head> <title>jQuery Child Filter Selectors</title> <meta name="Keywords" content="jquery child selectors, jquery first-child selector, jquery last-child,first-of-type,jquery-nth-child,"> <meta name="Description" content="Learn about all the jQuery child selectors with interactive live examples covering jquery first-selector, last-selector, jquery nth-selector and others "> </head> <body> <div class="main-wrapper"> <div class="wrapper"> <ul> <li><a href="../html/html-home.html">HTML</a></li> <li><a href="../css-tutorials/css-home.html">CSS</a></li> <li><a href="../javascript/javascript-home.html">Javascript</a></li> <li><a href="../jquery/jquery-home.html">jQuery</a></li> <li><a href="../references/web-references.html">Web References</a></li> <li><a href="../articles/articles-home.html">Articles</a></li> </ul> </div> <h1>jQuery Child Filter Selectors</h1> <h1>jQuery first-child Selector</h1> <div class="alert alert-info"> <p>jQuery <code>first-child</code> selector is used to select all the <code>HTML</code>elements which are the first child of their parent. </p> </div> <b style="font-size:20px;">Syntax</b> <textarea class="myTextareaCss"> $( ":first-child" ) </textarea> <div id="footer"> <div class="section section-standout section-slim"> <div class="container"> <div class="row row-gap-huge hidden-xs"></div> <h4>References</h4> <p class="caption"> <a href="../references/html-reference.html">HTML References</a> <br> <a href="../references/css-reference.html">CSS References</a> <br> <a href="../references/javascript-reference.html">JavaScript References</a> <br> <a href="../references/jquery-reference.html">jQuery References</a> <!-- end of the page --> </body> </html> ``` The above static HTML code perfectly indexed by Google. My question is if I convert the same code using MVC.net framework does Google index my page correctly. Here is my MVC code after conversion: **Note:** After converting into MVC all the (*head, body, title* tags will dynamically loaded) ``` @{ ViewBag.Title = " jQuery Child Filter Selectors"; } @section AdditionalMeta { <meta name="Keywords" content="jquery child selectors, jquery first-child selector, jquery last-child,first-of-type,jquery-nth-child,"> <meta name="Description" content="Learn about all the jQuery child selectors with interactive live examples covering jquery first-selector, last-selector, jquery nth-selector and others "> } <div class="main-wrapper"> <div class="wrapper"> <!-- Dynamically load the left menu --> @Html.Partial("~/Views/CSS/commonLeftMenu.cshtml") </div> <h1>jQuery Child Filter Selectors</h1> <h1>jQuery first-child Selector</h1> <div class="alert alert-info"> <p>jQuery <code>first-child</code> selector is used to select all the <code>HTML</code>elements which are the first child of their parent. </p> </div> <b style="font-size:20px;">Syntax</b> <textarea class="myTextareaCss"> $( ":first-child" ) </textarea> <!-- Dyntamically load the footer --> @Html.Partial("~/Views/CSS/commonRightMenu.cshtml") <!-- end of the page --> ``` Does the above MVC code correctly indexed by Google and other search engines if not what can I do for that to optimize my website which is of more than a 1000 web pages similar to the above.
Use like this: ``` @Override protected void onDestroy() { super.onDestroy(); asyncTask.cancel(true); } ```
81176
``` \documentclass{article} \usepackage{nicematrix} \begin{document} \begin{NiceTabular}{>{\arabic{iRow}}cc>{\alph{iRow}}cc}[first-row] \multicolumn{1}{c}{}\Block{1-2}{Name} && \Block{1-2}{Country} & \\ & George && France \\ & John && Hellas \\ & Paul && England \\ & Nick && USA \\ \end{NiceTabular} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/AFvDj.png)](https://i.stack.imgur.com/AFvDj.png) Questions 1. Is my code ok? 2. Is there a better code? (with nicematrix and without `\multicolumn` and first-row)
The second `NiceTabular` reproduces the first without using `\multicolumn` or `first-row`. [![a](https://i.stack.imgur.com/oh4pj.jpg)](https://i.stack.imgur.com/oh4pj.jpg) `\NRow` will output the row number decremented by 1 from the second row forward. `\ARow` does the same with alphabetical output. ``` \documentclass{article} \usepackage{nicematrix} \begin{document} \begin{NiceTabular}{>{\arabic{iRow}}cc>{\alph{iRow}}cc}[first-row] \multicolumn{1}{c}{}\Block{1-2}{Name} && \Block{1-2}{Country} & \\ & George && France \\ & John && Hellas \\ & Paul && England \\ & Nick && USA \\ \end{NiceTabular} \bigskip % *************************************************** added <<<<< \newcounter{iRowtmp} \newcommand{\NRow}{\ifnum\value{iRow} >1 \the\numexpr\value{iRow}-1\fi} \newcommand{\ARow}{\ifnum\value{iRow} >1 \setcounter{iRowtmp}{\the\numexpr\value{iRow}-1} \alph{iRowtmp}\fi} \begin{NiceTabular}{>{\NRow}cc>{\ARow}cc} \Block{1-2}{Name} & & \Block{1-2}{Country} & \\ & George& & France \\ & John & & Hellas \\ & Paul & & England \\ & Nick & & USA \\ \end{NiceTabular} \end{document} ``` **Interesting bit** (after @Alan Munn comment) : the `\ARow` command can be further simplified by suppressing the row number check as in ``` \newcommand{\ARow}{\setcounter{iRowtmp}{\the\numexpr\value{iRow}-1}\space\alph{iRowtmp}} ``` It will still work on the first row (where `\iRow-1=0`} because `\space\alph{<\iRow-1>}` will produce only the white space.
81206
i'm creating a link sharing that on bind() events of a specific textarea ( where i paste links ) it does an `$.post` ajax callback with a preview (in case of youtube or vimeo link). Basically, i would remove link into textarea each times that link is detected and preview is gotten. this is the function that does the callback : ``` $('#writer').bind('change keypress keyup keydown',function() { var value_= $('#writer').val(); $('#thumb-temp').hide(); $.post( 'checklink.php?', { string : value_ }, function(response) { $('.writer').prepend(response); $('#thumb-temp').show(); }).fail(function() { alert( "error" ) }) }); ``` and the page **checklink.php** that should remove the link ``` <? $link = $_POST['string']; $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/"; preg_match($reg_exUrl, $link, $url); $link = $url[0]; ?> <script>clearTextarea('<? echo $link ?>')</script> ``` and in the end the clearTextarea() function ``` function clearTextarea(url) { var _textarea = $('#writer'); var _curVal = _textarea.val(); var _curUrl = url; var _regex = new RegExp( _curUrl , 'g' ); var _newVal = _curVal.replace( _regex , '' ); _textarea.val( _newVal ); } ``` Now, apparentely, this should works but nothing happens, any ideas ? I do not understand where I'm wrong :(
I think this would be related to raw photo files, because DRIVE tries to [convert them to JPG](http://www.photographybay.com/2013/09/26/google-goes-raw-better-conversion-now-supports-over-70-cameras-look-out-adobe/) as is done in Google+, unless you specify convert=false. You should specify in your upload API to not convert that files. This second post says that it will allow you to preview the file [up to 25MB](https://support.google.com/drive/answer/2423485?hl=en), this size limitation could be related with your troubles. Maybe you could try to upload another photo with less than that size to ensure it's not this the limitation.
81923
I am trying to send an E-Mail using the gem 'mail' with Ruby 1.9.3. It contains an text/html and an text/plain part which should be embedded as alternative parts as well an attachment. This is my current code: ``` require 'mail' mail = Mail.new mail.delivery_method :sendmail mail.sender = "me@example.com" mail.to = "someguy@example.com" mail.subject = "Multipart Test" mail.content_type = "multipart/mixed" html_part = Mail::Part.new do content_type 'text/html; charset=UTF-8' body "<h1>HTML</h1>" end text_part = Mail::Part.new do body "TEXT" end mail.part :content_type => "multipart/alternative" do |p| p.html_part = html_part p.text_part = text_part end mail.add_file :filename => "file.txt", :content => "FILE" mail.deliver! ``` It results in an mail with working alternative parts but no attachment. I am using thunderbird 10.0.12 for testing. I already posted this on github, but unfortunately the posts don't make me smarter. <https://github.com/mikel/mail/issues/118#issuecomment-12276876>. Maybe somebody is able to understand the last post a bit better than me ;) Is somebody able to get this example working? Thanks, krissi
I managed to fix it like so: ```rb html_part = Mail::Part.new do content_type 'text/html; charset=UTF-8' body html end text_part = Mail::Part.new do body text end mail.part :content_type => "multipart/alternative" do |p| p.html_part = html_part p.text_part = text_part end mail.attachments['some.xml'] = {content: Base64.encode64(theXML), transfer_encoding: :base64} mail.attachments['some.pdf'] = thePDF mail.content_type = mail.content_type.gsub('alternative', 'mixed') mail.charset= 'UTF-8' mail.content_transfer_encoding = 'quoted-printable' ``` Not intuitive at all, but reading the [Pony](https://github.com/benprew/pony/blob/master/lib/pony.rb) source code kinda helped, as well as comparing a working .eml to whatever this gem was generating.
81997
Hey i have an array an I need to separate each value so it would be something like this ``` $arry = array(a,b,c,d,e,f) $point1 = (SELECT distance FROM Table WHERE Origin = a AND Destination = b); $point2 = (SELECT distance FROM Table WHERE Origin = b AND Destination = c); $point3 = (SELECT distance FROM Table WHERE Origin = c AND Destination = d); $point4 = (SELECT distance FROM Table WHERE Origin = d AND Destination = e); $point5 = (SELECT distance FROM Table WHERE Origin = e AND Destination = f); $point6 = (SELECT distance FROM Table WHERE Origin = f AND Destination = g); $point7 = (SELECT distance FROM Table WHERE Origin = g AND Destination = f); $total_trav = $point1+$point2+$point3+$point4+$point5+$point6+$point7 ```
Simple just use list(); ``` list($point1,$point2,$point3,$point4,$point5) = $arry; ``` Then do your query like so.... ``` $sql = "SELECT SUM(distance) FROM table WHERE (origin='$point1' AND destination='$point2') OR (origin='$point2' AND destination='$point3') OR (origin='$point3' AND destination='$point4') OR (origin='$point4' AND destination='$point5') ``` **EDIT** Ok based on what you need below in the comments, I worked up a simple solution for you.... ``` $arr = array("Vegas","Iowa","Utah","Washington"); //your array //First part of query string build... $sql = "SELECT SUM(distance) FROM table WHERE"; //Loop through the array...based on its # of contents for($i=0;$i<count($arr);$i++){ if(!empty($arr[$i+1])){ $sql.=" (origin='".$arr[$i]."' AND destination='".$arr[$i+1]."') OR";} } //Hack off the end bit, which contains an OR appended to the string... $sql = substr($sql, 0, -3); //$sql is now ready to be used in a query mysql_query($sql); ```