date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/21 | 2,163 | 7,725 | <issue_start>username_0: ---
Context
-------
---
I've been struggling with the following problem for the last few days and due to the very nature of a CDN and the manual review of each new rule, it takes me each time up to 4h to deploy a new rule.
As described in the following topic, I currently have my Angular application deployed to a **storage account** which has a single **blob container** called `cdn`
[](https://i.stack.imgur.com/WkBD1.png)
Within the **root** of this **blob container**, the whole `dist` folder from my angular project has been copied via my CI setup.
[](https://i.stack.imgur.com/Ucvpr.png)
The CDN profile has also been set up, to point at the `origin-path` called `/cdn`
[](https://i.stack.imgur.com/oFFZr.png)
---
Problem
-------
---
Unfortunately there is currently an ongoing [issue](https://feedback.azure.com/forums/217298-storage/suggestions/6417741-static-website-hosting-in-azure-blob-storage) that you can't directly access a default file.
1. What I would like is to redirect all incoming traffic from my Angular
application to the `index.html` file. This in order to satisfy the [routing
for Angular](https://angular.io/guide/router#set-the-base-href).
[](https://i.stack.imgur.com/g9KuQ.png)
2. Furthermore I would like to let any request for static files (e.g images)
through without any specific url rewritting.
I've seen various posts regarding this issue but none of the answer seem to cover my case or didn't in the deliver the expected result.
Currently I am using the **rules engines** feature of the **Azure CDN** from Verizon.
Regarding the patterns I used all the patterns mentioned in the [following article](https://blog.lifeishao.com/2017/05/24/serving-your-static-sites-with-azure-blob-and-cdn/), including which were mentioned in the comments.
I've also spent at least two days to find various other articles and stackoverflow articles but none of them worked for my case.
Furthermore I also created my own regex pattern but although they worked in my test environment, they would work once they were deployed to the CDN.
I usually ended up with one of the following results:
* Top level domain `https://myFancyWebsite.azureedge.net` wouldn't rewrite the url to the `index.html` and I would receive a http error `404`
* Top level domain would redirect to `index.html` but would stop working once I added a url path `https://myFancyWebsite.azureedge.net/login/callback` - once again a http error `404` as soon as I started using `/login/callback`
* Top level domain would rewrite the url to something like `https://myFancyWebsite.azureedge.net/cdn/cdn/cdn/cdn/cdn/cdn/cdn/cdn/cdn/cdn ....` in an http error `431`
The offical [documentation](https://learn.microsoft.com/en-us/azure/cdn/cdn-rules-engine-reference-features#url-rewrite) from Microsoft also didn't help in my case.
I am pretty sure I am not the first one who is deploying an Angular application to storage account and someone has run in the same issues as I have.
I am thankful for any information which points me in the right direction because at the moment I am definitely thinking about moving away from whole storage account deployment.
---
Update 1
--------
---
With the following `source` pattern `((?:[^\?]*/)?)($|\?.*)` which was also mentioned in the [article](https://blog.lifeishao.com/2017/05/24/serving-your-static-sites-with-azure-blob-and-cdn/) over here, I am able to handle at least the top level domain rewrite to the `index.html` file.
Unfortunately, I still need an additional pattern to redirect from `https://myFancyWebsite.azureedge.net/login/callback` to `https://myFancyWebsite.azureedge.net/index.html`
---
Update 2
--------
---
I am currently updating the regex pattern once or twice a day and once again it works on my test environment but stops working once I deploy it. I start to believe that Azure CDN is appending something to the URL after the top-level domain but I have no idea how to verify that.
<https://regex101.com/r/KK0jCN/23>
---
Update 3
--------
---
We are writting the year 3025 and I still have no clue why for example the following pattern isn't handling the url rewritting of the top domain.
<https://regex101.com/r/KK0jCN/25><issue_comment>username_1: For your requirement, I tested this issue on my side. Per my test, you could try to leverage the following URL Rewrite rule:
Source pattern: `(http[s]?://[^\?/#]+)(/(?!images)(?!scripts)[^\?#]*)?($|[\?#].*)`
Destination pattern: `$1/index.html$3`
**Note:** For loading other files (.ico,.txt,.js,.css,etc) correctly, you need to move them into new virtual directories instead of the root of your blob container. For example, you could move image files into `cdn\images` and move JavaScript files into `cdn\scripts`, then the regular expression would ignore the related virtual folders.
Additionally, you could use Azure Web App to host your static website and choose the Free pricing tier or the Shared tier which would cost you $9.49 per month per instance. Details you could follow [Pricing calculator](https://azure.microsoft.com/en-us/pricing/calculator/?service=app-service).
---
**UPDATE:**
Based on Justin's answer, I checked this issue and found that for Blob storage origin type, the `Source` and `Destination` under URL Rewrite are talking about the request against the blob storage endpoint. So we need to set regular expression against the request path and query string for the blob endpoint.
username_2 has provided the answer for rewrite everything to `cdn/index.html`. Based on your scenario, I have tested my rule and it could work on my side.
[](https://i.stack.imgur.com/HEjmj.png)
**TEST:**
[](https://i.stack.imgur.com/sGcHt.png)
[](https://i.stack.imgur.com/AMDvi.png)
Upvotes: 1 <issue_comment>username_2: * Add a new rule with condition **If Always**
* You will need to add a new Feature for each endpoint.
* For the Pattern, enter `[^?.]*(\?.*)?$`. This pattern catches URL paths with `.` in them, but doesn't care whether or not it's in the query string.
* For the Path, enter `origin_path/document.ext`. This is the tricky part. The Path is relative to the origin root. For instance, if your CDN endpoint's origin path is `/origin_path` and you want to redirect to `index.html`, you would enter `origin_path/index.html`. This will always be the case if your CDN is backed by an Azure Storage Account and the origin points to a container.
* Click Add to add your rule, wait N hours, and you're good to go.
Upvotes: 5 [selected_answer]<issue_comment>username_3: Just to add to this. If you're using Azure Verizon Premium CDN and your Azure endpoint is using an origin path. The origin path is a part of the rewrite. For example, lets say you're pointing to a versioned folder inside your `$web` blob.
[](https://i.stack.imgur.com/TQlXW.png)
So if in the above picture "Origin path" is `2.1.2` and your current static application is in `$web/2.1.2/`, then your rewrite for the CDN would be Source: `///(.\*)\/[^?.]\*(\?.\*)?$` --> Destination: `///$1/index.html`
[](https://i.stack.imgur.com/4Pxqe.jpg)
Upvotes: -1 |
2018/03/21 | 961 | 3,503 | <issue_start>username_0: I have long int number and I want to encode it to QRCode with exactly numeric type of encoding. Now I use CIFilter(name: "CIQRCodeGenerator"), but in this case I don't know how to choose type of encoding. Is there a way to create QR code with chosen type of encoding?<issue_comment>username_1: For your requirement, I tested this issue on my side. Per my test, you could try to leverage the following URL Rewrite rule:
Source pattern: `(http[s]?://[^\?/#]+)(/(?!images)(?!scripts)[^\?#]*)?($|[\?#].*)`
Destination pattern: `$1/index.html$3`
**Note:** For loading other files (.ico,.txt,.js,.css,etc) correctly, you need to move them into new virtual directories instead of the root of your blob container. For example, you could move image files into `cdn\images` and move JavaScript files into `cdn\scripts`, then the regular expression would ignore the related virtual folders.
Additionally, you could use Azure Web App to host your static website and choose the Free pricing tier or the Shared tier which would cost you $9.49 per month per instance. Details you could follow [Pricing calculator](https://azure.microsoft.com/en-us/pricing/calculator/?service=app-service).
---
**UPDATE:**
Based on Justin's answer, I checked this issue and found that for Blob storage origin type, the `Source` and `Destination` under URL Rewrite are talking about the request against the blob storage endpoint. So we need to set regular expression against the request path and query string for the blob endpoint.
username_2 has provided the answer for rewrite everything to `cdn/index.html`. Based on your scenario, I have tested my rule and it could work on my side.
[](https://i.stack.imgur.com/HEjmj.png)
**TEST:**
[](https://i.stack.imgur.com/sGcHt.png)
[](https://i.stack.imgur.com/AMDvi.png)
Upvotes: 1 <issue_comment>username_2: * Add a new rule with condition **If Always**
* You will need to add a new Feature for each endpoint.
* For the Pattern, enter `[^?.]*(\?.*)?$`. This pattern catches URL paths with `.` in them, but doesn't care whether or not it's in the query string.
* For the Path, enter `origin_path/document.ext`. This is the tricky part. The Path is relative to the origin root. For instance, if your CDN endpoint's origin path is `/origin_path` and you want to redirect to `index.html`, you would enter `origin_path/index.html`. This will always be the case if your CDN is backed by an Azure Storage Account and the origin points to a container.
* Click Add to add your rule, wait N hours, and you're good to go.
Upvotes: 5 [selected_answer]<issue_comment>username_3: Just to add to this. If you're using Azure Verizon Premium CDN and your Azure endpoint is using an origin path. The origin path is a part of the rewrite. For example, lets say you're pointing to a versioned folder inside your `$web` blob.
[](https://i.stack.imgur.com/TQlXW.png)
So if in the above picture "Origin path" is `2.1.2` and your current static application is in `$web/2.1.2/`, then your rewrite for the CDN would be Source: `///(.\*)\/[^?.]\*(\?.\*)?$` --> Destination: `///$1/index.html`
[](https://i.stack.imgur.com/4Pxqe.jpg)
Upvotes: -1 |
2018/03/21 | 476 | 1,825 | <issue_start>username_0: In my modx revo project I have list of links to articles, if I click on the link corresponding article will shown below. Those link can be styled, and that one which referring to displayed article needs to be styled difertly. So I need to add specific html class to that link, like
```html
1st article
1nd article
3rd article
4th article
```
Every article is modx resource content, and links list is part of template where it's opened.
Is there a way I can do it?<issue_comment>username_1: The easiest way would be to use an extra such as Wayfinder to build your menu which automatically handles adding the "active" class based on what resource you are viewing.
Here's a Wayfinder example from the docs, which gets 1 depth of pages under the root of the site and automatically adds the class "active" to the page you are viewing.
`[[Wayfinder? &startId=`0`&level=`1`]]`
By default, it outputs a unordered list of all items. This can then be customized to fit your site using the extra's parameters, specifically outerTpl and rowTpl (more info on the docs page for Wayfinder: <https://docs.modx.com/extras/revo/wayfinder> )
Upvotes: 2 [selected_answer]<issue_comment>username_2: The simple way would be to generate your navigation using an extra such as [pdoMenu](https://docs.modx.pro/en/components/pdotools/snippets/pdomenu) (available in the pdoTools package).
Use the following snippet call: `[[pdoMenu? &parents=`0` &level=`1`]]`
That will generate a nav according to the [default templates](https://docs.modx.pro/en/components/pdotools/snippets/pdomenu). The active li element will have the class `.active` so you can style it accordingly.
pdoTools also gives you a ton of other useful snippets which you can find [here](https://docs.modx.pro/en/components/pdotools/).
Upvotes: 2 |
2018/03/21 | 657 | 2,379 | <issue_start>username_0: I am using angular 5 with ionic 3.
I have one interface:
```
export interface IAny {
getDataSource: Observable;
}
```
Components which implements this interface has method:
```
getDataSource () {
return Observable.of(['Item1', 'Item2', 'Item3'] as any)
};
```
This method should return different types of dataSources, some time it will be simple array of string , some time array of objects, some time the simple object.
Is it possible at all ?<issue_comment>username_1: You have several way of doing this :
```
return Observable.of(['Item1', 'Item2', 'Item3'])
return Observable.of(['Item1', 'Item2', 'Item3']) as any
return Observable.of(['Item1', 'Item2', 'Item3']) as Observable // For code completion
```
All should work. You can just replace `any` with your type.
By the way, your interface should be this
```
export interface IAny {
getDataSource(): Observable;
}
```
You declare a function, not a variable.
Better, as [@nicowernli](https://stackoverflow.com/users/1027936/nicowernli) suggested, if you want to type your returns on the fly, declare your interface and your functions with generic types :
```
export interface IAny {
getDataSource(): Observable;
}
getDataSource() {
return Observable.of(['Item1', 'Item2', 'Item3'] as any)
};
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: It is possible, but you don't need to cast the array to `any`.
If you don't, in your example, your function is of type `() => Observable`, a type compatible with `() => Observable`, which is the type of the method defined in the interface.
I mean, if you have:
```
let a: () => Observable;
let b: () => Observable;
```
Then you can do:
```
a = b;
```
Because `any` is compatible with any type in TypeScript.
Upvotes: 2 <issue_comment>username_3: If you are like me and want to avoid the 'any' type as much as possible (and in this case your any-castings) you could use a Type Alias especially for your value.
It could look something like this:
```
// Just add your desired types that are possible return values
type DataSourceType = Array | Array | object;
```
You find everything about Type Aliases at the [TS Docs](http://www.typescriptlang.org/docs/handbook/advanced-types.html)
You could even take it one step further and replace the generic object type with your custom type.
Upvotes: 1 |
2018/03/21 | 700 | 1,571 | <issue_start>username_0: I need help
From a list I would like to get the addition of characters like the example below:
Start:
```
1
1
13
5
14
4
1
5
12
7
8
9
4
18
3
20
11
17
13
```
===============================================
Final results :
```
9001
9001
9013
9005
9014
9004
9001
9005
9012
9007
9008
9009
9004
9018
9003
9020
9011
9017
9013
```
this command does not work:
```
sed "s/^/9000/g" file.txt
```<issue_comment>username_1: You can do it like this:
```
for num in 1 1 13 5 14 4 1 5 12 7 8 9 4 18 3 20 11 17; do echo "$(($num + 9000))"; done
```
If you also have numbers in the list, which you don't want to process, because they are already in the 90XX format you can throw in an if statement:
```
for num in 1 1 13 5 14 4 1 5 12 7 8 9 4 18 3 20 11 17 9005; do if [ $(($num)) -le 9000 ]; then echo "$(($num + 9000))"; else echo $num; fi; done
```
[For loop in bash](https://www.cyberciti.biz/faq/bash-for-loop/) - for; do; done;
Bash arithmetic expression to add the numbers - [$((EXPR))](http://tldp.org/LDP/abs/html/arithexp.html)
Upvotes: 1 <issue_comment>username_2: This should work for you.
```
for num in `cat file.txt`; do if [ $num -le 9000 ]; then echo "$(($num + 9000))"; else echo $num; fi; done
```
Upvotes: 1 <issue_comment>username_3: This might work for you (GNU sed):
```
sed -r 's/^/0000/;s/^0*(.{3})$/9\1/' file
```
Prepend zeroes to the front of the number. Prepend a `9` and remove excess zeroes.
Upvotes: 2 <issue_comment>username_4: You can try (GNU sed):
```
sed 's/.*/echo $((9000+&))/e' infile
```
Upvotes: 1 |
2018/03/21 | 535 | 1,887 | <issue_start>username_0: Can anybody help me to find a solution how to make this code work on my Wix-Site:
```
[Click here to opt-out of Google Analytics](javascript:gaOptout())
```
I have this code from Google itself (At the bottom of the page see "example"):
<https://developers.google.com/analytics/devguides/collection/gajs/>
Here is a Screenshot of this code from the google website:
[Google Analytics Opt Out Code](https://i.stack.imgur.com/XKDJo.jpg)
I tried this:
```
$w("#text1").html = "[Click here to opt-out of Google Analytics](javascript:gaOptout())";
```
But I was told that in Wix it is not possible to add events to a-tag elements in text element. Here you will find the little discussion that I had on Wix Forum:
<https://www.wix.com/code/home/forum/questions-answers/how-to-link-text-to-a-url-using-w-link>
I also asked on Reddit, Facebook and WixSupport. But nobody could help me with that issue.<issue_comment>username_1: You cannot access the HTML directly via Wix Code. Wix Code exposes a dedicated API for you to manipulate their controllers and elements on screen but not further under the hood.
You can use `wix-fetch` to call external API calls to **google analytics**
(if they have an API to `opt-out`, not familiar enough to say here is the post)
anyway, your code in **Wix** should be something like this:
(as example API taken from their [docs](https://developers.google.com/analytics/devguides/reporting/core/v4/basics))
```js
import {fetch} from 'wix-data'
fetch('https://analyticsreporting.googleapis.com/v4/...', options) // returns a Promise
```
Upvotes: 0 <issue_comment>username_2: You might want to take a look at the new wix feature called "tracking and analytics". It lets you embed custom scripts in your html's body, header, or footer.
<https://support.wix.com/en/article/about-tracking-tools-analytics>
Upvotes: 1 |
2018/03/21 | 773 | 3,176 | <issue_start>username_0: I use the Code A to create a RecyclerView with radio button based some searched sample code from website.
1、I don't know if these code is good, is there a better way to implement radio button in RecyclerView?
2、How can I set the first radio button checked default when I start the APP? You know that none of radio button is checked when I start the APP.
**Code A**
```
class CustomAdapter (val backupItemList: List) : RecyclerView.Adapter() {
private var mSelectedItem = -1
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomAdapter.ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.item\_recyclerview, parent, false)
return ViewHolder(v)
}
fun getSelectedItem():Int{
return mSelectedItem
}
override fun onBindViewHolder(holder: CustomAdapter.ViewHolder, position: Int) {
holder.bindItems(backupItemList[position])
holder.itemView.radioButton.setChecked(position == mSelectedItem);
}
override fun getItemCount(): Int {
return backupItemList.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindItems(aMSetting: MSetting) {
itemView.radioButton.tag=aMSetting.\_id
itemView.textViewUsername.text=aMSetting.createdDate.toString()
itemView.textViewAddress.text=aMSetting.description
itemView.radioButton.setOnClickListener {
mSelectedItem=getAdapterPosition()
notifyDataSetChanged();
}
}
}
}
```
**XML File**
```
xml version="1.0" encoding="utf-8"?
```<issue_comment>username_1: If you want to set the first `RadioButton` in your list to be true, you can check the adapterPosition and if it is 0 (i.e. first item) set it to true.
**For example:**
```
class CustomAdapter
{
var mSelectedItem = 0
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindItems(aMSetting: MSetting) {
....
if(adapterPosition == mSelectedItem)
itemView.radioButton.checked = true
else
itemView.radioButton.checked = false
}
}
}
```
Upvotes: 1 <issue_comment>username_2: ```
private var mSelectedItem = -1
```
...
```
override fun onBindViewHolder(holder: CustomAdapter.ViewHolder, position: Int) {
holder.bindItems(backupItemList[position], position, mSelectedItem)
}
```
...
```
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindItems(aMSetting: MSetting, position: Int, selectedPosition: Int) {
itemView.radioButton.tag=aMSetting._id
itemView.textViewUsername.text=aMSetting.createdDate.toString()
itemView.textViewAddress.text=aMSetting.description
if ((selectedPosition == -1 && position == 0))
itemView.radioButton.setChecked(true)
else
if (selectedPosition == position)
itemView.radioButton.setChecked(true)
else
itemView.radioButton.setChecked(false)
itemView.radioButton.setOnClickListener {
mSelectedItem=getAdapterPosition()
notifyDataSetChanged()
}
}
```
}
Upvotes: 4 [selected_answer] |
2018/03/21 | 592 | 1,925 | <issue_start>username_0: I have an list of objects:
```
[class RetailerItemVariant {
sku: 008884303996
isAvailable: true
price: 70.0
}, class RetailerItemVariant {
sku: 008884304030
isAvailable: true
price: 40.0
},
...
```
What's the best way to extract an array of the SKU's in Java 8? e.g.:
```
["008884303996", "008884304030", ...]
```
Im new to Java and this is very easy in Javascript using the map() function but I haven't been able to find a similarly simple way of doing it in Java...<issue_comment>username_1: Try with stream java 8:
```
List listSku = list.stream().map(r->r.getSku())
.collect(Collectors.toList())
```
Upvotes: 2 <issue_comment>username_2: Also in Java 8 there are `map` you can use :
```
List listSku = listRetailerItemVariant.stream()
.map(RetailerItemVariant::getSku)
.collect(toList());
```
Upvotes: 2 <issue_comment>username_3: Since you use Java 8, the `stream api` can help you here:
```
List skus = itemList.stream()
.map(Item::getSku)
.collect(Collectors.toList());
```
Upvotes: 5 [selected_answer]<issue_comment>username_4: It varies from your *start collection* and your *end structure*, but your basic code should look like this:
```
mylist
.stream()
.map(variant -> variant.getSku())
.collect(Collectors.toCollection(ArrayList::new)))
```
As start structure, if you use Arrays instead of collections move from `myList.stream` to `Stream.of(variantArray).map()`.
And as for your end structure, adjust if instead of an `ArrayList::new` you want a HashSet (`HashSet::new`) or a linked list (`LinkedList::new`)
and if you have many, many item variants and you'd like to collect their Skus fast and in any order, consider *parallel stream processing* by adding `parallel()` to the `stream()` function:
```
mylist
.stream()
.parallel() // for parallel processing
.map(variant -> variant.getSku())
```
Upvotes: 1 |
2018/03/21 | 1,160 | 4,782 | <issue_start>username_0: I would like my users to be able to delete their own user account. I made a `SecurityController` where there is my 3 functions `login`, `logout` and `deleteUser`. When I delete the current user in database this error appears :
>
> You cannot refresh a user from the EntityUserProvider that does not contain an identifier. The user object has to be serialized with its own identifier mapped by Doctrine.
>
>
>
When I delete another user, it works correctly because he's not connected.
Do I have to serialize the User and pass it through a Service, logout the user then remove it in a Service? Or can I clear the PHP session in the controller but I don't know how to do it with [symfony4](/questions/tagged/symfony4 "show questions tagged 'symfony4'") I think it changed since version 4.
```
php
namespace App\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;
use App\Entity\User;
use App\Form\UserType;
class SecurityController extends Controller
{
/**
* @Route("/createAdmin", name="create_admin")
*/
public function createAdminUser(Request $request, UserPasswordEncoderInterface $passwordEncoder)
{
$usersRepo = $this-getDoctrine()->getRepository(User::class);
$uCount = $usersRepo->countAllUsers();
if ($uCount == 0)
{
$user = new User();
$form = $this->createForm(UserType::class, $user, array(
'is_fresh_install' => true,
));
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// Encode the password
$password = $passwordEncoder->encodePassword($user, $user->getPlainPassword());
$user->setPassword($password);
// save the User
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
// Do what you want here before redirecting the user
return $this->redirectToRoute('login');
}
return $this->render('security/register_admin_user.html.twig', array(
'form' => $form->createView(),
));
} else {
if ($this->getUser())
{
return $this->redirectToRoute('user_account');
} else {
return $this->redirectToRoute('login');
}
}
}
/**
* @Route("/login", name="login")
*/
public function login(Request $request, AuthenticationUtils $authUtils)
{
$usersRepo = $this->getDoctrine()->getRepository(User::class);
$uCount = $usersRepo->countAllUsers();
if ($uCount == 0)
{
return $this->redirectToRoute('create_admin');
} else {
$error = $authUtils->getLastAuthenticationError();
$lastUsername = $authUtils->getLastUsername();
return $this->render('security/login.html.twig', array(
'last_username' => $lastUsername,
'error' => $error,
));
}
}
/**
* @Route("/logout", name="logout")
*/
public function logout()
{
}
/**
* @Route("/delete_user/{id}", name="delete_user")
*/
public function deleteUser($id)
{
$em = $this->getDoctrine()->getManager();
$usrRepo = $em->getRepository(User::class);
$user = $usrRepo->find($id);
$em->remove($user);
$em->flush();
return $this->redirectToRoute('user_registration');
}
}
```<issue_comment>username_1: I think you have to serialize the User and pass it through a service.Just check with the previous versions,you will find out the problem.
Upvotes: 0 <issue_comment>username_2: **SOLUTION :**
You have to clear the Session before deleting user entry in DB with this method:
```
php
use Symfony\Component\HttpFoundation\Session\Session;
// In your deleteUser function...
$currentUserId = $this-getUser()->getId();
if ($currentUserId == $id)
{
$session = $this->get('session');
$session = new Session();
$session->invalidate();
}
```
I don't know why `$this->get('session')->invalidate();` doesn't work directly... if someone knows :)
Upvotes: 4 [selected_answer]<issue_comment>username_3: I find it also a good solution to do this what is an accepted answer but you can also simply redirect the user to the logout route.
This has worked for me without any problem in Symfony 4.4
Upvotes: 1 |
2018/03/21 | 607 | 2,128 | <issue_start>username_0: I have some records like below:
```
ID Val Amount
1 0 3
2 0 3
3 0 4
4 1 2
5 1 3
6 2 3
7 2 4
```
I want to group this data by the column Val and get the sum(amount), but do not group the ones with Val = 0.
The result set I need is like below:
```
Val Amount
0 3
0 3
0 4
1 5
2 7
```
I did it by two ways, but none seem to be the best way:
First one is by using unions, like, first having the ones with Val = 0, then grouping the ones with Val <> 0 and unioning the two result sets.
Second one is a little bit better. Let's call the data we have is in the table @Table:
```
WITH g AS
(
SELECT Val, Amount, CASE WHEN Val = '0' then Val + ID
else Val END A FROM @table
)
SELECT CASE WHEN A LIKE '0%' THEN 0 ELSE A END AS A, SUM(Amount)
FROM g
GROUP BY A
```
This also works, but being have to concatenate with the ID column (or raw\_number) and than using a left function to remove it is not a best practice.
So I'm looking for a better approach, both looking better and performing better as well.
I work on SQL Server 2008, but I'm open to any solutions which require newer versions.<issue_comment>username_1: I think you have to serialize the User and pass it through a service.Just check with the previous versions,you will find out the problem.
Upvotes: 0 <issue_comment>username_2: **SOLUTION :**
You have to clear the Session before deleting user entry in DB with this method:
```
php
use Symfony\Component\HttpFoundation\Session\Session;
// In your deleteUser function...
$currentUserId = $this-getUser()->getId();
if ($currentUserId == $id)
{
$session = $this->get('session');
$session = new Session();
$session->invalidate();
}
```
I don't know why `$this->get('session')->invalidate();` doesn't work directly... if someone knows :)
Upvotes: 4 [selected_answer]<issue_comment>username_3: I find it also a good solution to do this what is an accepted answer but you can also simply redirect the user to the logout route.
This has worked for me without any problem in Symfony 4.4
Upvotes: 1 |
2018/03/21 | 758 | 2,579 | <issue_start>username_0: I'm trying to get this to work:
I've got string variable in a file called `test.js`. Depending on some values the file is created by a php script and it says something like: `var test = 'up'` or: var `test = 'down'`.
Now, I would like display a certain image on my website depending on the value of `var test`. So in my html code I add this to the header:
```
```
Then in the body I write:
```
function Test(){
if (test == 'up'){
document.getElementById("test").src = '/img/arrows/arrow\_up.png';
}
else if (test == 'down'){
document.getElementById("test").src = '/img/arrows/arrow\_down.png';
}
else {
document.getElementById("test").src = '/img/arrows/arrow\_neutral.png';
}
}
```
And I add in the image with:
```
![]()
```
However, nothing is displayed on the page. Can someone help me out?<issue_comment>username_1: You have to call `Test()` somewhere, the code below executes it, when the page is fully loaded, so the other `.js` file has executed(`test` has been set) and the `![]()` is on the page.
```js
var test = 'down';
function Test() {
if (test == 'up') {
document.getElementById("test").src = '/img/arrows/arrow_up.png';
} else if (test == 'down') {
document.getElementById("test").src = '/img/arrows/arrow_down.png';
} else {
document.getElementById("test").src = '/img/arrows/arrow_neutral.png';
}
}
window.onload = function() {
Test()
};
```
```html
![]()
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: First of all, try to put manually a src to see if the src is correct :
```

```
If it works, you should call your Test() function somewhere :
```
window.onload = function() {
Test();
};
```
To make simplier, you can use JQuery (not obligatory) :
You should add jquery reference to your html page (depending on your scripts folder, the link can change) :
```
```
And you can change your Test() methode on this :
```
function Test(){
debugger;
if (test == 'up'){
$("#test").attr("src", '/img/arrows/arrow_up.png');
}
else if (test == 'down'){
$("#test").attr("src", '/img/arrows/arrow_down.png');
}
else {
$("#test").attr("src", '/img/arrows/arrow_neutral.png');
}
}
```
Finally, to check if your test parameter is correct, you can put a debugger in order to debug your code in any browser.
If you open the developper tools of your browser, (by pressing on F12 on the browser) you can debug your code. The code will hit the debugger keyword.
Upvotes: 0 |
2018/03/21 | 803 | 3,033 | <issue_start>username_0: I am very new to the idea of `kubernetes`.
I found some good tutorials online to get my `kubernetes` cluster up & running.
Right Now I want to add a `kubernetes` dashboard to my cluster so that it would be easy and good to have a page where I can watch how my pods and node's react (even do I'm more of a CLI guy, some GUI is not bad).
I've downloaded the dashboard pod and it's up and running. Because the kubernetes cluster is running on a Raspberry Pi cluster I've set up a NodePort to access it from outside my cluster. But I've come to some problems where I can't find any problems too online.
1. In my Linux host machine I can access the kubernetes dashboard but somehow in my Linux machine, my browsers won't add the cert exception.
2. Some people online are convinced that NodePort is not safe enough. So I've done some research on other possibilities. I am very interested in the ingress controller to connect my dashboard. But I didn't find any good and full documentation how to set up an ingress controller (and more importantly what is happening, cause there are a lot of yaml files online and they say just run this but i have no clue what he is doing).
Can someone direct me to the right documentation/tutorial / or give me any help for my Kube dashboard?<issue_comment>username_1: You have to call `Test()` somewhere, the code below executes it, when the page is fully loaded, so the other `.js` file has executed(`test` has been set) and the `![]()` is on the page.
```js
var test = 'down';
function Test() {
if (test == 'up') {
document.getElementById("test").src = '/img/arrows/arrow_up.png';
} else if (test == 'down') {
document.getElementById("test").src = '/img/arrows/arrow_down.png';
} else {
document.getElementById("test").src = '/img/arrows/arrow_neutral.png';
}
}
window.onload = function() {
Test()
};
```
```html
![]()
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: First of all, try to put manually a src to see if the src is correct :
```

```
If it works, you should call your Test() function somewhere :
```
window.onload = function() {
Test();
};
```
To make simplier, you can use JQuery (not obligatory) :
You should add jquery reference to your html page (depending on your scripts folder, the link can change) :
```
```
And you can change your Test() methode on this :
```
function Test(){
debugger;
if (test == 'up'){
$("#test").attr("src", '/img/arrows/arrow_up.png');
}
else if (test == 'down'){
$("#test").attr("src", '/img/arrows/arrow_down.png');
}
else {
$("#test").attr("src", '/img/arrows/arrow_neutral.png');
}
}
```
Finally, to check if your test parameter is correct, you can put a debugger in order to debug your code in any browser.
If you open the developper tools of your browser, (by pressing on F12 on the browser) you can debug your code. The code will hit the debugger keyword.
Upvotes: 0 |
2018/03/21 | 497 | 1,745 | <issue_start>username_0: What is the difference between this(var) and this.var in JAVA.?
```
public class Clock {
private long time = 0;
private Clock(long time) {
this.time = time;
}
public Clock(long time, long timeOffset) {
this(time);
this.time += timeOffset;
}
public static Clock newClock() {
return new Clock(System.currentTimeMillis());
}
}
```<issue_comment>username_1: The first one (`this(var)`) calls the constructor with the `var` as parameter, while the second one simply references the `var` property within the object.
Upvotes: 2 <issue_comment>username_2: Given the class
```
public class Clock
{
private long time = 0;
public Clock(long time)
{
...
}
}
```
you use
* `this(x)` to call the constructor with the parameter `x`. This is called [constructor chaining](https://beginnersbook.com/2013/12/java-constructor-chaining-with-example/) and you can only call `this()` from a constructor, where it has to be the first statement. Contructors may not call themselves through constructor chaining.
* and you use `this.time = x` to set the member called `time` to the value of `x`. `this` indicates the scope of `time`, e.g. if you are in a method with a local variable `time`, using `time` will get the *closest* scope from the method, which is the local one. If you want the instance scope, you use `this.time`.
---
For further reading, see [Java Language Specs - 8.8.7 Constructor Body](https://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.8.7) and [Java Language Specs - 6.3 Scope of a declaration](https://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.3) as well as the following sections.
Upvotes: 2 |
2018/03/21 | 1,715 | 5,445 | <issue_start>username_0: I'm trying to implement the following API :
```
geojson::position_t<> point_1{ 10, 12 };
geojson::position_t<> point_2( 11, 13 );
geojson::position_t<> point_3(std::pair(12, 14));
geojson::position\_t<> line\_1{
geojson::position\_t<>{ 100, 120 },
geojson::position\_t<>{ 110, 130 } };
geojson::position\_t<> poly\_1{
{ geojson::position\_t<>{ 100, 120 }, geojson::position\_t<>{ 110, 130 }},
{ geojson::position\_t<>{ 101, 121 }, geojson::position\_t<>{ 111, 131 }} };
```
The idea is to have **position\_t<>** template class with the following properties :
* have some internal `value_type` identifying whether it is point or
line
* have constructors and use SFINAE to identify if a point-type or
line-type can be created based on passed parameters to ctor
* have method `value_type get() const {...}` returning point or line type
depending whether point or line ctor was invoked
My first approach was to use boost::variant but I'm stuck how to get `value_type` and implement `get()` method.
The second attempt was to use partial template specialization. But so far, I didn't succeed with it.[wandbox example](https://wandbox.org/permlink/tOl5Mgiey9cCiS7G)
Could somebody suggest approach how to achive required API ?<issue_comment>username_1: Here are two optional solutions:
The first one uses standard polymorphism, it uses a base class `GraphicBase`.
The second approach is to use std::variant to keep the objects. If used that, you can remove the base class and virtual functions. As read from your comment, you see type deduction rules as a solution. Yes, my example work that way!
It has some pro and cons for vtable polymorphism versus tagged union as std::variant. Both is possible!
A remark on:
>
> have some internal value\_type identifying whether it is point or line
>
>
>
You do not need some additional identifier, because the variant itself contains already that type tag. A variant is simply a union and a additional data entry which keeps track of the actual assigned type. Exactly what you want! You can use these tag with `std::visit` to call any function which the corresponding type passed to the function object you pass. ( In my example I use a generic lambda to make dispatching quite easy.
Hint:
Don't think about SFINAE if a simple overload or a specialization is possible!
```
class GraphicBase
{
public:
virtual void Print()=0;
// for using with vtable polymorphism
GraphicBase* Get() { return this; }
};
class Point: public GraphicBase
{
public:
Point( int, int ){}
void Print() override { std::cout << "Point" << std::endl; }
void PrintNonVirtual() { std::cout << "Point" << std::endl; }
};
class Line: public GraphicBase
{
public:
Line( Point, Point ){}
void Print() override { std::cout << "Line" << std::endl; }
void PrintNonVirtual() { std::cout << "Line" << std::endl; }
};
template < typename T >
class Graphics: public T
{
public:
using T::T;
// for using with variants
T GetNonVirtual() { return static_cast(\*this);}
};
Graphics( int, int ) -> Graphics;
Graphics( Point, Point ) -> Graphics;
int main()
{
Graphics p1(1,1);
Graphics l1({1,2},{3,4});
// using vtable polymorphism
std::vector v;
v.push\_back( &p1 );
v.push\_back( &l1 );
for ( auto el: v ) el->Print();
// using the Get() to get the base pointer
GraphicBase\* ptr;
ptr = p1.Get();
ptr->Print();
ptr = l1.Get();
ptr->Print();
// or using variants:
using VT = std::variant< Point, Line >;
std::vector var;
var.push\_back( p1 );
var.push\_back( l1 );
for ( auto& el: var )
{
std::visit( []( auto& v ){ v.PrintNonVirtual(); }, el );
}
// here we get a copy of the object ( references not allowed in variants! )
VT va1 = p1.GetNonVirtual();
VT va2 = p1.GetNonVirtual();
std::visit( []( auto& v ){ v.PrintNonVirtual(); }, va1 );
std::visit( []( auto& v ){ v.PrintNonVirtual(); }, va2 );
}
```
Upvotes: 1 <issue_comment>username_2: In C++17, you may use deduced guide, so you have both `position_t` and `position_t` and according to parameter constructor, choose the correct one.
Something like:
```
class Point
{
public:
int x;
int y;
};
class Line
{
public:
Point start;
Point end;
};
template class position\_t;
template <>
class position\_t
{
public:
position\_t(int x, int y) : point{x, y} {}
position\_t(const std::pair& p) : point{p.first, p.second} {}
const Point& get() const { return point; }
private:
Point point;
};
template <>
class position\_t
{
public:
position\_t(const position\_t& start,
const position\_t& end)
: line{start.get(), end.get()}
{}
const Line& get() const { return line; }
private:
Line line;
};
```
And then the deduction guide
```
position_t(int, int) -> position_t;
position\_t(std::pair) -> position\_t;
position\_t(const position\_t&, const position\_t&) -> position\_t;
```
So:
```
geojson::position_t point_1{ 10, 12 }; // geojson::position_t
geojson::position\_t point\_2( 11, 13 ); // geojson::position\_t
geojson::position\_t point\_3(std::pair(12, 14)); // geojson::position\_t
geojson::position\_t line\_1{ // geojson::position\_t
geojson::position\_t{ 100, 120 }, // geojson::position\_t
geojson::position\_t{ 110, 130 } }; // geojson::position\_t
```
[Demo](http://coliru.stacked-crooked.com/a/2881ed01948681be)
Upvotes: 3 [selected_answer] |
2018/03/21 | 1,741 | 4,270 | <issue_start>username_0: I have 2 tables, 01 is current status and 01 is finish status.
I want to calculate time difference of 2 rows that have the same PO\_NO,MANAGEMENT\_NO,PROCESS\_NAME .
Each PROCESS\_NAME has the STATUS (Start/Finish)
```
ID INDEXNO PO_NO ITEM_CD MANAGEMENT_NO SEQ PROCESS_NAME STATUS Time_Occurrence TimeDiff (Minute)
43 126690 GV12762 332393961 616244 6 RFID Start 17-03-18 13:28 NULL
44 126690 GV12762 332393961 616244 6 RFID Finish 17-03-18 13:29 0
49 141646 GV14859 7E7060100 619005 2 Imprint Start 19-03-18 13:23 NULL
50 141646 GV14859 7E7060100 619005 2 Imprint Finish 19-03-18 13:30 7
48 141646 GV14859 7E7060100 619005 1 R.M.Requisition Start 19-03-18 13:18 NULL
56 141646 GV14859 7E7060100 619005 1 R.M.Requisition Finish 19-03-18 15:54 156
```
The expected result is : TimeDiff (Minute) column
```
select PO_NO, [MANAGEMENT_NO],[STATUS] [Time_Occurrence],
datediff(minute, (isnull((select [Time_Occurrence] from [TBL_FINISH_STATUS] t1 where t1.id=t2.id-1), dateadd(dd, 0, datediff(dd, 0, getdate())))), [Time_Occurrence])TimeDiff
from [PROC_MN].[dbo].[TBL_FINISH_STATUS] t2
ORDER BY PO_NO,MANAGEMENT_NO,ITEM_CD,Time_Occurrence
```
With above query, the result is far wrong with the expected result
Could anyone help me please?
Note: the ID column (48,56) of SEQ 1 of PO\_NO: GV14859<issue_comment>username_1: It is not really clear what you are expecting as a result. Looking at your data sample, the design looks flawed from the start. There is too much redundancy for an SQL database. Maybe you don't have any control over the existing database. Anyway, this could be solved in N different ways and if my memory is not wrong, LEAD\LAG functions didn't exist in SQL server 2008 (but row\_number is there as another solution). I tried to create something that is even compatible with older versions, but not sure if that is what you meant as a result:
```
DECLARE @myTable TABLE([ID] INT,
[INDEXNO] INT,
[PO_NO] VARCHAR(7),
[ITEM_CD] VARCHAR(10),
[MANAGEMENT_NO] INT,
[SEQ] INT,
[PROCESS_NAME] VARCHAR(15),
[STATUS] VARCHAR(6),
[Time_Occurrence] DATETIME,
[TimeDiff] VARCHAR(4));
INSERT INTO @myTable([ID], [INDEXNO], [PO_NO], [ITEM_CD], [MANAGEMENT_NO], [SEQ], [PROCESS_NAME], [STATUS], [Time_Occurrence], [TimeDiff])
VALUES(43, 126690, 'GV12762', '332393961', 616244, 6, 'RFID', 'Start', '20180317 13:28', NULL),
(44, 126690, 'GV12762', '332393961', 616244, 6, 'RFID', 'Finish', '20180317 13:29', '0'),
(49, 141646, 'GV14859', '7E7060100', 619005, 2, 'Imprint', 'Start', '20180319 13:23', NULL),
(50, 141646, 'GV14859', '7E7060100', 619005, 2, 'Imprint', 'Finish', '20180319 13:30', '7'),
(48, 141646, 'GV14859', '7E7060100', 619005, 1, 'R.M.Requisition', 'Start', '20180318 13:18', NULL),
(56, 141646, 'GV14859', '7E7060100', 619005, 1, 'R.M.Requisition', 'Finish', '20180318 15:54', '156');
SELECT * FROM @myTable;
WITH
Starters AS (
SELECT ID, PO_NO, [MANAGEMENT_NO], [PROCESS_NAME], [Time_Occurrence]
FROM @myTable
WHERE STATUS='Start'
),
Finishers AS (
SELECT ID, PO_NO, [MANAGEMENT_NO], [PROCESS_NAME], [Time_Occurrence]
FROM @myTable
WHERE STATUS='Finish'
)
SELECT s.PO_NO, s.MANAGEMENT_NO, s.PROCESS_NAME,
s.Time_Occurrence as [Start], f.Time_Occurrence as [End],
DATEDIFF(MINUTE, s.Time_Occurrence, f.Time_Occurrence) AS TIMEdiff
FROM Starters s
LEFT JOIN Finishers f ON s.PO_NO=f.PO_NO
AND s.MANAGEMENT_NO=f.MANAGEMENT_NO
AND f.PROCESS_NAME=s.PROCESS_NAME;
```
Upvotes: 0 <issue_comment>username_2: If I understand what you want, then this seems like a simple query for it:
```
select INDEXNO, PO_NO, ITEM_CD, MANAGEMENT_NO, SEQ,
datediff(minute,
min(case when status = 'Start' then Time_Occurrence end),
max(case when status = 'Finish' then Time_Occurrence end)
) as timediff
from t
group by INDEXNO, PO_NO, ITEM_CD, MANAGEMENT_NO, SEQ;
```
[Here](http://www.sqlfiddle.com/#!18/fd401/2) is a SQL Fiddle.
Upvotes: 2 [selected_answer] |
2018/03/21 | 1,773 | 5,402 | <issue_start>username_0: Find the bellow parent child tree object I have created. I need to find the root parent of a given child id. For example child id - 242 root parent id is 238. There are similar questions have been asked and this is the one I found very similar to my question.
[Convert parent-child array to tree](https://stackoverflow.com/questions/15792794/convert-parent-child-array-to-tree/23939907)
I have change the original code a bit But not working for child element. The issue is here. when it comes the recursive function with `rootNode.children` for loop will not execute since it does not loop through children. But if I change the for loop `for (var i = 0; i < rootNode.length; i++)` to `for (var i = 0; i < rootNode.children.length; i++)` then it break on first loop since does not have children. I'm sure with small code change this can make work.
```js
var getParent = function (rootNode, rootId) {
if (rootNode.id === rootId)
return rootNode;
//for (var i = 0; i < rootNode.children.length; i++) -- original code line not working first time
for (var i = 0; i < rootNode.length; i++) {
var child = rootNode[i];
if (child.id === rootId)
return child;
if (typeof child.children !== 'undefined')
var childResult = getParent(child, rootId);
if (childResult != null) return childResult;
}
return null;
};
var mytree = [
{
"id": 245,
"parent": "0",
"title": "project1",
"children": [
{
"id": 246,
"parent": "245",
"title": "sub task 1"
}
]
},
{
"id": 238,
"parent": "0",
"title": "project2",
"children": [
{
"id": 240,
"parent": "238",
"title": "sub task 2"
},
{
"id": 242,
"parent": "238",
"title": "sub task 3",
"children" : [
{
"id": 241,
"parent": "242",
"title": "sub task 3.1"
}
]
}
]
},
{
"id": 173,
"parent": "0",
"title": "project3"
}
];
console.log(JSON.stringify(getParent(mytree, 238)['title']));
console.log(JSON.stringify(getParent(mytree, 241)));
```<issue_comment>username_1: You need to iterate the given root node, because this is an array, not an object.
```js
function getParent(root, id) {
var node;
root.some(function (n) {
if (n.id === id) {
return node = n;
}
if (n.children) {
return node = getParent(n.children, id);
}
});
return node || null;
}
var mytree = [{ id: 245, parent: "0", title: "project1", children: [{ id: 246, parent: "245", title: "sub task 1" }] }, { id: 238, parent: "0", title: "project2", children: [{ id: 240, parent: "238", title: "sub task 2" }, { id: 242, parent: "238", title: "sub task 3", children: [{ id: 241, parent: "242", title: "sub task 3.1" }] }] }, { id: 173, parent: "0", title: "project3" }];
console.log(getParent(mytree, 238));
console.log(getParent(mytree, 241));
```
```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
```
More a classical attempt
```js
function getParent(root, id) {
var i, node;
for (var i = 0; i < root.length; i++) {
node = root[i];
if (node.id === id || node.children && (node = getParent(node.children, id))) {
return node;
}
}
return null;
}
var mytree = [{ id: 245, parent: "0", title: "project1", children: [{ id: 246, parent: "245", title: "sub task 1" }] }, { id: 238, parent: "0", title: "project2", children: [{ id: 240, parent: "238", title: "sub task 2" }, { id: 242, parent: "238", title: "sub task 3", children: [{ id: 241, parent: "242", title: "sub task 3.1" }] }] }, { id: 173, parent: "0", title: "project3" }];
console.log(getParent(mytree, 238));
console.log(getParent(mytree, 241));
```
```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: I think my js tools can help you
<https://github.com/wm123450405/linqjs>
```js
var mytree = [
{
"id": 245,
"parent": "0",
"title": "project1",
"children": [
{
"id": 246,
"parent": "245",
"title": "sub task 1"
}
]
},
{
"id": 238,
"parent": "0",
"title": "project2",
"children": [
{
"id": 240,
"parent": "238",
"title": "sub task 2"
},
{
"id": 242,
"parent": "238",
"title": "sub task 3",
"children" : [
{
"id": 241,
"parent": "242",
"title": "sub task 3.1"
}
]
}
]
},
{
"id": 173,
"parent": "0",
"title": "project3"
}
];
//node.asEnumerable get a Tree object
//isAncestorOf to predicate the root node is or not the ancestor node of parameter
console.log(mytree.find(node => node.asEnumerable(node => node.children, node => node.id).isAncestorOf(241)));
console.log(mytree.find(node => node.asEnumerable(node => node.children, node => node.id).isAncestorOf(242)).title);
```
Upvotes: 0 |
2018/03/21 | 908 | 2,629 | <issue_start>username_0: I'v created a masonry grid with Flexbox. The order of the items was vertically, therefore I created a function to sort the items horizontally:
Before:
```
1 4 7
2 5 8
3 6 9
```
After (with my function):
```
1 2 3
4 5 6
7 8 9
```
Function to sort the items:
```
// Function to order the post items for the masonry Grid
// @param {Array} Posts
// @param {Integer} Number of columns
// @return {Array} Ordered list of posts
export const orderItems = (postItems, columns) => {
let posts = [];
let orderedPosts = [];
for (let col = 0; col < columns; col++) {
posts[col] = [];
}
let col = 0;
for (let i = 0; i < postItems.length; i++) {
if (i % columns === 0) {
posts[col].push(postItems[i]);
} else if (i % columns === 1) {
posts[col + 1].push(postItems[i]);
} else if (i % columns === 2) {
posts[col + 2].push(postItems[i]);
} else if (i % columns === 3) {
posts[col + 3].push(postItems[i]);
} else if (i % columns === 4) {
posts[col + 4].push(postItems[i]);
} else if (i % columns === 5) {
posts[col + 5].push(postItems[i]);
} else if (i % columns === 6) {
posts[col + 6].push(postItems[i]);
}
}
for (let col = 0; col < columns; col++) {
for (let post = 0; post < posts[col].length; post++) {
orderedPosts.push(posts[col][post]);
}
}
return orderedPosts;
};
```
I used a dynamic array because It depends on the screen size how many columns exist. But I'm not very happy with my solution..
Is there a better way (better performance) to solve my problem (without dynamic array)?
Thanks for your help !<issue_comment>username_1: Use array.map:
```js
var before = [
[1, 4, 7],
[2, 5, 8],
[3, 6, 9]
];
var after = before[0].map((e, i) => before.map(row => row[i]));
console.log(after);
```
Upvotes: 2 <issue_comment>username_2: The simplest would be to use Flexbox own property, `order`, and e.g. when 3 in each column, give element an inline style of:
* 1,4,7 `order: 1`
* 2,5,8 `order: 2`
* 3,6,9 `order: 3`
Then, e.g. in below sample, you set the item's `order` and parent `height` inline with your script.
```css
.parent {
display: flex;
flex-flow: column wrap;
align-content: flex-start;
}
/* for this demo only */
.parent {
counter-reset: num;
}
.parent div::before {
counter-increment: num;
content: counter(num);
}
.parent div {
width: 80px;
height: 80px;
margin: 5px;
background: #ccc;
display: flex;
justify-content: center;
align-items: center;
}
```
```html
```
Upvotes: 2 [selected_answer] |
2018/03/21 | 578 | 2,237 | <issue_start>username_0: I have a linked list like this:
>
> Head->A->B->C->D->Tail.
>
>
>
There can be `N (1 items in the list.
The current cursor position is, cursor->B which is 2 if we think like an array.
I have to perform the following operation on my list:`
* insert x characters in the list at the cursor position and update the
cursor.
* delete `y (y < N`) characters starting from the
cursor position and update the cursor.
* move the cursor to a specific position within in the list.
I want all this operation in constant time.
Can anyone kindly help by suggesting any data structure model?<issue_comment>username_1: There isn't. Searching / iterating is linear in complexity - O(n). If you want a constant complexity, you need to use the different data structure. Since you are using C++, you should utilize one from the [Containers library](http://en.cppreference.com/w/cpp/container).
Upvotes: 2 <issue_comment>username_2: Of course it is not possible to use the linked list for that. As said before a linked list has a linear complexity.
You can try to use a more complex data structure like a hash as a lookup-container for the items in your list, which has a complexity of - O(n). Instead of storing the items itself the stored item can contain a pointer / index showing to the next item. But you have to keep in mind that the deletion will be still expensive because when removing one item you have to refresh the links showing to this item as well, So the item itself will need to know, if any other items are pointing to it.
Upvotes: 0 <issue_comment>username_3: If the data can be sorted then by using "skip lists" a speed up can be achieved.
The principle is that extra pointers are used to skip ahead.
>
> skip list is a data structure that allows fast search within an ordered sequence of elements. Fast search is made possible by maintaining a linked hierarchy of subsequences, with each successive subsequence skipping over fewer elements than the previous one ...
>
>
>
[wikipedia](https://en.m.wikipedia.org/wiki/Skip_list)
>
> Therefore, with O(√n) extra space, we are able to reduce the time complexity to O(√n).
>
>
>
[Skip-list](https://www.geeksforgeeks.org/skip-list/)
Upvotes: 2 |
2018/03/21 | 441 | 1,374 | <issue_start>username_0: I get the json from API, and the json look's like :
```
"diagnosis": {
"type": [],
"kode": [],
"PrimaryCat": [],
"Location": [],
"Encountrace": [],
"Fracture": [],
"Healing": [],
}
```
Expected Result:
I want to store the `keys` into array, and the result should be
>
> ['type', 'kode', 'PrimaryCat', 'Location', 'Encountrace', 'Fracture', 'Healing']
>
>
>
it is possible to get it?
Refer to [this question](https://stackoverflow.com/questions/30412603/get-jsonarray-key-name), I cant convert the code from android into javascript<issue_comment>username_1: Just use `Object.keys` method.
>
> The Object.keys() method returns an array of a given object's own
> enumerable properties, in the same order as that provided by a
> for...in loop (the difference being that a for-in loop enumerates
> properties in the prototype chain as well).
>
>
>
```
const keys = Object.keys(diagnosis)
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can use `Object.keys`. For more info see [this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)
```js
var diagnosis= {
"type": [],
"kode": [],
"PrimaryCat": [],
"Location": [],
"Encountrace": [],
"Fracture": [],
"Healing": [],
}
var keys=Object.keys(diagnosis);
console.log(keys)
```
Upvotes: 1 |
2018/03/21 | 456 | 1,558 | <issue_start>username_0: Wonder how to resize an image inside a `TextView` xml in a `LinearLayout`. I read some solution using `setCompoundDrawablesWithIntrinsicBounds` method, but cannot get it right.
Here is the image:
[](https://i.stack.imgur.com/C6Ywx.png)
I want to reduce the size of the logo.
Here is my TextView code:
```
```<issue_comment>username_1: **Try :**
```
android:scaleX="0.7"
android:scaleY="0.7"
```
**OR**
Wrap your resource in a drawable that defines your desired size similar to:
```
xml version="1.0" encoding="utf-8"?
```
then use it in drawable left.
Upvotes: 6 [selected_answer]<issue_comment>username_2: there is only one solution take image view for the image and resize image but text display image right side . you used below code and i hope your issue solved..
```
xml version="1.0" encoding="utf-8"?
```
```
```
Upvotes: 2 <issue_comment>username_3: Programmatic solution:
You can use `drawable.setBounds` but it requires pixels rather than dp as parameters.
how to convert: [Converting pixels to dp](https://stackoverflow.com/questions/4605527/converting-pixels-to-dp)
code:
```java
Drawable drawable = getDrawable(R.drawable.ic_your_drawable);
int size = dp2px(this, dpSize);
if (drawable != null) {
drawable.setBounds(0, 0, size, size);
}
textView.setCompoundDrawables(drawable, drawable, drawable, drawable); // should be (drawable, null, null, null) for you
```
Upvotes: 0 |
2018/03/21 | 434 | 1,617 | <issue_start>username_0: There are several ways my user can get privileges in a Google Cloud Platform project. Direct role and privilege assignment, act as service accounts, different group membership.
So given a GCP project, how can I list the active privileges for my user?<issue_comment>username_1: Usually, in GCP, they are called "[Permissions](https://cloud.google.com/resource-manager/docs/access-control-proj#permissions_and_roles)". For ease of use, those permissions are grouped in "Roles".
Each user can have different roles in your project. To get a full list of the accounts having each role in a project, you can use the [Resource Manager API](https://cloud.google.com/resource-manager/reference/rest/) to [get the IAM policies](https://cloud.google.com/resource-manager/reference/rest/v1/projects/getIamPolicy).
Long story short, make sure that `gcurl` is properly configured and just run the following command, filtering the output according to your needs:
```
curl -XPOST https://cloudresourcemanager.googleapis.com/v1/projects/$(gcloud config get-value project):getIamPolicy -d'{}' -H"Authorization: Bearer $(gcloud auth print-access-token)" -H'content-type:application/json'
```
Upvotes: 2 <issue_comment>username_2: ```
gcloud projects get-iam-policy $PROJ \
--flatten="bindings[].members" \
--format='table(bindings.role)' \
--filter="bindings.members:user:$USER"
```
`USER` is like email (*<EMAIL>*), `PROJ` is like *project-654321*.
**UPDATE** To search across **all resources**:
```
gcloud asset search-all-iam-policies --query=policy:$EMAIL
```
Upvotes: 2 [selected_answer] |
2018/03/21 | 781 | 2,881 | <issue_start>username_0: I have the following method that I want to decrypt. The following method Encrypts. What should I do to decrypt?
**Code**
```
PlainString = "5lg3yg7Q+Y8="
func tripleDesEncrypt(PlainString: String) -> String {
let keyData = "<KEY>"
let PlainStringvar = PlainString
guard let data = PlainStringvar.data(using: .utf8) else {
return ""
}
let cryptData = NSMutableData(length: Int(data.count) + kCCBlockSize3DES)!
let keyLength = size_t(kCCKeySize3DES)
let operation: CCOperation = UInt32(kCCEncrypt)
let algoritm: CCAlgorithm = UInt32(kCCAlgorithm3DES)
let options: CCOptions = UInt32(kCCOptionECBMode + kCCOptionPKCS7Padding)
var numBytesEncrypted :size_t = 0
let cryptStatus = CCCrypt(operation,
algoritm,
options,
keyData.bytes, keyLength,
nil,
data.bytes, data.count,
cryptData.mutableBytes, cryptData.length,
&numBytesEncrypted)
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
cryptData.length = Int(numBytesEncrypted)
var base64cryptString = cryptData.base64EncodedString(options: .lineLength64Characters)
return base64cryptString //// encodeString(str: base64cryptString)
} else {
print("Error: \(cryptStatus)")
}
return ""
}
```<issue_comment>username_1: Usually, in GCP, they are called "[Permissions](https://cloud.google.com/resource-manager/docs/access-control-proj#permissions_and_roles)". For ease of use, those permissions are grouped in "Roles".
Each user can have different roles in your project. To get a full list of the accounts having each role in a project, you can use the [Resource Manager API](https://cloud.google.com/resource-manager/reference/rest/) to [get the IAM policies](https://cloud.google.com/resource-manager/reference/rest/v1/projects/getIamPolicy).
Long story short, make sure that `gcurl` is properly configured and just run the following command, filtering the output according to your needs:
```
curl -XPOST https://cloudresourcemanager.googleapis.com/v1/projects/$(gcloud config get-value project):getIamPolicy -d'{}' -H"Authorization: Bearer $(gcloud auth print-access-token)" -H'content-type:application/json'
```
Upvotes: 2 <issue_comment>username_2: ```
gcloud projects get-iam-policy $PROJ \
--flatten="bindings[].members" \
--format='table(bindings.role)' \
--filter="bindings.members:user:$USER"
```
`USER` is like email (*<EMAIL>*), `PROJ` is like *project-654321*.
**UPDATE** To search across **all resources**:
```
gcloud asset search-all-iam-policies --query=policy:$EMAIL
```
Upvotes: 2 [selected_answer] |
2018/03/21 | 828 | 2,651 | <issue_start>username_0: I have written a JAX-RS REST-API, that fetches rows from Oracle.
For this I have used `JNDI` since I am using `Jetty`. But on deploying the WAR file I am getting the following error:
```
Caused by:
java.lang.IllegalStateException: Nothing to bind for name jdbc/replaydev
at org.eclipse.jetty.plus.webapp.PlusDescriptorProcessor.bindEntry(PlusDescriptorProcessor.java:914)
```
My web.xml has the following entry:
```
jdbc/replaydev
javax.sql.DataSource
Container
```
WEB-INF/jetty-env.xml has following entries:
```
xml version="1.0" encoding="UTF-8"?
jdbc/replaydev
jdbc:oracle:thin://@MY.ORACLE.SERVER:1555/JOBCTL
XYZ
rockOn
true
```
And my Java code has the following:
```
Context initContext = new InitialContext();
ds = (DataSource)initContext.lookup("java:/comp/env/jdbc/replaydev");
con = ds.getConnection();
Class.forName("oracle.jdbc.OracleDriver");
```
POM.xml has following dependencies added:
```
org.eclipse.jetty
jetty-server
9.2.11.v20150529
org.eclipse.jetty
jetty-webapp
9.2.11.v20150529
org.eclipse.jetty
jetty-plus
9.2.11.v20150529
org.eclipse.jetty
jetty-jndi
9.2.11.v20150529
```
I even tried adding `id` tags in web.xml entry like: `....` for jetty-env.xml . Its not working either.
Am I missing something??<issue_comment>username_1: Usually, in GCP, they are called "[Permissions](https://cloud.google.com/resource-manager/docs/access-control-proj#permissions_and_roles)". For ease of use, those permissions are grouped in "Roles".
Each user can have different roles in your project. To get a full list of the accounts having each role in a project, you can use the [Resource Manager API](https://cloud.google.com/resource-manager/reference/rest/) to [get the IAM policies](https://cloud.google.com/resource-manager/reference/rest/v1/projects/getIamPolicy).
Long story short, make sure that `gcurl` is properly configured and just run the following command, filtering the output according to your needs:
```
curl -XPOST https://cloudresourcemanager.googleapis.com/v1/projects/$(gcloud config get-value project):getIamPolicy -d'{}' -H"Authorization: Bearer $(gcloud auth print-access-token)" -H'content-type:application/json'
```
Upvotes: 2 <issue_comment>username_2: ```
gcloud projects get-iam-policy $PROJ \
--flatten="bindings[].members" \
--format='table(bindings.role)' \
--filter="bindings.members:user:$USER"
```
`USER` is like email (*<EMAIL>*), `PROJ` is like *project-654321*.
**UPDATE** To search across **all resources**:
```
gcloud asset search-all-iam-policies --query=policy:$EMAIL
```
Upvotes: 2 [selected_answer] |
2018/03/21 | 593 | 2,023 | <issue_start>username_0: I m want to extract the scene change timestamp using the scene change detection from ffmpeg. I have to run it on a few hundreds of videos , so i wanted to use a python subprocess to loop over all the content of a folder.
My problem is that the command that i was using for getting these values on a single video involve piping the output to a file which seems to not be an option from inside a subprocess call.
this is my code :
```
p=subprocess.check_output(["ffmpeg", "-i", sourcedir+"/"+name+".mpg","-filter:v", "select='gt(scene,0.4)',showinfo\"","-f","null","-","2>","output"])
```
this one tell ffmpeg need an output
```
output = "./result/"+name
p=subprocess.check_output(["ffmpeg", "-i", sourcedir+"/"+name+".mpg","-filter:v", "select='gt(scene,0.4)',metadata=print:file=output","-an","-f","null","-"])
```
this one give me no error but doesn't create the file
this is the original command that i use directly with ffmpeg:
```
ffmpeg -i input.flv -filter:v "select='gt(scene,0.4)',showinfo" -f null - 2> ffout
```
I just need the ouput of this command to be written to a file, anyone see how i could make it work?
is there a better way then subprocess ? or just another way ? will it be easier in C?<issue_comment>username_1: Things are easier in your case if you use the `shell` argument of the `subprocess` command and it should behave the same. When using the shell command, you can pass in a **string** as the command rather then a **list of args.**
```
cmd = "ffmpeg -i {0} -filter:v \"select='gt(scene,0.4)',showinfo\" -f {1} - 2> ffout".format(inputName, outputFile)
p=subprocess.check_output(cmd, shell=True)
```
If you want to pass arguments, you can easily format your string
Upvotes: 0 <issue_comment>username_2: You can redirect the `stderr` output directly from Python without any need for `shell=True` which can lead to shell injection.
It's as simple as:
```
with open(output_path, 'w') as f:
subprocess.check_call(cmd, stderr=f)
```
Upvotes: 1 |
2018/03/21 | 852 | 3,220 | <issue_start>username_0: I'm creating a seat selection screen but I'm confused, how can I achieve this view. I want to access all selected seats into one single Java file. Plz, help me[](https://i.stack.imgur.com/P8wuB.png)
EDIT: I've tried this code but with this code, I'm not able to create a view like this into single gridview. Now I'm using 2 separate gridviews for that and two Java files with the separate adapter with them.
Seat\_Select.java
```
public class Seat_Select extends AppCompatActivity {
GridView androidgridview;
int[] image = {
R.drawable.rect_select, R.drawable.rect_select,
R.drawable.rect_select, R.drawable.rect_select,
R.drawable.rect_select, R.drawable.rect_select,
R.drawable.rect_select, R.drawable.rect_select,
R.drawable.rect_select, R.drawable.rect_select,
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seat__select);
androidgridview = findViewById(R.id.grid);
SeatAdapter seatAdapter=new SeatAdapter(Seat_Select.this,image);
androidgridview.setAdapter(seatAdapter);
androidgridview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
Toast.makeText(getBaseContext(), "Grid Item " + (position + 1) + " Selected", Toast.LENGTH_LONG).show();
}
});
}
```
SeatAdapter.java
```
public class SeatAdapter extends BaseAdapter {
Context context;
LayoutInflater layoutInflater;
int image[];
public SeatAdapter(Context context,int[] image) {
this.context = context;
this.image=image;
layoutInflater=(LayoutInflater.from(context));
}
@Override
public int getCount() {
return image.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView =layoutInflater.inflate(R.layout.grid2col,null);
ImageView imageView= convertView.findViewById(R.id.grid_image);
imageView.setImageResource(image[position]);
return convertView;
}
}
```
grid2col.xml
```
xml version="1.0" encoding="utf-8"?
```
activity\_seat\_select.xml
```
```<issue_comment>username_1: **GridView**
GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid. The grid items are automatically inserted to the layout using a ListAdapter. you can GridView in your layout file like below.
```
xml version="1.0" encoding="utf-8"?
```
**GridLayout**
Grid layout is mainly used to align its child views in cells which are the horizontal and vertical intercepts of an invisible line. Each view child is place in a cell and the cells are numbered with the horizontal and vertical indexes.
```
```
Upvotes: 0 <issue_comment>username_2: Please check [SeatBookingRecylerView](https://github.com/TakeoffAndroid/SeatBookingRecyclerView). This example has full source code. It may be helpful for you. This is using `RecyclerView`.
Upvotes: 1 |
2018/03/21 | 587 | 1,981 | <issue_start>username_0: I am trying to complete, which i thought would be simple, a `where` statement within SQL using `CurDate` instead of me having to amend dates each time i run my code, i am looking for the `where` statement to look over a 360 period, beginning today and working backwards.
I have tried all of the items below and neither will work, please can someone tell me where i am going wrong.
```
Where LastPD > CurDate()- interval 360 days;
Where LastPD > CurDate()-360;
Where LastPD > CurDate-360;
```
I am trying to reduce a file with over 20 million rows of data to show data with either a `LastPD` within the last 6/12 months or a `AssignDate` within the last 6/12 Months.
The code i have previously used is as follows;
```
Data DCARMSLive12LPD;
Set DCARMSLive12;
Where LastPD > '20170320';
run;
Data DCARMSLive12PLC;
Set DCARMSLive12;
Where AssignDate > '20MAr2017'd;
Run;
Data DCARMSLive06LPD;
Set DCARMSLive6;
Where LastPD > '20170920';
run;
Data DCARMSLive06PLC;
Set DCARMSLive6;
Where AssignDate > '20Sep2017'd;
Run;
```
I want to replace the actual date within the where statements so they do not have to be updated manually each time the code is ran.<issue_comment>username_1: **GridView**
GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid. The grid items are automatically inserted to the layout using a ListAdapter. you can GridView in your layout file like below.
```
xml version="1.0" encoding="utf-8"?
```
**GridLayout**
Grid layout is mainly used to align its child views in cells which are the horizontal and vertical intercepts of an invisible line. Each view child is place in a cell and the cells are numbered with the horizontal and vertical indexes.
```
```
Upvotes: 0 <issue_comment>username_2: Please check [SeatBookingRecylerView](https://github.com/TakeoffAndroid/SeatBookingRecyclerView). This example has full source code. It may be helpful for you. This is using `RecyclerView`.
Upvotes: 1 |
2018/03/21 | 1,097 | 4,124 | <issue_start>username_0: I would like to know how pass ArrayList data through intent() in gridView.setOnItemClickListener() and get it in ShowTracksActivity.java. How is possible ?
**MainActivity.java**
```
ArrayListartists = new ArrayList();
// Artist 1
String[] artist\_title = new String[]{ "Title 1", "Title 2","Title 3", "Title 4" };
artists.add(new Artist("Artist Name", "Album Name", "img\_album", artist\_title ));
// Artist 2
//...
ArtistAdapter adapter = new ArtistAdapter(this, artists);
GridView gridView = (GridView) findViewById(R.id.gridview);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new GridView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView parent, View v, int position, long id)
{
Intent ShowTrackIntent = new Intent(MainActivity.this, ShowTracksActivity.class);
// Here ?
// ShowTrackIntent.putExtra( ??? );
startActivity(ShowTrackIntent);
}
});
```
**ShowTracksActivity.java**
```
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ???
}
```
Thank you for your help.<issue_comment>username_1: You try:
**In MainActivity:**
`intent.putExtra("list", artists);`
**In ShowTracksActivity:**
```
ArrayList list = (ArrayList)
getIntent().getSerializableExtra("list");
```
And `Artist` must is implements `Serializable`
Upvotes: 0 <issue_comment>username_2: You can try this in **MainActivity.java**
```
gridView.setOnItemClickListener(new GridView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView parent, View v, int position, long id)
{
Intent ShowTrackIntent = new Intent(MainActivity.this, ShowTracksActivity.class);
ShowTrackIntent.putParcelableArrayListExtra("key", ArrayList list);
startActivity(ShowTrackIntent );
}
});
```
And Retrieve it in **ShowTracksActivity.java**
```
getIntent().getParcelableArrayListExtra("key");
```
Upvotes: 1 <issue_comment>username_3: Ok so here is the idea, when you click on the artist you get position of that cell inside your click listener, so now you have to use that position and take out the artist from your artists list of that position. And pass it through intent, in android for passing user defined data/object you need to either make them Serializable or Parcelable.
You can refer this [question](https://stackoverflow.com/q/2736389/4878972)
Also Intent/Bundle class has methods for this type of data passing between Activities.
**Sample code:**
```
Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);
intent.putExtra(key, value); // Here key would be String and value can be either Parcelable or Serializable
startActivity(intent);
```
**In your case inside your item click listener:**
```
Artist artist = artists.get(postion);
Intent intent = new Intent(MainActivity.this, ShowTracksActivity.class);
intent.putExtra("selected_artist", artist); // Here key would be String and value can be either Parcelable or Serializable
startActivity(intent);
```
**Note:** You have to make your Artist class serializable for passing it to other activity, for how to do that you can refer this
[Why use parcelable?](https://stackoverflow.com/a/10179861/4878972), [How To make class parcelable?](https://stackoverflow.com/a/6923794/4878972) and [The easy and dirty way](https://stackoverflow.com/a/7827593/4878972)
Upvotes: 2 [selected_answer]<issue_comment>username_4: I made something like that in order to pass a full object what ever it is using Gson
```
Intent ShowTrackIntent = new Intent(MainActivity.this,ShowTracksActivity.class);
ShowTrackIntent .putExtra("ObjectValue",new Gson().toJson(yourObject));
startActivity(ShowTrackIntent);
```
in the second activity when you pull the object you just need to pull it like the following
```
MyClassModel myModel=new Gson().fromJson(getIntent().getStringExtra("ObjectValue"),MyClassModel.class);
```
You need to import the Powerfull [Gson](https://github.com/google/gson) Library dependency, almost it is there in all projects
Upvotes: 1 |
2018/03/21 | 2,143 | 7,635 | <issue_start>username_0: I have some problems with pandas' `HDFStore` being far to slow and unfortunately I'm unable to put together a satisfying solution from other questions here.
### Situation
I have a big DataFrame, containing mostly floats and sometimes integer columns which goes through multiple processing steps (renaming, removing bad entries, aggregating by 30min). Each row has a timestamp associated to it. I would like to save some middle steps to a HDF file, so that the user can do a single step iteratively without starting from scratch each time.
Additionally the user should be able to plot certain column from these saves in order to select bad data. Therefore I would like to retrieve only the column names without reading the data in the HDFStore.
Concretely the user should get a list of all columns of all dataframes stored in the HDF then they should select which columns they would like to see whereafter I use matplotlib to present them the corresponding data.
Data
`shape == (5730000, 339)` does not seem large at all, that's why I'm confused... (Might get far more rows over time, columns should stay fixed)
In the first step I append iteratively rows and columns (that runs okay), but once that's done I always process the entire DataFrame at once, only grouping or removing data.
### My approach
1. I do all manipulations in memory since pandas seems to be rather fast and I/O is slower (HDF is on different physical server, I think)
2. I use datetime index and automatically selected float or integer columns
3. I save the steps with `hdf.put('/name', df, format='fixed')` since `hdf.put('/name'.format(grp), df, format='table', data_columns=True)` seemed to be far too slow.
4. I use e.g. `df.groupby(df.index).first()` and `df.groupby(pd.Grouper(freq='30Min')).agg(agg_dict)` to process the data, where agg\_dict is a dictonary with one function per column. This is incredibly slow as well.
5. For plotting, I have to read-in the entire dataframe and then get the columns: `hdfstore.get('/name').columns`
### Question
* *How can I retrieve all columns without reading any data from the HDFStore?*
* What would be the most efficient way of storing my data? Is HDF the right option? Table or fixed?
* Does it matter in term of efficiency if the index is a datetime index? Does there exists a more efficient format in general (e.g. all columns the same, fixed dtype?)
* Is there a faster way to aggregate instead of `groupby` (`df.groupby(pd.Grouper(freq='30Min')).agg(agg_dict)`)
### similar questions
[How to access single columns using `.select`](https://stackoverflow.com/questions/13926089/selecting-columns-from-pandas-hdfstore-table#13977244)
I see that I can use this to retrieve only certain columns but only after I know the column names, I think.
Thank you for any advice!<issue_comment>username_1: For a HDFStore `hdf` and a `key` (from `hdf.keys()`) you can get the column names with:
```
# Table stored with hdf.put(..., format='table')
columns = hdf.get_node('{}/table'.format(key)).description._v_names
# Table stored with hdf.put(..., format='fixed')
columns = list(hdf.get_node('{}/axis0'.format(key)).read().astype(str))
```
note that `hdf.get(key).columns` works as well, but it reads all the data into memory, while the approach above only reads the column names.
---
Full working example:
```
#!/usr/bin/env python
import pandas as pd
data = pd.DataFrame({'a': [1,1,1,2,3,4,5], 'b': [2,3,4,1,3,2,1]})
with pd.HDFStore(path='store.h5', mode='a') as hdf:
hdf.put('/DATA/fixed_store', data, format='fixed')
hdf.put('/DATA/table_store', data, format='table', data_columns=True)
for key in hdf.keys():
try:
# column names of table store
print(hdf.get_node('{}/table'.format(key)).description._v_names)
except AttributeError:
try:
# column names of fixed store
print(list(hdf.get_node('{}/axis0'.format(key)).read().astype(str)))
except AttributeError:
# e.g. a dataset created by h5py instead of pandas.
print('unknown node in HDF.')
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You may simply load 0 rows of the DataFrame by specifying same `start` and `stop` attributes. And leave all internal index/column processing for pandas itself:
```py
idx = pd.MultiIndex.from_product([('A', 'B'), range(2)], names=('Alpha', 'Int'))
df = pd.DataFrame(np.random.randn(len(idx), 3), index=idx, columns=('I', 'II', 'III'))
df
>>> I II III
>>> Alpha Int
>>> A 0 -0.472412 0.436486 0.354592
>>> 1 -0.095776 -0.598585 -0.847514
>>> B 0 0.107897 1.236039 -0.196927
>>> 1 -0.154014 0.821511 0.092220
```
Following works both for `fixed` an `table` formats:
```py
with pd.HDFStore('test.h5') as store:
store.put('df', df, format='f')
meta = store.select('df', start=1, stop=1)
meta
meta.index
meta.columns
>>> I II III
>>> Alpha Int
>>>
>>> MultiIndex(levels=[[], []],
>>> codes=[[], []],
>>> names=['Alpha', 'Int'])
>>>
>>> Index(['I', 'II', 'III'], dtype='object')
```
As for others question:
1. As long as your data is mostly homogeneous (almost float columns as you mentioned) and you are able to store it in single file without need to distribute data across machines - HDF is the first thing to try.
2. If you need to append/delete/query data - you must use `table` format. If you only need to write once and read many - `fixed` will improve performance.
3. As for datetime index, i think here we may use same idea as in 1 clause. If u are able to convert all data into single type it should increase your performance.
4. Nothing else that proposed in comment to your question comes to mind.
Upvotes: 2 <issue_comment>username_3: 1. Columns without reading any data:
```py
store.get_storer('df').ncols # substitute 'df' with your key
# you can also access nrows and other useful fields
```
2. From the docs ([fixed format](https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#fixed-format), [table format](https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#table-format)): (important points in **bold**)
>
> [**fixed**] These types of stores are **not appendable** once written (though you can simply remove them and rewrite). **Nor are they queryable**; they must be retrieved in their entirety. They also do not support dataframes with non-unique column names. The fixed format stores offer very fast writing and slightly faster reading than table stores.
>
>
>
>
> [**table**] Conceptually a table is shaped very much like a DataFrame, with rows and columns. A table **may be appended** to in the same or other sessions. In addition, **delete and query type operations are supported**.
>
>
>
3. You may try to use epochms (or epochns) (milliseconds or nanoseconds since epoch) in place of datetimes. This way, you are just dealing with integer indices.
4. You may have a look at [this answer](https://stackoverflow.com/questions/15798209/pandas-group-by-query-on-large-data-in-hdfstore) if what you need is grouping by on large data.
---
*An advice: if you have 4 questions to ask, it may be better to ask 4 separate questions on SO. This way, you'll get a higher number of (higher quality) answers, since each one is easier to tackle. And each will deal with a specific topic, making it easier to search for people that are looking for specific answers.*
Upvotes: 0 |
2018/03/21 | 377 | 921 | <issue_start>username_0: I've tried to find the cube root in Python but I have no idea how to find it. There was 1 line of code that worked but he wouldn't give me the full number. Example:
```
math.pow(64, 1/3)
```
This doesn't give me 4 tough but 3.99999. Does anyone know how I am supposed to fix this?<issue_comment>username_1: This is one option without using math library
```
>>> 64**(1/3)
3.9999999999999996
>>> round(64**(1/3.),2)
4.0
```
If you want to do with your code, you can apply 'round()' method
```
>>>import math
>>>round(math.pow(64,1/3.))
4
```
Upvotes: 3 <issue_comment>username_2: You can use the power operator `**` with fractions like:
Python3:
```
>>> 8**(1/3)
2.0
```
Python2:
```
>>> 8**(1.0/3)
2.0
```
Upvotes: 4 <issue_comment>username_3: in `Python 3.11`, `math.cbrt`
```
x = 64
math.cbrt(x)
```
(or)
use `numpy`
```
import numpy as np
x = 64
np.cbrt(x)
```
Upvotes: 3 |
2018/03/21 | 2,313 | 6,908 | <issue_start>username_0: I'd like that when I open a div, all the others close himself. I've looked for around and I found only answer with jQuery and not JavaScript.
This is my code:
```js
function openDescription(description_id) {
var x = document.getElementById(description_id);
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
};
```
```css
.row_team_pic{
text-align:center;
margin:-72px;
margin-top:0px;
margin-bottom: 15px;
}
.container{
background-color:silver;
width:150px;
display:inline-block;
margin-top:0px;
margin-left:10px;
}
.photo{
min-height:125px;
width:125px;
margin:10px;
padding-top:10px;
}
.name{
text-align: center;
padding-bottom: 10px;
cursor: pointer;
}
.description1{
float:left;
margin-left:0%;
margin-top:10px;
background-color:silver;
width:322px;
}
.description2{
float:left;
margin-left:-57%;
margin-top:10px;
background-color:silver;
width:322px;
}
.description3{
float:left;
margin-left:-57%;
margin-top:10px;
background-color:silver;
width:322px;
}
.description4{
float:left;
margin-left:-114%;
margin-top:10px;
background-color:silver;
width:322px;
}
```
```html

Name1
It's ok. It's working. It's ok. It's working. It's ok. It's working.
It's ok. It's working. It's ok. It's working.

Name2
It's ok. It's working. It's ok. It's working. It's ok. It's working.
It's ok. It's working. It's ok. It's working.

Name3
It's ok. It's working. It's ok. It's working. It's ok. It's working.
It's ok. It's working. It's ok. It's working.

Name4
It's ok. It's working. It's ok. It's working. It's ok. It's working.
It's ok. It's working. It's ok. It's working.
```
For example if I click on `name2` it give me the `description2`, but if I click on `name3` it doesn't close the `description2` but overlap only.
How should I achieve that?<issue_comment>username_1: Inside the function you have to reset `display = none` to all the div having class name started with `description` except the clicked element. Then set `display = block` only to the div whose `id` is passed to the function.
To achieve that add the following code inside the function:
```
var allNames = document.querySelectorAll('[class^=description]');
allNames.forEach(function(d){
if(d.getAttribute('id') != description_id){
d.style.display = "none";
}
});
```
**Working Code:**
```js
function openDescription(description_id) {
var allNames = document.querySelectorAll('[class^=description]');
allNames.forEach(function(d){
if(d.getAttribute('id') != description_id){
d.style.display = "none";
}
});
var x = document.getElementById(description_id);
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
};
```
```css
.row_team_pic{
text-align:center;
margin:-72px;
margin-top:0px;
margin-bottom: 15px;
}
.container{
background-color:silver;
width:150px;
display:inline-block;
margin-top:0px;
margin-left:10px;
}
.photo{
min-height:125px;
width:125px;
margin:10px;
padding-top:10px;
}
.name{
text-align: center;
padding-bottom: 10px;
cursor: pointer;
}
.description1{
float:left;
margin-left:0%;
margin-top:10px;
background-color:silver;
width:322px;
}
.description2{
float:left;
margin-left:-57%;
margin-top:10px;
background-color:silver;
width:322px;
}
.description3{
float:left;
margin-left:-57%;
margin-top:10px;
background-color:silver;
width:322px;
}
.description4{
float:left;
margin-left:-114%;
margin-top:10px;
background-color:silver;
width:322px;
}
```
```html

Name1
It's ok. It's working. It's ok. It's working. It's ok. It's working.
It's ok. It's working. It's ok. It's working.

Name2
It's ok. It's working. It's ok. It's working. It's ok. It's working.
It's ok. It's working. It's ok. It's working.

Name3
It's ok. It's working. It's ok. It's working. It's ok. It's working.
It's ok. It's working. It's ok. It's working.

Name4
It's ok. It's working. It's ok. It's working. It's ok. It's working.
It's ok. It's working. It's ok. It's working.
```
Upvotes: 2 <issue_comment>username_2: Add a new class called `description` into all the div elements which has the description. Then in your function, if the element's style is not `display: block`, hide all the elements that have the class `description` and set the `display: block` property to only to the selected element.
```js
function openDescription(description_id) {
var x = document.getElementById(description_id);
if (x.style.display === "block") {
x.style.display = "none";
} else {
var elements = document.getElementsByClassName('description');
for (var i = 0; i < elements.length; i++){
elements[i].style.display = 'none';
}
x.style.display = "block";
}
};
```
```css
.row_team_pic{
text-align:center;
margin:-72px;
margin-top:0px;
margin-bottom: 15px;
}
.container{
background-color:silver;
width:150px;
display:inline-block;
margin-top:0px;
margin-left:10px;
}
.photo{
min-height:125px;
width:125px;
margin:10px;
padding-top:10px;
}
.name{
text-align: center;
padding-bottom: 10px;
cursor: pointer;
}
.description1{
float:left;
margin-left:0%;
margin-top:10px;
background-color:silver;
width:322px;
}
.description2{
float:left;
margin-left:-57%;
margin-top:10px;
background-color:silver;
width:322px;
}
.description3{
float:left;
margin-left:-57%;
margin-top:10px;
background-color:silver;
width:322px;
}
.description4{
float:left;
margin-left:-114%;
margin-top:10px;
background-color:silver;
width:322px;
}
```
```html

Name1
It's ok. It's working. It's ok. It's working. It's ok. It's working.
It's ok. It's working. It's ok. It's working.

Name2
It's ok. It's working. It's ok. It's working. It's ok. It's working.
It's ok. It's working. It's ok. It's working.

Name3
It's ok. It's working. It's ok. It's working. It's ok. It's working.
It's ok. It's working. It's ok. It's working.

Name4
It's ok. It's working. It's ok. It's working. It's ok. It's working.
It's ok. It's working. It's ok. It's working.
```
Upvotes: 1 [selected_answer] |
2018/03/21 | 1,143 | 4,472 | <issue_start>username_0: I have multiple build types defined in my build.gradle. In variant window I selected build variant (ex debugAPI23). I expected that code in only one build type will be executed. But in Gradle Console I can see output for all build types.
As you can see I am trying to remove specific file for each build type. But everytime all build types are executed. So in the end I am missing the file that should be present for my selected build type.
```
android {
buildTypes {
debug {
println "build type debug"
debuggable true
signingConfig signingConfigs.debug
sourceSets {
main.java {
exclude '/cz/kctdata/kmf/Reader/KMFReaderCN51A60.java'
}
main.java.getIncludes().each { println "Added include: $it" }
main.java.sourceFiles.each { println "File in source set: " + it }
}
}
release {
println "build type release"
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
sourceSets {
main.java {
exclude '/cz/kctdata/kmf/Reader/KMFReaderCN51A60.java'
}
main.java.getIncludes().each { println "Added include: $it" }
main.java.sourceFiles.each { println "File in source set: " + it }
}
}
debugAPI23 {
println "build type debugAPI23"
debuggable true
signingConfig signingConfigs.debug
sourceSets {
main.java {
exclude '/cz/kctdata/kmf/Reader/KMFReaderCN51A42.java'
}
main.java.getIncludes().each { println "Added include: $it" }
main.java.sourceFiles.each { println "File in source set: " + it }
}
}
releaseAPI23 {
println "build type releaseAPI23"
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
sourceSets {
main.java {
exclude '/cz/kctdata/kmf/Reader/KMFReaderCN51A42.java'
}
main.java.getIncludes().each { println "Added include: $it" }
main.java.sourceFiles.each { println "File in source set: " + it }
}
}
}
}
```
I can not use build type specific folder because I have more build types and some files should be presented in multiple build types. I don't want to have multiple copies of same file in my project.<issue_comment>username_1: Last gradle android plugins have a new concept of "dimensions". <https://developer.android.com/studio/build/build-variants.html>
So you can try to use flavors and dimensions. A example:
```
android {
flavorDimensions "dim1", "dim2"
}
productFlavors {
flavor1 {
dimension "dim1"
}
flavor2 {
dimension "dim1"
}
flavor3 {
dimension "dim1"
}
flavor4 {
dimension "dim2"
}
}
```
Here you will get a combination between build type + favor with dim1 + flavor with dim2, in other words files from flavor4 will be accessible in all flavors. For example in variant debugFlavor1Flavor4 you will have all resources which belongs to debug, flavor1 and flavor4
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can build through the Terminal window in Android Studio, choosing by hand which flavor/build variant you want:
```
./gradlew assembleRelease
```
Or:
```
./gradlew assembleDebug
```
Or:
```
./gradlew assemble debugAPI23
```
Upvotes: 2 <issue_comment>username_3: I was able to do it with product flavors, suppose I have three flavors (Stage, Prod, QA) . Then I can create builds with the following commands:-
1. prod with releaseAPI23 (will create a build at ***PROJECT/android/app/build/outputs/apk/prod/releaseAPI23*** )
>
> ./gradlew assembleProdReleaseAPI23.
>
>
>
2. QA with releaseAPI23 (will create a build at ***PROJECT/android/app/build/outputs/apk/qa/releaseAPI23***)
>
> ./gradlew assembleQaReleaseAPI23.
>
>
>
3. Stage with releaseAPI23 (will create a build at ***PROJECT/android/app/build/outputs/apk/stage/releaseAPI23***)
>
> ./gradlew assembleStageReleaseAPI23.
>
>
>
\*\*You can try different variants as per your need
Upvotes: 1 |
2018/03/21 | 592 | 1,906 | <issue_start>username_0: ```
public static void randomSquare()
{
int[] array = new Random().ints(10).toArray();
for (int i=0; i
```
I currently have this method which returns random numbers. How would I modify it so it returns a stream of 10 square numbers instead?<issue_comment>username_1: If you want to square the random numbers, change
```
int[] array = new Random().ints(10).toArray();
```
to
```
int[] array = new Random().ints(10).map(x -> x*x).toArray();
```
However, this may result in integer overflow, so you might want to limit the range of the random integers. For example:
```
int[] array = new Random().ints(10,1,100).map(x -> x*x).toArray();
```
Also, you can init the Random first, like
```
static final Random RAND = new Random();
```
and then use
```
int[] array = RAND.ints(10,1,100).map(x -> x*x).toArray();
```
if you want to improve the performance.
Upvotes: 2 <issue_comment>username_2: If you are using Java 8, you can change your line of code to:
```
int[] array = new Random().ints(10).map(x -> x*x).toArray();
```
However your method at the moment does not return nothing. You use void keyword. Void doesn't return anything. It tells the compiler the method doesn't have a return value.
You can use int[], to return int array.
```
public static int[] randomSquare()
{
int[] array = new Random().ints(10).map(x -> x*x).toArray();
//some code, method logic etc.
return array;
}
```
Upvotes: 0 <issue_comment>username_3: I'm adding to [Eran's answer](https://stackoverflow.com/a/49401552/4405757).
If you don't want to limit the range, you could use a `BigInteger`
```
List bigIntegers = new Random().ints(10)
.mapToObj(i ->{
BigInteger intAsBigInteger = new BigInteger(String.valueOf(i));
return intAsBigInteger.multiply(intAsBigInteger);
})
.collect(Collectors.toList());
System.out.println(bigIntegers);
```
Upvotes: 0 |
2018/03/21 | 286 | 1,117 | <issue_start>username_0: I have a table `category`, `profile` and `employee_belongs_to`, where `employee_belongs_to` stores profile\_id and category\_id. The `profile` table stores all the employees details. `category` table stores different category like English, math,physics ...
I want to select only name from `profile` table to which profile\_id corresponds to particular category\_id in `employee_belongs_to` table.
How can i write the SQL statement?<issue_comment>username_1: You can join the tables and write query like shown below
```
SELECT *
FROM profile INNER JOIN employee_belongs_to ON employee_belongs_to.profileID = profile.ProfileID
INNER JOIN category ON category.categoryID = employee_belongs_to.categoryID
WHERE category.categoryID = @CategoryID
```
Upvotes: 1 <issue_comment>username_2: The following SQL statement worked for me:
```
SELECT profile.* FROM profile JOIN employee_belongs_to JOIN category ON employee_belongs_to.Profile_id=profile.Profile_id AND employee_belongs_to.Category_id=category.Category_id WHERE category.Category_id=?
```
Upvotes: 1 [selected_answer] |
2018/03/21 | 340 | 1,267 | <issue_start>username_0: I would like to know how to disable the browser cache, using HTML5.
I found this useful post ([How to control web page caching, across all browsers?](https://stackoverflow.com/questions/49547/how-to-control-web-page-caching-across-all-browsers/2068407)), but it contains the info only for HTML4 or other languages.
In my web application I use Java (**Spring Boot**) and **Thymeleaf** to produce HTML5.
I would like to understand what are the equivalent tags for HTML5, of the following HTML tags:
```
```
It's fine either through HTML5 tags, or even through a Java side solution.<issue_comment>username_1: You can join the tables and write query like shown below
```
SELECT *
FROM profile INNER JOIN employee_belongs_to ON employee_belongs_to.profileID = profile.ProfileID
INNER JOIN category ON category.categoryID = employee_belongs_to.categoryID
WHERE category.categoryID = @CategoryID
```
Upvotes: 1 <issue_comment>username_2: The following SQL statement worked for me:
```
SELECT profile.* FROM profile JOIN employee_belongs_to JOIN category ON employee_belongs_to.Profile_id=profile.Profile_id AND employee_belongs_to.Category_id=category.Category_id WHERE category.Category_id=?
```
Upvotes: 1 [selected_answer] |
2018/03/21 | 668 | 2,443 | <issue_start>username_0: I am using javascript code to select a option on body load as shown in the snippet. This works fine for me.
The issue i am facing in the next step is that i am not able to call onchange event dynamically as soon as the value gets selected in selectpicker.
Code what i have written to select the options dynamically
```
$('select[name=pname]').val(pnamea);
$('.selectpicker').selectpicker('refresh');
```
After this i am mapping a simple function addcname1 to onchange event which gives an alert of selected option. but this is not working for me.
Snippet has been provided which explain the problem statment more clearly.
Can you please guide me through where i am going wrong?
Thanks
```js
function openmd2(pnamea){
$('select[name=pname]').val(pnamea);
$('.selectpicker').selectpicker('refresh');
$(document).on('change','.selectpicker',function(){
addcname1(this.options[this.selectedIndex])
});
}
function addcname1(getval){
var myname = getval.getAttribute('value');
alert(myname)
}
```
```html
select
Mustard
Ketchup
Relish
```<issue_comment>username_1: It will not give you an alert. Understand it this way.
**1-** By default, you will have value 1 selected from the first two lines of your `function openmd2(pnamea)` which will be called on your `onLoad()`.
**2-** Now in the third line, it gets a call to monitor for the `onChange` event.
```
$(document).on('change','.selectpicker',function(){
addcname1(this.options[this.selectedIndex])
});
```
**3-** And hence moving forward, if you change the dropdown, you will get the alert. But not the first time (your `onload`) since there are no listeners waiting for its *change*.
AFAIK, its working like you wrote it.
Upvotes: 0 <issue_comment>username_2: In your code you have to do some small changes to make it running.
```
$(document).on('change','.selectpicker',function(){
addcname1(this.options[this.selectedIndex])
});
function openmd2(pnamea){
$('select[name=pname]').val(pnamea).change();
}
function addcname1(getval){
var myname = getval.getAttribute('value');
alert(myname)
}
```
Here I have just changed the $('select[name=pname]').val(pnamea) with $('select[name=pname]').val(pnamea).change(); to make it running
You can refer this like to get the exact answer
<https://jsfiddle.net/Sakshigargit15/j4ccdeaq/17/>
Upvotes: 2 |
2018/03/21 | 740 | 2,425 | <issue_start>username_0: in the select statement below I have 707 row
```
select detail_serial, Price from apa_invoice_detail
```
and I have another select statement which is
```
Select max(detail_serial)
,asc_item.item_name_2
,asc_group.group_name_2
From apa_invoice_detail
inner join asc_item on asc_item.item_id=apa_invoice_detail.item_id
inner join asc_group on asc_group.group_id=asc_item.group_id
Group by asc_item.item_name_2, asc_group.group_name_2
```
and this one gives me 197 row
I need to get the price from the first statement for the detail\_serial in the second statement (for only 197 row)
I tried this:
```
select detail_serial, Price from apa_invoice_detail where detail_serial in
(Select max(detail_serial)
,asc_item.item_name_2
,asc_group.group_name_2
From apa_invoice_detail
inner join asc_item on asc_item.item_id=apa_invoice_detail.item_id
inner join asc_group on asc_group.group_id=asc_item.group_id
Group by asc_item.item_name_2, asc_group.group_name_2)
```
but it gives me "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS."
How can I solve this ???<issue_comment>username_1: try removing the columns in the inner select statement
```
select detail_serial, Price from apa_invoice_detail where detail_serial in
(Select max(detail_serial)
From apa_invoice_detail
inner join asc_item on asc_item.item_id=apa_invoice_detail.item_id
inner join asc_group on asc_group.group_id=asc_item.group_id
Group by asc_item.item_name_2, asc_group.group_name_2)
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Use `EXISTS` instead of `IN`.
```
;WITH SecondQueryResults AS
(
Select max(detail_serial) detail_serial
, asc_item.item_name_2
, asc_group.group_name_2
From apa_invoice_detail
inner join asc_item on asc_item.item_id=apa_invoice_detail.item_id
inner join asc_group on asc_group.group_id=asc_item.group_id
Group by asc_item.item_name_2, asc_group.group_name_2
)
select
detail_serial,
Price
from
apa_invoice_detail T
where
EXISTS (SELECT 'serial exists on query result' FROM SecondQueryResults AS S WHERE S.detail_serial = T.detail_serial)
```
... or just select 1 column (the `detail_serial`) inside your `IN` subquery.
Upvotes: 0 |
2018/03/21 | 804 | 2,315 | <issue_start>username_0: I have GoCD instance and want to automate regular actions like scheduling pipelines and checking pipelines statuses using GoCD API.
When I do GET request it works:
```
curl 'https://gocd.demo.kagarlickij.com/go/api/pipelines/frankenstein/status' \
-u 'kagarlickij:Pa$$w0rd' | jq
```
[](https://i.stack.imgur.com/pVra9.png)
..but when I do POST request it returns "The resource you requested was not found!":
```
curl 'https://gocd.demo.kagarlickij.com/go/api/pipelines/frankenstein/pause' \
-u 'kagarlickij:Pa$$w0rd' \
-H 'Accept: application/vnd.go.cd.v1+json' -H 'Content-Type: application/json' \
-X POST -d '{"pause_cause": "Investigating build failures"}' | jq
```
[](https://i.stack.imgur.com/Bwag3.png)
..another POST example:
```
curl 'https://gocd.demo.kagarlickij.com/go/api/pipelines/frankenstein/schedule' \
-u 'kagarlickij:P@$$w0rd' \
-H 'Accept: application/vnd.go.cd.v1+json' -H 'Content-Type: application/json' \
-X POST -d @gocd.json | jq
```
json content:
```
{
"environment_variables": {},
"materials": {},
"update_materials_before_scheduling": false
}
```
[](https://i.stack.imgur.com/2VPoo.png)
Any ideas how pipelines could be started using API?<issue_comment>username_1: Some GoCD API calls [require](https://github.com/username_1/yagocd/blob/master/yagocd/resources/pipeline.py#L217-L234) `'Confirm': 'true'` header.
In you case, you can try running curl like this:
`curl 'https://gocd.demo.username_2.com/go/api/pipelines/frankenstein/pause' \
-u 'username_2:<PASSWORD>' \
-H 'Accept: application/vnd.go.cd.v1+json' \
-H 'Content-Type: application/json' \
-H 'Confirm: true' \
-X POST -d '{"pause_cause": "Investigating build failures"}' | jq`
I can recommend my lib [yagocd](https://github.com/username_1/yagocd) for GoCD, which takes cares about version incompatibilities and makes working with GoCD API much easier.
Upvotes: 1 <issue_comment>username_2: The answer turned out to be very simple - that API actions require GoCD v18.2.0 but I had v18.0.0
After upgrade API calls work as expected
Upvotes: 1 [selected_answer] |
2018/03/21 | 410 | 1,421 | <issue_start>username_0: Suppose the following code.
```
try:
some_code_1
except: # will it be called twice, if an error occures in finally?
some_code_2
finally:
some_code_3
```
Suppose an exception occurs in `some_code_3`. Do I need an extra try-except clause around `some_code_3` (see below) or will the exception with `some_code_2` be called again, which in principle could cause an infinite loop?
Is this saver?
```
try:
some_code_1
except: # will it be called twice, if an error occures in finally?
some_code_2
finally:
try:
some_code_3
except:
pass
```<issue_comment>username_1: python doesn't go back in the execution flow, but rather statement by statement.
By the time it reaches `finally`, if an error is thrown there, it needs yet another handle
Upvotes: 2 <issue_comment>username_2: Just give it a try:
```
try:
print(abc) #Will raise NameError
except:
print("In exception")
finally:
print(xyz) #Will raise NameError
Output:
In exception
Traceback (most recent call last):
File "Z:/test/test.py", line 7, in
print(xyz)
NameError: name 'xyz' is not defined
```
So no, it doesn't end up in an infinite loop
Upvotes: 3 [selected_answer]<issue_comment>username_3: The **finally** in your sample code will not catch exception from some\_code\_3.
whether it's needed to catch exception from some\_code\_3 depends on your design.
Upvotes: 2 |
2018/03/21 | 2,035 | 7,624 | <issue_start>username_0: i know its a duplicate question for so many fellows but i have tried all possible solutions which were given by community members but none of them helped me so i am posting this question as i am stuck with this error.I urge all the members please look at my code before marking it as duplicate.
i am using the recyclerview inside a fragment.
this is my fragment class:-
```
public class BuyOrders extends Fragment {
private Boolean isConnected = true;
private Socket mSocket;
LinearLayoutManager mLinearLayoutManager;
private RecyclerView mRecyclerView;
private ArrayList mMessages = new ArrayList();
private RecyclerView.Adapter mAdapter;
private static final String TAG = "BuyOrderHistoryFragment";
public BuyOrders() {
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
mAdapter = new BuyOrderHistoryAdapter(mMessages, context);
if (context instanceof Activity) {
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
AppController app = (AppController) getActivity().getApplication();
mSocket = app.getSocket();
mSocket.connect();
mSocket.on(Socket.EVENT\_CONNECT, onConnect);
mSocket.on(Socket.EVENT\_DISCONNECT, onDisconnect);
mSocket.on(Socket.EVENT\_CONNECT\_ERROR, onConnectError);
mSocket.on(Socket.EVENT\_CONNECT\_TIMEOUT, onConnectError);
mSocket.on("connection\_successfull", onConnect);
mSocket.on("buy\_orders\_data", onBuyOrdersData);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragments\_buyorders, container, false);
return v;
}
@Override
public void onDestroy() {
super.onDestroy();
mSocket.off(Socket.EVENT\_CONNECT, onConnect);
mSocket.off(Socket.EVENT\_DISCONNECT, onDisconnect);
mSocket.off(Socket.EVENT\_CONNECT\_ERROR, onConnectError);
mSocket.off(Socket.EVENT\_CONNECT\_TIMEOUT, onConnectError);
mSocket.off("connection\_successfull", onConnect);
mSocket.off("buy\_orders\_data", onBuyOrdersData);
mSocket.disconnect();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mLinearLayoutManager = new LinearLayoutManager(getActivity());
mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView = (RecyclerView) view.findViewById(R.id.rv\_buyorder);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
private Emitter.Listener onConnect = new Emitter.Listener() {
@Override
public void call(Object... args) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (!isConnected) {
JSONObject data = (JSONObject)args[0];
Log.d(TAG, String.valueOf(data));
mSocket.emit("fetch\_buy\_orders",sendFetchBuyOrderRequest(""));
Log.i(TAG, "connected");
Toast.makeText(getActivity().getApplicationContext(),
R.string.connect, Toast.LENGTH\_LONG).show();
isConnected = true;
}
}
});
}
};
protected String sendFetchBuyOrderRequest(String s) {
String pageno = "1";
String recordperpage = "10";
String userid = "22";
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("page\_no:", pageno );
jsonObject.put("records\_per\_page", recordperpage);
jsonObject.put("user\_id:", userid);
return jsonObject.toString();
}catch (Exception e){
e.printStackTrace();
}
return s;
}
private Emitter.Listener onBuyOrdersData = new Emitter.Listener() {
@Override
public void call(final Object... args) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
JSONObject data = (JSONObject) args[0];
Log.v("Data Coming From Server", String.valueOf(data));
String volume;
String bid;
String total;
try {
volume = data.getString("volume");
bid = data.getString("bid");
total = data.getString("total");
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
return;
}
addData(volume,bid,total);
}
});
}
};
protected void addData(String volume, String bid, String total){
mMessages.add(new BuyOrderHistory.Builder(BuyOrderHistory.RECEIVER)
.volume(volume).bid(bid).total(total).build());
mAdapter.notifyItemInserted(mMessages.size() - 1);
scrollToBottom();
}
private void scrollToBottom() {
mRecyclerView.scrollToPosition(mAdapter.getItemCount() - 1);
}
protected Emitter.Listener onDisconnect = new Emitter.Listener() {
@Override
public void call(Object... args) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Log.i(TAG, "disconnected");
isConnected = false;
Toast.makeText(getActivity().getApplicationContext(),
R.string.disconnect, Toast.LENGTH\_LONG).show();
}
});
}
};
protected Emitter.Listener onConnectError = new Emitter.Listener() {
@Override
public void call(Object... args) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Log.e(TAG, "Error connecting");
Toast.makeText(getActivity().getApplicationContext(),
R.string.error\_connect, Toast.LENGTH\_LONG).show();
}
});
}
};
}
```
Below is my Adapter class:-
```
public class BuyOrderHistoryAdapter extends RecyclerView.Adapter{
ArrayList arrayList;
Context context;
private int RECEIVER = BuyOrderHistory.RECEIVER;
public BuyOrderHistoryAdapter(ArrayList arrayList,Context context){
this.arrayList = arrayList;
this.context = context;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = null;
RecyclerView.ViewHolder vh = null;
if (viewType == RECEIVER){
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list\_buyorders, parent,false);
vh = new ReceivedDataHolder(v);
}
return vh;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder.getItemViewType() == RECEIVER){
((ReceivedDataHolder)holder).volume.setText(arrayList.get(position).getmVolume());
((ReceivedDataHolder)holder).bid.setText(arrayList.get(position).getmBid());
((ReceivedDataHolder)holder).total.setText(arrayList.get(position).getmTotal());
}
}
@Override
public int getItemCount() {
return arrayList == null ? 0 : arrayList.size();
}
@Override
public int getItemViewType(int position) {
if(arrayList.get(position).getmType() == RECEIVER){
}
return RECEIVER;
}
private class ReceivedDataHolder extends RecyclerView.ViewHolder{
public TextView volume, bid, total;
public ReceivedDataHolder(View itemView) {
super(itemView);
volume = (TextView) itemView.findViewById(R.id.tv\_buyvolume);
bid = (TextView) itemView.findViewById(R.id.tv\_buybid);
total = (TextView) itemView.findViewById(R.id.tv\_buytotal);
}
}
```<issue_comment>username_1: python doesn't go back in the execution flow, but rather statement by statement.
By the time it reaches `finally`, if an error is thrown there, it needs yet another handle
Upvotes: 2 <issue_comment>username_2: Just give it a try:
```
try:
print(abc) #Will raise NameError
except:
print("In exception")
finally:
print(xyz) #Will raise NameError
Output:
In exception
Traceback (most recent call last):
File "Z:/test/test.py", line 7, in
print(xyz)
NameError: name 'xyz' is not defined
```
So no, it doesn't end up in an infinite loop
Upvotes: 3 [selected_answer]<issue_comment>username_3: The **finally** in your sample code will not catch exception from some\_code\_3.
whether it's needed to catch exception from some\_code\_3 depends on your design.
Upvotes: 2 |
2018/03/21 | 1,225 | 3,429 | <issue_start>username_0: I've joined up my tables such that every entry is unique and I want to get a COUNT() value for how many unique courses the teachers teach. I figured I would make a table of distinct courses then do a count based on the teacher's id, however this doesn't account for teachers who taught no courses and I wish to return a zero value in this case. How do I go about getting these zero values?
Table for reference:
```
id | name | course_id | sec_id | semester | year
-------+------------+-----------+--------+----------+------
33456 | A | | | |
10101 | B | CS-101 | 1 | Fall | 2009
76766 | C | BIO-301 | 1 | Summer | 2010
12121 | D | FIN-201 | 1 | Spring | 2010
10101 | B | CS-347 | 1 | Fall | 2009
76543 | E | | | |
83821 | F | CS-319 | 2 | Spring | 2010
83821 | F | CS-190 | 2 | Spring | 2009
98345 | G | EE-181 | 1 | Spring | 2009
10101 | B | CS-315 | 1 | Spring | 2010
22222 | H | PHY-101 | 1 | Fall | 2009
45565 | I | CS-101 | 1 | Spring | 2010
15151 | J | MU-199 | 1 | Spring | 2010
32343 | K | HIS-351 | 1 | Spring | 2010
83821 | F | CS-190 | 1 | Spring | 2009
45565 | I | CS-319 | 1 | Spring | 2010
76766 | C | BIO-101 | 1 | Summer | 2009
58583 | L | | | |
```
ps. I believe I am using PostgreSQL.
[EDIT] the expected result is a table of id's, names, and a number showing the amount of courses the teacher has taught, including 0 if they have not taught any course.
[EDIT 2] I only need a query on **this** table, all the other work is done. If there is no value for course\_id, sec\_id, semester, year then that teacher has **not** taught a course (in the case of teachers A, E, and L; who would have a count of 0). I only need a way to count these courses, nothing else.<issue_comment>username_1: I believe, this query should do the job:
SELECT COUNT(DISTINCT course\_id), t.id, name FROM courses r Right Outer JOIN teachers t ON (r.id=t.id) group by t.id, name;
I assumed, that not all teachers where in the table you have provided, thus the need for the Outer Join. Tested on similar database on Oracle.
Upvotes: 0 <issue_comment>username_2: Do the `join`s with `subquery` to find the teachers course count
```
select t.name, coalesce(c.course_count, 0) course_count
from table t left join (
select name, count(distinct course _id) course_count
from table
group by name
) c on c. name = t.name
group by t.name
```
Upvotes: 0 <issue_comment>username_3: let's assume the table name is t:
```
select distinct count(course_id) filter (where course_id is not null) over (partition by id,name),id, name
from t
order by name;
count | id | name
-------+-------+--------------
0 | 33456 | A
3 | 10101 | B
2 | 76766 | C
1 | 12121 | D
0 | 76543 | E
3 | 83821 | F
1 | 98345 | G
1 | 22222 | H
2 | 45565 | I
1 | 15151 | J
1 | 32343 | K
0 | 58583 | L
(12 rows)
```
<https://www.postgresql.org/docs/current/static/sql-expressions.html>
Upvotes: 2 [selected_answer] |
2018/03/21 | 660 | 2,109 | <issue_start>username_0: Have this weird case when my images are being found in sources, linked correctly, src url is okay, but still not being displayed. Other images in that same folder are being loaded and displayed just fine, but my new uploaded images are not. I'm using open cart and upload images via ftp. Permissions are fine 644 like the others. I asked other developers in my team and no one has any clue why is that. Guys tried downlaoding and opening the image on their computer and can't even open it, whereas I'm using MAC and can open the same images on my computer without any problems. Images are saved as .jpg from Photoshop. What's the deal here? Here is how it looks in Mozilla:
[](https://i.stack.imgur.com/HgvZn.png)<issue_comment>username_1: I believe, this query should do the job:
SELECT COUNT(DISTINCT course\_id), t.id, name FROM courses r Right Outer JOIN teachers t ON (r.id=t.id) group by t.id, name;
I assumed, that not all teachers where in the table you have provided, thus the need for the Outer Join. Tested on similar database on Oracle.
Upvotes: 0 <issue_comment>username_2: Do the `join`s with `subquery` to find the teachers course count
```
select t.name, coalesce(c.course_count, 0) course_count
from table t left join (
select name, count(distinct course _id) course_count
from table
group by name
) c on c. name = t.name
group by t.name
```
Upvotes: 0 <issue_comment>username_3: let's assume the table name is t:
```
select distinct count(course_id) filter (where course_id is not null) over (partition by id,name),id, name
from t
order by name;
count | id | name
-------+-------+--------------
0 | 33456 | A
3 | 10101 | B
2 | 76766 | C
1 | 12121 | D
0 | 76543 | E
3 | 83821 | F
1 | 98345 | G
1 | 22222 | H
2 | 45565 | I
1 | 15151 | J
1 | 32343 | K
0 | 58583 | L
(12 rows)
```
<https://www.postgresql.org/docs/current/static/sql-expressions.html>
Upvotes: 2 [selected_answer] |
2018/03/21 | 631 | 1,971 | <issue_start>username_0: After publishing my MVC app, my website is giving me this error:
>
> Server Error in '/' Application.
>
> CREATE DATABASE permission denied in database 'master'.
>
>
>
I have added the connection string, both in the web.config file and in the ASP.NET settings on the domain, this is the connection string:
```
Data Source=.;Initial Catalog=ADB;Integrated Security=True;User ID=MVCU;Password=<PASSWORD>
```
I have created a database in the domain's server, with the same Username and Password as it is in the connection string above.
The database itself only has the default login/registration tables, that MVC creates automatically.<issue_comment>username_1: I believe, this query should do the job:
SELECT COUNT(DISTINCT course\_id), t.id, name FROM courses r Right Outer JOIN teachers t ON (r.id=t.id) group by t.id, name;
I assumed, that not all teachers where in the table you have provided, thus the need for the Outer Join. Tested on similar database on Oracle.
Upvotes: 0 <issue_comment>username_2: Do the `join`s with `subquery` to find the teachers course count
```
select t.name, coalesce(c.course_count, 0) course_count
from table t left join (
select name, count(distinct course _id) course_count
from table
group by name
) c on c. name = t.name
group by t.name
```
Upvotes: 0 <issue_comment>username_3: let's assume the table name is t:
```
select distinct count(course_id) filter (where course_id is not null) over (partition by id,name),id, name
from t
order by name;
count | id | name
-------+-------+--------------
0 | 33456 | A
3 | 10101 | B
2 | 76766 | C
1 | 12121 | D
0 | 76543 | E
3 | 83821 | F
1 | 98345 | G
1 | 22222 | H
2 | 45565 | I
1 | 15151 | J
1 | 32343 | K
0 | 58583 | L
(12 rows)
```
<https://www.postgresql.org/docs/current/static/sql-expressions.html>
Upvotes: 2 [selected_answer] |
2018/03/21 | 360 | 951 | <issue_start>username_0: I'd like to get the two lasts octets from an IP address with PHP.
I tried this :
```
substr(strrchr($ip,'.'),2);
```
But it seems I misunderstood the code, since it's not working... (eg. if my IP is 192.168.0.79, this line returns only "9"...)<issue_comment>username_1: Using your solution, just change `2` with `1`:
```
substr(strrchr($ip,'.'),1); // Output 79
```
Upvotes: 2 <issue_comment>username_2: you can [explode](http://php.net/manual/tr/function.explode.php) the ip string and get the parts from it.
```
$ip = "192.168.0.79";
$split = explode(".", $ip);
$part1 = $split[2]; // 0
$part2 = $split[3];// 79
```
Upvotes: 4 [selected_answer]<issue_comment>username_3: If you want last part as **string**, use `explode` with 3rd parameter:
```
$parts = explode('.', '192.168.0.79', 3);
echo $parts[2]; // "0.79"
// or even:
echo explode('.', '192.168.0.79', 3)[2]; // "0.79"
```
Upvotes: 2 |
2018/03/21 | 396 | 1,479 | <issue_start>username_0: I have a legacy code, for which the complexity of the code is higher than 20. My pipelines are failing due to this fact. This is the exact error message from the pipelines:
```
Function's cyclomatic complexity (36) exceeds allowed maximum of 20
```
I don't have the time to refactor the code so, I am looking for a temporary solution like suppressing/ignoring my file:
I tried to use these:
```
* @SuppressWarnings(PHPMD)
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.LongVariable)
* @SuppressWarnings(PHPMD.UnusedLocalVariable)
```
or
```
// @codingStandardsIgnoreStart
my code here
// @codingStandardsIgnoreEnd
```
I also followed this [article](https://phpmd.org/rules/codesize.html) , but my pipelines are still failing. Have you ever faced such an issue before ? Do you have any idea how to fix this, **without** changing my pipelines settings/configurations?<issue_comment>username_1: The OP did not mention whether the error came from PHPCS or PHPMD. If it's coming from PHPCS, then this doc comment line will suppress the warning:
`* phpcs:disable Generic.Metrics.CyclomaticComplexity`
Upvotes: 1 <issue_comment>username_2: I get the same warning as OP and I'm sure that it comes from PHPMD.
To suppress it I use PhpDoc comment before method:
```
/**
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function myComplexMethod(...)
```
Upvotes: 0 |
2018/03/21 | 212 | 819 | <issue_start>username_0: i have a hybrid app. I used web-view to make a android hybrid app. I also have a native menubar above the webview. My question is, How can i disable the native menu from my web application? Is it possible? If yes please share your thoughts on this<issue_comment>username_1: The OP did not mention whether the error came from PHPCS or PHPMD. If it's coming from PHPCS, then this doc comment line will suppress the warning:
`* phpcs:disable Generic.Metrics.CyclomaticComplexity`
Upvotes: 1 <issue_comment>username_2: I get the same warning as OP and I'm sure that it comes from PHPMD.
To suppress it I use PhpDoc comment before method:
```
/**
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function myComplexMethod(...)
```
Upvotes: 0 |
2018/03/21 | 247 | 910 | <issue_start>username_0: I have selector like follow:
```
$('#codes-datatable tbody').on('click', 'tr', function () {});
```
And I would like not to have buttons triggering this selector.
For example. I have inside the table a button:
```
Button
```
I've tried already many combination with `.not('.btn')` and `:not(.btn)` but none worked out.
Please help.<issue_comment>username_1: The OP did not mention whether the error came from PHPCS or PHPMD. If it's coming from PHPCS, then this doc comment line will suppress the warning:
`* phpcs:disable Generic.Metrics.CyclomaticComplexity`
Upvotes: 1 <issue_comment>username_2: I get the same warning as OP and I'm sure that it comes from PHPMD.
To suppress it I use PhpDoc comment before method:
```
/**
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function myComplexMethod(...)
```
Upvotes: 0 |
2018/03/21 | 275 | 735 | <issue_start>username_0: how to convert string time to date object
```
var time_t = "09:56 AM" ;
this.audit_time = new Date(time_t);
//Error Invalid date
```
how do i correct it.please help me to solve this<issue_comment>username_1: try this
```js
var time_t = "09:56 AM";
var timeArr = time_t.replace(" AM", "").split(":");
var d = new Date();
d.setMinutes(timeArr[1]);
d.setHours(timeArr[0]);
console.log(d);
```
Upvotes: 0 <issue_comment>username_2: You need also date part in your string (this will also work with PM):
```js
var time_t = "09:56 AM" ;
var dt = new Date("1990-01-01 "+time_t);
console.log(dt);
dt = new Date(new Date().toISOString().slice(0,10) + " " + time_t);
console.log(dt);
```
Upvotes: 2 |
2018/03/21 | 234 | 648 | <issue_start>username_0: It is successful to use the command 'git push origin tagname', but The tag isn't displayed in remote<issue_comment>username_1: try this
```js
var time_t = "09:56 AM";
var timeArr = time_t.replace(" AM", "").split(":");
var d = new Date();
d.setMinutes(timeArr[1]);
d.setHours(timeArr[0]);
console.log(d);
```
Upvotes: 0 <issue_comment>username_2: You need also date part in your string (this will also work with PM):
```js
var time_t = "09:56 AM" ;
var dt = new Date("1990-01-01 "+time_t);
console.log(dt);
dt = new Date(new Date().toISOString().slice(0,10) + " " + time_t);
console.log(dt);
```
Upvotes: 2 |
2018/03/21 | 383 | 1,340 | <issue_start>username_0: I have two custom components called Grid and FieldValue and I use the FieldValue component multiple times on a particular page. I am using a class name called `.black` for all the FieldValue components. Now, I want to use a different class name called `.blue-pointer` where the data in FieldValue says view2. please help me understand how to do it.
Components on the page look like below
```
```
And the FieldValue is defined as below,
```
class FieldValue extends React.Component<>{
render(){
{'testView'}
}
}
```
And the CSS is defined as below
```
.black{
color:#4d546d;
}
.blue-pointer {
color: #0070d2;
cursor: pointer;
}
```<issue_comment>username_1: Use `props` from your component :
```
class FieldValue extends React.Component{
render() {
return (
{'testView'}
);
}
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can define `className` as a `prop`, and give it a default value of `'black'`.
```
class FieldValue extends React.Component<> {
static defaultProps = {
className: 'black'
}
render() {
const { className } = this.props
{'testView'}
}
}
```
For the default case, you don't need to change anything:
```
// Still uses the `black` style.
```
When you want to change the class name, use:
```
```
Upvotes: 0 |
2018/03/21 | 271 | 894 | <issue_start>username_0: I am fetching data from one tag lets say 111 22222 and splitting by using space
like 111 and 22222.
I want to transfer the value to two different tags into different request
lets say
111 for Tag1 and 22222 for Tag2<issue_comment>username_1: Use `props` from your component :
```
class FieldValue extends React.Component{
render() {
return (
{'testView'}
);
}
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can define `className` as a `prop`, and give it a default value of `'black'`.
```
class FieldValue extends React.Component<> {
static defaultProps = {
className: 'black'
}
render() {
const { className } = this.props
{'testView'}
}
}
```
For the default case, you don't need to change anything:
```
// Still uses the `black` style.
```
When you want to change the class name, use:
```
```
Upvotes: 0 |
2018/03/21 | 1,259 | 3,836 | <issue_start>username_0: I have a textbox that contains data separated by commas See pictures:
[](https://i.stack.imgur.com/gTlzZ.png)
and a button to add data.
The data is comma-separated: E013-007,E013-021,E013-022,E013-048,E013-049,V039-034
I need help to insert data from that textbox into SQL using C#.
Data in Sql by line:
>
> E013-007
>
>
> E013-021
>
>
> E013-022
>
>
> ...
>
>
>
I have the code but it does not work:
```
SqlConnection con = new SqlConnection(DbConnect.ConnectStr);
SqlCommand cmd = new SqlCommand("multiple", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
con.Open();
if (txtKMH.Text.Contains(","))//checking for you are entered single value or multiple values
{
string[] arryval = txtKMH.Text.Split(',');//split values with ‘,’
int j = arryval.Length;
int i = 0;
for (i = 0; i < j; i++)
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@Main_KMH", arryval[j]);
cmd.Parameters.AddWithValue("@Main_Date", txtNgay.Text);
cmd.ExecuteNonQuery();
}
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "alert('Thành công!')");
}
con.Close();
```
Sql:
```
USE [Database]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[multiple] @Main_KMH nvarchar(50),@Main_Date DateTime
AS
Begin
insert into MainVotes(Main_KMH,Main_Date) values(@Main_KMH,@Main_Date);
End
```<issue_comment>username_1: Pass the comma seperated string as nvarchar(max) parameter to sql server. Then handle this to convert that to rows and use it insert. You can create a function for this.
Something like:
```
CREATE FUNCTION dbo.BreakRows (@CommadelimitedString varchar(1000))
RETURNS @Result TABLE (Column1 VARCHAR(100))
AS
BEGIN
DECLARE @IntLocation INT
WHILE (CHARINDEX(',', @CommadelimitedString, 0) > 0)
BEGIN
SET @IntLocation = CHARINDEX(',', @CommadelimitedString, 0)
INSERT INTO @Result (Column1)
--LTRIM and RTRIM to ensure blank spaces are removed
SELECT RTRIM(LTRIM(SUBSTRING(@CommadelimitedString, 0, @IntLocation)))
SET @CommadelimitedString = STUFF(@CommadelimitedString, 1, @IntLocation, '')
END
INSERT INTO @Result (Column1)
SELECT RTRIM(LTRIM(@CommadelimitedString))--LTRIM and RTRIM to ensure blank spaces are removed
RETURN
END
GO
```
Source [here](https://www.databasejournal.com/features/mssql/converting-comma-separated-value-to-rows-and-vice-versa-in-sql-server.html)
Now use this in your stored proc:
```
SELECT * FROM dbo.BreakStringIntoRows('Apple,Banana,Orange')
```
You will have to change this code a bit. But the idea can be used to achieve what you are trying to do
Upvotes: 3 [selected_answer]<issue_comment>username_2: We can create a function to split given comma separated string in to line by line using XMl and SPlit()
```
CREATE FUNCTION [dbo].[udf_GetUnsplitData]
(
@string nvarchar(max)
)
RETURNS @OutTable TABLE
(
DATA varchar(20)
)
AS
BEGIN
DECLARE @Temp AS TABLE
(
DATA nvarchar(max)
)
INSERT INTO @Temp
SELECT @string
INSERT INTO @OutTable
SELECT
Split.a.value('.','nvarchar(1000)') As DATA
FROM
(
SELECT
CAST('~~'+REPLACE(DATA,',','~~~~')+'~~' AS XML ) AS DATA
FROM @Temp
)A
CROSS APPLY DATA.nodes('S') AS Split(a)
RETURN
END
GO
SELECT [dbo].[udf_GetUnsplitData]('E013-007,E013-021,E013-022,E013-048,E013-049,V039-034')
```
RESULT
```
DATA
--------
E013-007
E013-021
E013-022
E013-048
E013-049
V039-034
```
Upvotes: 0 |
2018/03/21 | 1,313 | 4,363 | <issue_start>username_0: I'd like to modify part of the text in a textarea with Selenium. The textarea seems almost as if it were read-only.
In this very simple example using a sample algo, it would be great to be able to change the stock id on this line:
```
context.aapl = sid(24)
```
... to something like:
```
context.aapl = sid(39840)
```
... which is the Tesla stock id. The variable name will no longer make sense, doesn't matter, just a start.
This Selenium code for me is able to open the sample with no login required.
```
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
t = webdriver.Firefox() # t stands for tab as in browser tab in my mind
t.implicitly_wait(10)
t.get('https://www.quantopian.com/algorithms/')
o = t.find_element_by_xpath("//body") # o stands for object
o.send_keys(Keys.ESCAPE) # clearing the popup
o = t.find_element_by_link_text("Hello World Algorithm")
o.click()
''' for the fun of it if you want to run the backtest
o = t.find_element_by_xpath('//body')
o.send_keys(Keys.CONTROL + 'b')
o.send_keys(Keys.ESCAPE)
'''
print t.find_element_by_id('code-area').text
```
Here's the output from that
```
1
# Called once at the start of the simulation.
2
def initialize(context):
3
# Reference to the AAPL security.
4
context.aapl = sid(24)
5
6
# Rebalance every day, one hour and a half after market open.
7
schedule_function(my_rebalance,
8
date_rules.every_day(),
9
time_rules.market_open(hours=1, minutes=30))
10
11
# This function was scheduled to run once per day at 11AM ET.
12
def my_rebalance(context, data):
13
14
# Take a 100% long position in AAPL. Readjusts each day to
15
# account for price fluctuations.
16
if data.can_trade(context.aapl):
17
order_target_percent(context.aapl, 1.00)
```
That id is 'code-area'. The content includes margin numbers which might be a problem.
Next nested area is 'code-area-internal', seems the same.
Followed by these two.
```
```
In trying to obtain the content of the algorithm with 'codebox', content doesn't appear to be present, just u'' ...
```
>>> p = t.find_element_by_id('codebox').text
>>> p
u''
```
Attempt to do CTRL-A on it results in this exception...
```
>>> o = t.find_element_by_id('codebox')
>>> o.send_keys(Keys.CONTROL + 'a')
```
**ElementNotInteractableException: Message: Element is not reachable by keyboard**
If the text can be completely cut, then replace can done in Python and paste, that would be fine.
I wouldn't expect Selenium to be able to find and replace text, just surprised it finds a visible area for user input to be off limits from interactivity.
That textarea does have its own Find, and hoping won't have to resort to trying to use it as a workaround.
*(The environment is an online IDE for stock market algorithms called Quantopian)*
This is the one other thing I tried, with no apparent effect:
```
>>> t.execute_script("arguments[0].value = arguments[1]", t.find_element_by_id("ide-container"), "_new_")
```
Appreciate any pointers.<issue_comment>username_1: Textarea has `style="display: none"` attribute which means that you cannot get its content with `text` property. In this case you can use:
```
p = t.find_element_by_id('codebox').get_attribute("textContent")
```
To set new value to code field you can use:
```
field = driver.find_element_by_css_selector('div[role="presentation"]')
driver.execute_script("arguments[0].textContent = 'New value';", field)
```
But note that initially each code line in code field displayed as separate `div` node with specific value and styles. So to make new value looks exactly as code (in the same formatting) you can prepare HTML sample e.g.
```
value = """1
```line
# Comment for new code.
```
"""
```
and do
```
driver.execute_script("arguments[0].innerHTML = arguments[1];", field, value)
```
Upvotes: 3 <issue_comment>username_2: The content of the algorithm with **codebox** which you are trying to extract is having the *style* attribute set to **display: none;**. So to extract the text you can use the following lines of code :
```
p = t.find_element_by_xpath("//div[@class='ide-container']/textarea[@id='codebox']")
t.execute_script("arguments[0].removeAttribute('style')", p)
print(t.get_attribute("innerHTML"))
```
Upvotes: 2 |
2018/03/21 | 556 | 1,918 | <issue_start>username_0: [](https://i.stack.imgur.com/wzIp3.png)
I want to make the gradient area swipe-able (down to show, swipe up to hide).
this is my code :
```
val scopeLayout = inflaterView.findViewById(R.id.scope\_layout)
scopeLayout.setOnTouchListener({ v, event ->
when (event.action) {
MotionEvent.ACTION\_DOWN ->
Toast.makeText(context, "you just touch the screen :-)", Toast.LENGTH\_SHORT).show()
scopeLayout.height = 215 // error val cannot be reassigned
}
true
})
```
and I got the error `val cannot be reassigned`. and how to set the height with `dp` value?<issue_comment>username_1: Textarea has `style="display: none"` attribute which means that you cannot get its content with `text` property. In this case you can use:
```
p = t.find_element_by_id('codebox').get_attribute("textContent")
```
To set new value to code field you can use:
```
field = driver.find_element_by_css_selector('div[role="presentation"]')
driver.execute_script("arguments[0].textContent = 'New value';", field)
```
But note that initially each code line in code field displayed as separate `div` node with specific value and styles. So to make new value looks exactly as code (in the same formatting) you can prepare HTML sample e.g.
```
value = """1
```line
# Comment for new code.
```
"""
```
and do
```
driver.execute_script("arguments[0].innerHTML = arguments[1];", field, value)
```
Upvotes: 3 <issue_comment>username_2: The content of the algorithm with **codebox** which you are trying to extract is having the *style* attribute set to **display: none;**. So to extract the text you can use the following lines of code :
```
p = t.find_element_by_xpath("//div[@class='ide-container']/textarea[@id='codebox']")
t.execute_script("arguments[0].removeAttribute('style')", p)
print(t.get_attribute("innerHTML"))
```
Upvotes: 2 |
2018/03/21 | 382 | 1,548 | <issue_start>username_0: My issue is simple. I have a class that manages all my viewcontroller to viewcontroller transition animations, and it takes classes from a protocol, because I want to make it portable and I usually make a baseviewcontroller with project-specific stuff.
The protocol is something like this:
```
protocol AnimatedViewController {
var view: UIView { get set }
func animateViews()
}
```
But when I let a `UIViewController` inherit from this, I get errors that `view` is not defined. When I define it, it tells me that it's already defined.
How can I have `view` defined in my protocol and have it be the `view` already defined in `UIViewController`?
PS: Don't really know how to name the title, so edits are welcome.<issue_comment>username_1: `view` in `UIViewController` is a force unwrapped `UIView`, so just define your protocol as this:
```
protocol AnimatedViewController {
var view: UIView! { get set }
func animateViews()
}
```
And `view` from `UIViewController` will be used to satisfy the requirement of this protocol.
E.g.:
```
class MyController: UIViewController, AnimatedViewController {
func animateViews() {
// do your stuff
}
}
```
Upvotes: 1 <issue_comment>username_2: You can use where clause in your protocol and you don't need `view` property.
```
protocol AnimatedViewController where Self:UIViewController {
func animateViews()
}
class TVC : UIViewController, AnimatedViewController {
func animateViews() {
}
}
```
Upvotes: 3 [selected_answer] |
2018/03/21 | 316 | 1,283 | <issue_start>username_0: I am developing an intranet portal with spring mvc and jsp.
The problem: in a jsp page, I list objects. At the click of a button, I would like to open a modal window (bootstrap) with a modification form of this object with its old information. But I can not understand the logic / technique
to implement to achieve this. I spent a lot of time searching in the internet, but I didn't find any useful solution. Could someone give me an idea to solve this problem?<issue_comment>username_1: `view` in `UIViewController` is a force unwrapped `UIView`, so just define your protocol as this:
```
protocol AnimatedViewController {
var view: UIView! { get set }
func animateViews()
}
```
And `view` from `UIViewController` will be used to satisfy the requirement of this protocol.
E.g.:
```
class MyController: UIViewController, AnimatedViewController {
func animateViews() {
// do your stuff
}
}
```
Upvotes: 1 <issue_comment>username_2: You can use where clause in your protocol and you don't need `view` property.
```
protocol AnimatedViewController where Self:UIViewController {
func animateViews()
}
class TVC : UIViewController, AnimatedViewController {
func animateViews() {
}
}
```
Upvotes: 3 [selected_answer] |
2018/03/21 | 467 | 1,709 | <issue_start>username_0: I want to get all available keys of an union type.
```
interface Foo {
foo: string;
}
interface Bar {
bar: string;
}
type Batz = Foo | Bar;
type AvailableKeys = keyof Batz;
```
I want to have `'foo' | 'bar'` as result of `AvailableKeys` but it is `never` (as alternative I could do `keyof (Foo & Bar)`, what produces exact the required type but I want to avoid to repeat the Types).
I found already the issue [`keyof` union type should produce union of keys](https://github.com/Microsoft/TypeScript/issues/12948) at github. I understand the answer, that `keyof UnionType` should not produce all possible keys.
So my question is: Is there an other way to get the list of all possible keys (it is ok if the verison 2.8 of tsc is required)?<issue_comment>username_1: Instead of a union type, you need an intersection type:
```
type Batz = Foo & Bar;
```
I agree that their naming can sometimes be confusing.
Upvotes: 0 <issue_comment>username_2: This can be done in typescript 2.8 and later using conditional types. Conditional types iterate over types in a union, union-ing the result:
```
type Batz = Foo | Bar;
type KeysOfUnion = T extends T ? keyof T: never;
// AvailableKeys will basically be keyof Foo | keyof Bar
// so it will be "foo" | "bar"
type AvailableKeys = KeysOfUnion;
```
The reason a simple `keyof Union` does not work is because `keyof` always returns the accessible keys of a type, in the case of a union that will only be the common keys. The conditional type in `KeysOfUnion` will actually take each member of the union and get its keys so the result will be a union of `keyof` applied to each member in the union.
Upvotes: 8 [selected_answer] |
2018/03/21 | 2,308 | 7,317 | <issue_start>username_0: I am use the .map method to return the name of an object, and ultimately populate the innerHTML of a table with that name.
The problem is I can't get it to show the appropriate values.
So for example, for the flavor Almond\_Divinity it would have a Table row with three table data tags. The first would have the name 'Almond Divinity,' the second would have the price '.99', and the third would have the link.
My javascript is below:
```
var Menu = {
Almond_Divinity : {name: 'Almond Divinity', price: .99, history: 'x', availability: 'x'},
Mango_Sorbet : {name: 'Mango Sorbet', price: .99, history: '', availability: ''},
Decaf : {name: 'Decaf', price: .99, history: '', availability: ''},
Almond_Chocolate_Coconut : {name: 'Almond Chocolate Coconut', price: .99, history: '', availability: ''},
Alpine_Fudge_Crunch : {name: 'Alpine Fudge Crunch', price: .99, history: '', availability: ''},
Banana_Cream_Pie : {name: 'Banana Cream Pie', price: .99, history: '', availability: ''},
Birthday_Cake : {name: 'Birthday Cake:', price: .99, history: '', availability: ''},
Black_Raspberry_Chocolate_Crunch : {name: 'Black Raspberry Chocolate Crunch', price: .99, history: '', availability: ''},
Blueberry_Cobbler : {name: 'Blueberry Cobbler', price: .99, history: '', availability: ''},
Black_Walnut : {name: 'Black Walnut', price: .99, history: '', availability: ''},
Mint_Chocolate_Chip : {name: 'Mint Chocolate Chip', price: .99, history: '', availability: ''},
Caramel_Apple : {name: 'Caramel Apple:', price: .99, history: '', availability: ''},
Almond_Divinity : {name: 'Almond Divinity', price: .99, history: '', availability: ''},
Cherries_Jubilee : {name: '<NAME>', price: .99, history: '', availability: ''},
Tutti_Frutti : {name: '<NAME>', price: .99, history: '', availability: ''},
Artic_Roll : {name: '<NAME>', price: .99, history: '', availability: ''},
Dame_Blanche : {name: '<NAME>', price: .99, history: '', availability: ''},
Sizzling_Brownie : {name: '<NAME>', price: .99, history: '', availability: ''},
Choco_Taco : {name: 'Choco-Taco', price: .99, history: '', availability: ''}
};
window.onload = function () {
// calls the keys property of the Object to find Menu and it's associated properties, and then uses the sort method to compare them and sort them alphabetically
const sortedFlavors = Object.keys(Menu).sort(function(a, b) {return - (name[a] - name[b])});
document.querySelector('#icecream_flavors').innerHTML = sortedFlavors.map(function icecream_flavor(currentValue, index, array) { return ' ${currentValue} | $.99 | [History](https://en.wikipedia.org/wiki/Ice_cream) |'}).join('')
};
```
And my HTML is this:
```
Betty's icecream
@font-face {
font-family: "KR Sweet Tooth";
src: url("fonts/KR Sweet Tooth.ttf");
}
* [Home](#)
* [Menu](#menu)
* [Employees](#employees)
* View Mobile
* [Contact](#)

Betty's s Parlor
=====================
550 Ice Cream Lane
Mulberry Hollow,
Utah
84501
208-208-2080
Put a bird on it 3 wolf moon street art synth, lumbersexual slow-carb poke live-edge brooklyn coloring book tattooed pour-over kombucha. Pitchfork sartorial marfa, tote bag pop-up hell of 90's lo-fi vape coloring book distillery fap fixie. Edison bulb chicharrones actually fanny pack, normcore salvia microdosing fixie activated charcoal direct trade food truck 3 wolf moon. Knausgaard chia copper mug cred, deep v roof party PBR&B kombucha semiotics pickled poutine man bun messenger bag. Shoreditch tbh intelligentsia hammock master cleanse banjo. Wayfarers pork belly skateboard freegan, leggings migas iPhone VHS photo booth knausgaard truffaut. Coloring book forage
| Flavor
| Price
|
link
|
| --- | --- | --- |
|
Employees
---------

[Meet Ben: An impulsive Vanilla lover.](#)

[Meet <NAME>: An argumentative mint chocolate-chipper.](#)
.jpg)
[Meet Jerry: A strawberry introvert.](#)
.jpg)
[Meet <NAME>: A flirtatious chocolate lover.](#)

[Meet <NAME>: A sherbet pessimist.](#)

[Meet <NAME>: An aggressive Rocky Roader.](#)
* Franchise
* Jobs
* Inquiries
* Parties
* Adventure
* Coupons
copyright © Trrapp
// Select all links with hashes
$('a[href\*="#"]')
// Remove links that don't actually link to anything
.not('[href="#"]')
.not('[href="#0"]')
.click(function(event) {
// On-page links
if (
location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
&&
location.hostname == this.hostname
) {
// Figure out element to scroll to
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
// Does a scroll target exist?
if (target.length) {
// Only prevent default if animation is actually gonna happen
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 1000, function() {
// Callback after animation
// Must change focus!
var $target = $(target);
$target.focus();
if ($target.is(":focus")) { // Checking if the target was focused
return false;
} else {
$target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
$target.focus(); // Set focus again
};
});
}
}
});
function newWindow() {
newwindow = window.open('https://trrapp12.github.io/ice-cream/', '', 'width=680,height=680')
function resizeWinTo() {
newwindow.resizeTo(20, 20);
newwindow.focus();
alert("inner function called")
};
resizeWinTo();
};
```
The result I am getting is this:
[link to image](https://i.stack.imgur.com/xLH1V.jpg)
Any help you can give would be appreciated. And since I'm making no claims to greatness here, condescending commentary need not apply.<issue_comment>username_1: You need to enclose the string in backticks to get string interpolated:
```
sortedFlavors.map(function(currentValue) {
return ` ${currentValue} | $.99 | [History](https://en.wikipedia.org/wiki/Ice_cream) |`
}).join('')
```
Also, for sure, the items won't be sorted as a subtraction operation on strings results in `NaN`.
Upvotes: 1 <issue_comment>username_2: You need to use [**template literal**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) instead of single quotes `'`
```
//notice that ' is replaced with `
document.querySelector('#icecream_flavors').innerHTML =
sortedFlavors.map( function icecream_flavor(currentValue, index, array) {
return ` ${currentValue} | $.99 | [History](https://en.wikipedia.org/wiki/Ice_cream) |`
}).join('');
```
Upvotes: 1 <issue_comment>username_3: ```
$(document).ready(function(){
var temp="";
for(var prop in Menu){
temp+="| "+Menu[prop].name+" | "+Menu[prop].price+" | "+Menu[prop].availability+" |
";
}
$("#icecream_flavors").append(temp);
});
```
Upvotes: -1 |
2018/03/21 | 1,521 | 5,059 | <issue_start>username_0: I'm relatively inexperienced with Node and I've been asked to create a POP3 email client. The newest package I could find that handles POP3 is [node-poplib-yapc](https://www.npmjs.com/package/node-poplib-yapc) and I've been playing around with it, seeing how it works.
Now the problem I've run into is that I don't know how to do error handling with this package, I've been purposefully giving it the wrong login details so that I can test it's error handling. When I give it the correct credentials it seems to work fine (I've been able to login and download emails) so I doubt there's an issue with the package or how I call the package. The docs is also completely unclear about it, the only thing that I could find related to (what I think is) error handling says the following:
>
> connect(callback)
>
>
> * callback - function(err) // <- This 'err' variable is what I thought meant 'error'
>
>
> Connect to the mailserver using hostname and port. Starts TLS connection if tls property is true. Then login into your mailbox using credentials properties username and password.
>
>
>
After reading the above I tried the following:
```
let popClient = require('node-poplib-yapc').Client;
let client = new popClient({ /* my incorrect credentials */ });
client.connect((err) => {
if(err) {
console.log('There was an error');
console.log(err);
}
});
```
But this doesn't work, instead it's throwing an actual error in the terminal (I'll add the output below). I also tried the following with the same results:
```
client.connect(() => {
}, (err) => {
console.log('There was an error');
console.log(err);
});
```
And the good old `try/catch`, which also let me down:
```
try {
client.connect(() => {
});
} catch (err) {
console.log(err);
}
```
Here is the error it throws in the terminal when I run any of the above code:
```
events.js:165
throw er; // Unhandled 'error' event
^
Error: [AUTH] Username and password not accepted.
at Client.onData (/home/lee/github/chatterbox/node_modules/node-poplib-yapc/main.js:97:10)
at TLSSocket.emit (events.js:180:13)
at addChunk (_stream_readable.js:269:12)
at readableAddChunk (_stream_readable.js:256:11)
at TLSSocket.Readable.push (_stream_readable.js:213:10)
at TLSWrap.onread (net.js:578:20)
Emitted 'error' event at:
at Client.onData (/home/lee/github/chatterbox/node_modules/node-poplib-yapc/main.js:107:10)
at TLSSocket.emit (events.js:180:13)
[... lines matching original stack trace ...]
at TLSWrap.onread (net.js:578:20)
```
The last thing I also tried is this:
```
client.connect(() => {
}).catch(err => {
console.log('There was an error');
console.log(err);
});
```
Which resulted in the following error:
```
/home/lee/github/chatterbox/service/email.js:29
}).catch(err => {
^
TypeError: Cannot read property 'catch' of undefined
at Object.getMail (/home/lee/github/chatterbox/service/email.js:29:5)
at accounts.forEach (/home/lee/github/chatterbox/app.js:17:11)
at Array.forEach ()
at main (/home/lee/github/chatterbox/app.js:16:12)
at Object. (/home/lee/github/chatterbox/app.js:27:1)
at Module.\_compile (module.js:649:30)
at Object.Module.\_extensions..js (module.js:660:10)
at Module.load (module.js:561:32)
at tryModuleLoad (module.js:501:12)
at Function.Module.\_load (module.js:493:3)
```
If anyone could please help me out with how to properly handle errors with packages like this one, I'd be most appreciative. Obviously a solution that handles any and all errors (not just authentication errors) is preferred, but really just anything that points me in the right direction would help a lot.<issue_comment>username_1: The reason `client` throws an error is that it's an `EventEmitter` and it emits an `'error'` event. Since you don't have any event listeners on the `'error'` event it blows up.
This is what you're missing.
```
client.on('error', err => {
console.error('client got error', err)
})
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Actually first try is OK. When you call connect, if there is error in credentials, callback is called with first param err, so only thing that you are missing is return in if block.
```
let popClient = require('node-poplib-yapc').Client;
let client = new popClient({ /* my incorrect credentials */ });
client.connect((err) => {
if(err) {
console.log('There was an error');
console.log(err);
... you can throw additional error and what you need but after must
return;
}
... if there is no error you call list retrieve or what you need
});
```
Upvotes: 0 <issue_comment>username_3: Well for me, I needed both error callback handler in connect method as well as separate error event handler.
```
client.on('error', err => {
console.error('client got error', err)
})
client.connect(function(err) {
if(err)
{
console.log('error');
}
else{
console.log('success');
}
})
});
```
Upvotes: 0 |
2018/03/21 | 279 | 950 | <issue_start>username_0: According to [MDN](https://developer.mozilla.org/fr/docs/Web/HTML/Element/Input/datetime-local), I should use `datetime-local` type for a date and a time input:
```
```
I can validate a date in laravel with this code (in a controller):
```
$this->validate($request, ['my_date' => 'required|date']);
```
But is there a way to validate a `datetime-local`?<issue_comment>username_1: You can use `date_format:format` or `date` to validate. All date validation is performed by php [strtotime](http://php.net/manual/en/function.strtotime.php)
The best way to know for sure is to test this. Create your `rules` function in the controller and test, that way you know for sure for *your* laravel version and *your* php version as you don't mention that information.
Upvotes: 3 [selected_answer]<issue_comment>username_2: In your example:
```
$this->validate($request, ['my_date' => 'date_format:Y-m-d\TH:i']);
```
Upvotes: 4 |
2018/03/21 | 248 | 941 | <issue_start>username_0: I am curently developping a java/jee app in which i need to store files.I tried storing files as blob in the DB but i got a problem in size of files which must be configured in the application server so i am thinking about storing those files directly in the server disk.So i want to know what is better storing files as blob or directly in the disk.<issue_comment>username_1: You can use `date_format:format` or `date` to validate. All date validation is performed by php [strtotime](http://php.net/manual/en/function.strtotime.php)
The best way to know for sure is to test this. Create your `rules` function in the controller and test, that way you know for sure for *your* laravel version and *your* php version as you don't mention that information.
Upvotes: 3 [selected_answer]<issue_comment>username_2: In your example:
```
$this->validate($request, ['my_date' => 'date_format:Y-m-d\TH:i']);
```
Upvotes: 4 |
2018/03/21 | 1,217 | 4,706 | <issue_start>username_0: I am very new to VueJS.
From what I've seen there is probably an elegant answer to this. I have a table of records. Clicking on one of them opens a modal and loads that row/record. My code looks like this (made easier to read):
### Javascript
```
app = new Vue({
el: '#app',
data: {
records: [], //keys have no significance
focusRecord: { //this object will in the modal to edit, initialize it
id: '',
firstname: '',
lastname: ''
},
focusRecordInitial: {}
},
created: function(){
//load values in app.records via ajax; this is working fine!
app.records = ajax.response.data; //this is pseudo code :)
},
methods: {
loadRecord: function(record){
app.focusRecord = record; // and this works
app.focusRecordInitial = record;
}
}
});
```
### Html
```
| {{ record.id }} | {{ record.firstname }} {{ record.lastname }} |
```
What I'm trying to do is really simple: detect if `focusRecord` has changed after it has been loaded into the modal from a row/record. Ideally another attribute like `app.focusRecord.changed` that I can reference. I'm thinking this might be a computed field which I'm learning about, but again with Vue there may be a more elegant way. How would I do this?<issue_comment>username_1: What you need is to use VueJS watchers : <https://v2.vuejs.org/v2/guide/computed.html#Watchers>
```
...
watch : {
focusRecord(newValue, oldValue) {
// Hey my value just changed
}
}
...
```
Here is another way to do it, however I didn't know what's refers "focusRecordInitial"
```js
new Vue({
el: '#app',
data() {
return {
records: [],
focusRecordIndex: null
}
},
computed : {
focusRecord() {
if (this.focusRecordIndex == null) return null
if (typeof this.records[this.focusRecordIndex] === 'undefined') return null
return this.records[this.focusRecordIndex]
}
},
watch : {
focusRecord(newValue, oldValue) {
alert('Changed !')
}
},
created() {
this.records = [{id: 1, firstname: 'John', lastname: 'Doe'}, {id: 2, firstname: 'Jane', lastname: 'Doe'}, {id: 3, firstname: 'Frank', lastname: 'Doe'}]
},
methods : {
loadRecord(index) {
this.focusRecordIndex = index
}
}
})
```
```html
| | |
| --- | --- |
| {{ record.id }} | {{ record.firstname }} {{ record.lastname }} |
{{focusRecord}}
```
Upvotes: 1 <issue_comment>username_2: ### Vue Watchers
Vue provides a more generic way to react to data changes through the watch option. This is most useful when you want to perform asynchronous or expensive operations in response to changing data.
[Vue JS Watchers](https://v2.vuejs.org/v2/guide/computed.html#Watchers)
You can do something like this:
```
app = new Vue({
el: '#app',
data: {
records: [], //keys have no significance
focusRecord: { //this object will in the modal to edit, initialize it
id: '',
firstname: '',
lastname: ''
},
focusRecordInitial: {}
},
created: function(){
//load values in app.records via ajax; this is working fine!
app.records = ajax.response.data; //this is pseudo code :)
},
methods: {
loadRecord: function(record){
app.focusRecord = record; // and this works
app.focusRecordInitial = record;
}
},
watch: {
loadRecord: function () {
alert('Record changed');
}
}
});
```
You can also check out: Vue JS [Computed Properties](https://v2.vuejs.org/v2/guide/computed.html#Computed-Properties)
Upvotes: 0 <issue_comment>username_3: You can set up a [watcher](https://v2.vuejs.org/v2/guide/computed.html#Watchers) to react to data changes as:
```
watch: {
'focusRecord': function(newValue, oldValue) {
/* called whenever there is change in the focusRecord
property in the data option */
console.log(newValue); // this is the updated value
console.log(oldValue); // this is the value before changes
}
}
```
The `key` in the `watch` object is the expression you want to watch for the changes.
The expression is nothing but the dot-delimited paths of the property you want to watch.
Example:
```
watch: {
'focusRecord': function(newValue, oldValue) {
//do something
},
'focusRecord.firstname': function(newValue, oldValue){
//watch 'firstname' property of focusRecord object
}
}
```
Upvotes: 0 |
2018/03/21 | 1,359 | 5,008 | <issue_start>username_0: I'm awful with Async code in Javascript and have been stuck on something for a while now.
I'm working with WebSql and just going through database initialization steps but one of the loops is not executing in the way I expect it to.
```
$(document).ready(function() {
initdatabase();
});
function initdatabase() {
var db = window.openDatabase("nothing", "1.0", "nothing", 2 * 1024 * 1024);
db.transaction(function(trans) {
trans.executeSql("CREATE TABLE", [], function(trans, result) {
// success
defaultdata(db);
}, function(error) {
// failed
});
});
}
function defaultdata(db) {
db.transaction(function(trans) {
var lo_data = [
{code:"CODE01", desc:"Code 01 Desc"},
{code:"CODE02", desc:"Code 02 Desc"},
{code:"CODE03", desc:"Code 03 Desc"}
];
for(i = 0; i < lo_data.length; i++) {
trans.executeSql("INSERT", [lo_data[i].code, lo_data[i].desc], function(trans, result) {
// success
console.log("INS : " + i);
}, function(error) {
// failed
});
}
console.log("END");
});
}
```
But the log to indicate the end is executing before the for loop has finished. If I try validate that the data has been inserted I always get fails because the loop hasn't completed the inserts.
Google says that async code should be handled with promises but I can't find examples of promises being used in an instance like this.
Any help would be greatly appreciated<issue_comment>username_1: Convert each callback into a promise, and then use Promise.all
```js
const loDataPromises = lo_data.map(({ code, desc }) => {
return new Promise((resolve, reject) => {
trans.executeSql(
"INSERT",
[code, desc],
function(trans, result) {
console.log('success');
resolve();
},
function(error) {
console.log('failed');
reject();
}
);
});
});
Promise.all(loDataPromises)
.then(() => {
console.log('all done');
});
```
Upvotes: 1 <issue_comment>username_2: I haven't been able to find any clear code examples on the internet so I wanted to post the working version here as the answer. Hopefully it can benefit someone also trying to understand promises and promise loops.
After a complete overhaul I've managed to get it working in a way that makes sense. I've change it to be executed as a promise chain and then the function with the for loop is utilizing the promise all logic.
```
$(document).ready(function() {
////
// promise chain
////
console.log("BEGIN");
f_initdatabase().then(function(result) {
return f_defaultdata(result.db);
}).then(function(result) {
console.log("END");
}).catch(function(result) {
// abandon all hope
});
});
////
// single promise usage
////
function f_initdatabase() {
return new Promise(function(resolve, reject) {
console.log(" INIT DB");
var lo_result = {db:null};
var lv_db = window.openDatabase("thenothing", "1.0", "The Nothing DB", 2 * 1024 * 1024);
lv_db.transaction(function(trans) {
trans.executeSql ("create table if not exists dummydata (dd_idno integer primary key, dd_code text not null, dd_desc text not null)", [], function(trans, results) {
console.log(" INIT DB : DONE");
lo_result.db = lv_db;
resolve(lo_result);
}, function(error) {
lo_result.db = null;
reject(lo_result);
});
});
});
}
////
// loop promise all usage
////
function f_defaultdata(lv_db) {
return new Promise(function(resolve, reject) {
console.log(" DEF DATA");
var lo_result = {db:null};
lv_db.transaction(function(trans) {
var la_promises = [];
var lo_data = [
{dd_code:"CODE01", dd_desc:"Code 01 Desc"},
{dd_code:"CODE02", dd_desc:"Code 02 Desc"},
{dd_code:"CODE03", dd_desc:"Code 03 Desc"}
];
for(i = 0; i < lo_data.length; i++) {
console.log(" INS : " + i);
trans.executeSql (" insert into dummydata (dd_code, dd_desc) values (?, ?)", [lo_data[i].dd_code, lo_data[i].dd_desc], function(trans, results) {
la_promises.push(resolve(lo_result));
}, function(error) {
la_promises.push(reject(lo_result));
});
}
Promise.all(la_promises).then(function(results) {
console.log(" DEF DATA : DONE");
lo_result.db = lv_db;
resolve(lo_result);
}).catch(function() {
lo_result.db = null;
reject(lo_result);
});
});
});
}
```
This gives the output according to the flow needed
```
BEGIN
INIT DB
INIT DB : DONE
DEF DATA
INS : 0
INS : 1
INS : 2
DEF DATA : DONE
END
```
Upvotes: 0 |
2018/03/21 | 2,720 | 10,154 | <issue_start>username_0: Hello everybody i'm working on reactjs project here i have an issue if you want to help me thanks for advance
i passed my data to my function so i can push activities and tasks into acts and tasks 'json format'
```
function StoryMap(props) {
var acts = [];
var taskss = [];
for (var i = 0; i < props.data.activities.length; i++) {
acts.push(props.data.activities[i]);
console.log(acts)
for (var j = 0; j < props.data.activities[i].tasks.length; j++) {
taskss.push(props.data.activities[i].tasks[j]);
console.log(taskss)
}
}
console.log(acts);
return (
|
| |
);
}
```
in console output the console.log works fine but there is an error ×
TypeError: Cannot read property 'length' of undefined
[error](https://i.stack.imgur.com/0PyRK.png)<issue_comment>username_1: You need to check if `props.data.activities` is present before using it since `this.state.data` may initially be empty in your parent component during initial render and you could be populating it only later
```
function StoryMap(props) {
var acts = [];
var taskss = [];
if(props.data.activities) {
for (var i = 0; i < props.data.activities.length; i++) {
acts.push(props.data.activities[i]);
console.log(acts)
for (var j = 0; j < props.data.activities[i].tasks.length; j++) {
taskss.push(props.data.activities[i].tasks[j]);
console.log(taskss)
}
}
}
console.log(acts);
return (
|
| |
);
}
```
Upvotes: 2 <issue_comment>username_2: ```
this is the code and it contains the data
import React, {Component} from 'react';
import './App.css';
import Ranger from './header.js';
function StoryMap(props) {
var acts = [];
var taskss = [];
for (var i = 0; i < props.data.activities.length; i++) {
acts.push(props.data.activities[i]);
console.log(acts)
for (var j = 0; j < props.data.activities[i].tasks.length; j++) {
taskss.push(props.data.activities[i].tasks[j]);
console.log(taskss)
}
}
console.log(acts);
return (
|
| |
);
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: {
activities: [
{
id: 'A1',
label: 'Activite 1',
tasks: [
{
id: 'A1.T1',
label: 'Activite 1 task 1'
}, {
id: 'A1.T2',
label: 'Activite 1 task 1'
}, {
id: 'A1.T3',
label: 'Activite 1 task 1'
}
]
}, {
id: 'A2',
label: 'Activite 2',
tasks: [
{
id: 'A2.T1',
label: 'Activite 1 task 1'
}, {
id: 'A2.T2',
label: 'Activite 1 task 1'
}, {
id: 'A2.T3',
label: 'Activite 1 task 1'
}
]
}, {
id: 'A3',
label: 'Activite 3'
}, {
id: 'A4',
label: 'Activite 4'
}
],
releases: [
{
id: 'R1',
storiesByTasks: {
'A1.T1': [
{
id: 'A1.T1.S1'
}, {
id: 'A1.T1.S2'
}
],
'A1.T2': [
{
id: 'A1.T2.S1'
}, {
id: 'A1.T2.S2'
}, {
id: 'A1.T2.S3'
}
]
}
}, {
id: 'R2',
storiesByTasks: {
'A1.T2': [
{
id: 'A1.T2.S4'
}, {
id: 'A1.T2.S5'
}
],
'A2.T1': [
{
id: 'A2.T1.S8'
}
]
}
}
]
}
};
}
render() {
return (
< StoryMap data={this.state.data}/>
);
}
}
export default App;
```
Upvotes: 0 <issue_comment>username_3: Try This code: it works
```
import React, { Component } from "react";
function StoryMap(props) {
var acts = [];
var taskss = [];
for (var i = 0; i < props.data.activities.length; i++) {
acts.push(props.data.activities[i]);
console.log("acts", acts);
console.log("prop: ", props.data.activities[i].tasks);
if (props.data.activities[i].tasks) {
console.log("length :", props.data.activities[i].tasks.length);
for (var j = 0; j < props.data.activities[i].tasks.length; j++) {
taskss.push(props.data.activities[i].tasks[j]);
console.log(" tasks ", taskss);
}
}
}
console.log(acts);
return (
|
| |
);
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: {
activities: [
{
id: "A1",
label: "Activite 1",
tasks: [
{
id: "A1.T1",
label: "Activite 1 task 1"
},
{
id: "A1.T2",
label: "Activite 1 task 1"
},
{
id: "A1.T3",
label: "Activite 1 task 1"
}
]
},
{
id: "A2",
label: "Activite 2",
tasks: [
{
id: "A2.T1",
label: "Activite 1 task 1"
},
{
id: "A2.T2",
label: "Activite 1 task 1"
},
{
id: "A2.T3",
label: "Activite 1 task 1"
}
]
},
{
id: "A3",
label: "Activite 3"
},
{
id: "A4",
label: "Activite 4"
}
],
releases: [
{
id: "R1",
storiesByTasks: {
"A1.T1": [
{
id: "A1.T1.S1"
},
{
id: "A1.T1.S2"
}
],
"A1.T2": [
{
id: "A1.T2.S1"
},
{
id: "A1.T2.S2"
},
{
id: "A1.T2.S3"
}
]
}
},
{
id: "R2",
storiesByTasks: {
"A1.T2": [
{
id: "A1.T2.S4"
},
{
id: "A1.T2.S5"
}
],
"A2.T1": [
{
id: "A2.T1.S8"
}
]
}
}
]
}
};
}
render() {
return (
);
}
}
export default App;
```
Upvotes: 1 <issue_comment>username_4: try this
App.js
```
import React, { Component } from 'react';
import StoryMap from './StoryMap';
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: {
activities: [
{
id: 'A1',
label: 'Activite 1',
tasks: [
{
id: 'A1.T1',
label: 'Activite 1 task 1'
}, {
id: 'A1.T2',
label: 'Activite 1 task 1'
}, {
id: 'A1.T3',
label: 'Activite 1 task 1'
}
]
}, {
id: 'A2',
label: 'Activite 2',
tasks: [
{
id: 'A2.T1',
label: 'Activite 1 task 1'
}, {
id: 'A2.T2',
label: 'Activite 1 task 1'
}, {
id: 'A2.T3',
label: 'Activite 1 task 1'
}
]
}, {
id: 'A3',
label: 'Activite 3'
}, {
id: 'A4',
label: 'Activite 4'
}
],
releases: [
{
id: 'R1',
storiesByTasks: {
'A1.T1': [
{
id: 'A1.T1.S1'
}, {
id: 'A1.T1.S2'
}
],
'A1.T2': [
{
id: 'A1.T2.S1'
}, {
id: 'A1.T2.S2'
}, {
id: 'A1.T2.S3'
}
]
}
}, {
id: 'R2',
storiesByTasks: {
'A1.T2': [
{
id: 'A1.T2.S4'
}, {
id: 'A1.T2.S5'
}
],
'A2.T1': [
{
id: 'A2.T1.S8'
}
]
}
}
]
}
};
}
render() {
return (
);
}
}
export default App;
```
StoryMap.js
```
import React, {Component} from 'react';
import PropTypes from 'prop-types';
class StoryMap extends Component{
render(){
const {data} = this.props;
//console.log("data",data)
var acts = [];
var taskss = [];
//console.log(data);
for (var i = 0; i < data.activities.length; i++) {
acts.push(data.activities[i]);
console.log(acts)
if(data.activities[i].tasks){
for (var j = 0; j < data.activities[i].tasks.length; j++) {
taskss.push(data.activities[i].tasks[j]);
console.log(taskss)
}
}
}
return (
|
| |
);
}
}
export default StoryMap;
```
Upvotes: 0 |
2018/03/21 | 621 | 2,269 | <issue_start>username_0: [](https://i.stack.imgur.com/JjGVj.png)
I want to move my `ImageView` so it will be half way out of the `ConstraintLayout` (parent one)
You can imagine this as I make negative margin in my `LinearLayout`
*What I have is an Image and it should be cut as on picture, so only button side of the image should be displayed on the actual device. Other part should be cut off.*
Here is a part of my layout.
```
```
So, is there any good way to do that?<issue_comment>username_1: Add a guide line and say that your ImageView should be above that guidelines for example this code will make everything appear like your layout:
```
xml version="1.0" encoding="utf-8"?
```
Upvotes: 3 <issue_comment>username_2: To position the `ImageView` halfway outside parent enforce the vertical constraints by setting `layout_height` to `0dp`. To maintain the appropriate size of the `ImageView` set the `dimensionRatio` to `1:1`. The code will look like this (note that parent `ConstraintLayout` now has `layout_height` matching parent):
```
```
Upvotes: 0 <issue_comment>username_3: So I found the solution.
Basically you need to make a translation of the image out of its container.
```
android:translationY="-22dp"
```
Upvotes: 4 <issue_comment>username_4: Put the image inside of the Linear Layout.
```
```
And add attribute called **clipChildren** and make it **true**.
Upvotes: 0 <issue_comment>username_5: One trick would be to set negative margin for the side you want, in the `ConstraintLayout` itself. This requires that other views that have constraint to that side be offset. The right button in the images is below the `ConstraintLayout` and hidden under the bottom bar:
[](https://i.stack.imgur.com/Lp2M3.png)
[](https://i.stack.imgur.com/Vjeff.png)
```
xml version="1.0" encoding="utf-8"?
```
Upvotes: 0 <issue_comment>username_6: I did this by adding View inside the ConstraintLayout and give it some margin.
View provides background to ConstraintLayout.
ConstraintLayout must be of transparent background.
```
```
Upvotes: 0 |
2018/03/21 | 350 | 1,235 | <issue_start>username_0: I use [create-react-native-app](https://github.com/react-community/create-react-native-app), and I wonder how I can get a `.ipa` file to run in my iPhone from it? I see the command `npm run eject`, but I do not know what to do next. And for some reason, I cannot use `exp` in the command line.
Is there a detail instructions to solve my problem? thanks<issue_comment>username_1: I xcode:
1. Change scheme destination to `generic ios device`
2. Go to `Product` - `Archive`
3. Go to `Window` - `Organizer`
4. Select the archive you want, click `export`
There you should be able to choose method and destination.
Upvotes: 0 <issue_comment>username_2: `npm run eject` will not create a IPA file for you. It will just create project files for iOS and Android which you can run on their respective IDE's. i.e Xcode and Android Studio.
Here is a good document which you can use to build iOS without ejecting it : <https://docs.expo.io/versions/latest/guides/building-standalone-apps.html>
If you choose to eject then, open Xcode project from the iOS folder -> change the bundle id. and follow along this <https://wiki.genexus.com/commwiki/servlet/wiki?34616,HowTo%3A+Create+an+.ipa+file+from+XCode>,
Upvotes: 2 |
2018/03/21 | 341 | 1,570 | <issue_start>username_0: Hi I am using kubernetes and now need to make a choice between traefik and nginx ingress controller for ingress expose. I have googled a lot, but seems no such big difference, especially nginx just announce support grpc now. Anyone can give a advice? Thanks very very much!<issue_comment>username_1: Found this comment at [stackshare](https://stackshare.io/stackups/nginx-vs-traefik) by <NAME>
The reasons for choosing Traefik over Nginx are as follows:
* Traefik built-in Let’s Encrypt and supports automatic renewal
* Traefik automatically enables HTTP/2
* Prometheus can be supported through simple Traefik configuration
* cookiecutter django integrates Traefik's configuration by default
Upvotes: 2 <issue_comment>username_2: TL;DR -> microservice on docker/kubernetes -> traefik
Nginx: It is a high-performance, free, and open-source web server that serves as an HTTP and reverse proxy server. It has been widely used and has recently announced support for gRPC. It has good community support and documentation.
Traefik: It is a modern HTTP reverse proxy and load balancer designed specifically for microservices deployments. It offers seamless integration with Kubernetes and aims to simplify the deployment of microservices. Traefik has gained popularity for its ease of use and dynamic configuration.
Ultimately, the choice between Traefik and Nginx Ingress Controller depends on your specific requirements and preferences. If you prioritize simplicity and native Kubernetes integration, Traefik might be a good fit.
Upvotes: -1 |
2018/03/21 | 1,346 | 4,679 | <issue_start>username_0: I am new in **Kotlin**. I have a view that I need to show or hide in conditional ways.
How can I do this in Kotlin?
**In Java:**
```
public void showHide(View view){
if (view.getVisibility() == View.VISIBLE) {
view.setVisibility(View.INVISIBLE);
} else {
view.setVisibility(View.VISIBLE);
}
}
```<issue_comment>username_1: In response to this answer, I believe a Kotlin-styled way to accomplish this can also be written as:
```
fun showHide(view:View) {
view.visibility = if (view.visibility == View.VISIBLE){
View.INVISIBLE
} else{
View.VISIBLE
}
}
```
Upvotes: 7 [selected_answer]<issue_comment>username_2: You could do this in an [extension function](https://kotlinlang.org/docs/reference/extensions.html#extension-functions):
```
fun View.toggleVisibility() {
if (visibility == View.VISIBLE) {
visibility = View.INVISIBLE
} else {
visibility = View.VISIBLE
}
}
```
Can be used like this:
```
someView.toggleVisibility()
```
Upvotes: 3 <issue_comment>username_3: You can convert using Android Studio: Click on the Java file you want to convert, choose Code -> Convert Java File To Kotlin File and see the magic.
The result is:
```
fun showHide(view: View) {
if (view.visibility == View.VISIBLE) {
view.visibility = View.INVISIBLE
} else {
view.visibility = View.VISIBLE
}
}
```
Upvotes: 3 <issue_comment>username_4: This is how I handle view's visibility in Kotlin. These methods can be called on any subclass of `View` class. E.g. `LinearLayout`, `TextView` etc.
**VISIBLE / GONE:**
```
// @BindingAdapter("visibleOrGone")
fun View.visibleOrGone(visible: Boolean) {
visibility = if(visible) View.VISIBLE else View.GONE
}
```
**VISIBLE / INVISIBLE:**
```
// @BindingAdapter("visibleOrInvisible")
fun View.visibleOrInvisible(visible: Boolean) {
visibility = if(visible) View.VISIBLE else View.INVISIBLE
}
```
**Databinding:**
Uncomment `@BindingAdapter` if you also want to use above methods with databinding.
```
```
or
```
```
My `ViewModel` class looks like this:
```
class LoginViewModel {
val visibleView = ObservableBoolean()
}
```
Upvotes: 2 <issue_comment>username_5: You can use from bellow code:
```
fun View.isVisible(): Boolean {
return visibility == View.VISIBLE
}
```
And:
```
fun View.setVisible(visible: Boolean) {
visibility = if (visible) {
View.VISIBLE
} else {
View.GONE
}
}
```
And you can use:
```
if (text_view.isVisible()) {
text_view.setVisible(false)
}
```
Upvotes: 3 <issue_comment>username_6: A simple way in Kotlin:
```
fun toggleView(view: View) {
view.isVisible = !view.isVisible
}
```
Upvotes: 3 <issue_comment>username_7: if you want to visible icon
```
ic_back.visibility = View.VISIBLE
```
and if you want to visibility GONE so please try it :
```
ic_back.visibility = View.GONE
```
Upvotes: 5 <issue_comment>username_8: You can get the visibility state of a view with the command .isVisible
I´ll show you how.
```
val menu: ConstraintLayout = findViewById(R.id.layMenu)
if (menu.isVisible==false){
//view is not visible
} else {
//view is visible
}
```
Upvotes: 1 <issue_comment>username_9: You can simply do it.
```
idTextview.isVisible = true
idTextview.isVisible = false
```
Upvotes: 4 <issue_comment>username_10: If the View is visible initially, one can use the xor operator to toggle the visibility.
```
view.visibility = view.visibility.xor(View.GONE)
```
The correct - and more readable - way however is to use the inline var `View.isVisible`:
```
view.isVisible = !isVisible
inline var View.isVisible: Boolean
get() = visibility == View.VISIBLE
set(value) {
visibility = if (value) View.VISIBLE else View.GONE
}
```
Edit May 1 2022:
----------------
Android developers have added an extension [androidx.core.view.ViewKt#isVisible](https://developer.android.com/reference/kotlin/androidx/core/view/package-summary#(android.view.View).isVisible()) to toggle visibility between View.VISIBLE and View.GONE. So use that rather.
Upvotes: 3 <issue_comment>username_11: * If you using **viewBinding** on Kotlin.
* **binding.yourView.visibility = View.VISIBLE**
Upvotes: 2 <issue_comment>username_12: You can do it in 2 different ways.
`I.way`
```kotlin
fun showHide(view: View) {
if (view.visibility == View.VISIBLE) view.visibility = View.INVISIBLE else view.visibility = View.VISIBLE
}
```
`II.way`
```kotlin
fun showHide(view: View) {
view.isVisible = view.visibility != View.VISIBLE
}
```
Upvotes: 1 |
2018/03/21 | 248 | 1,004 | <issue_start>username_0: I am trying to create package-info.java of a package which is already being created. Eclipse have the option to create a package-info.java at the time of create of package. Is there any way to create package-ingo.java after creating package?<issue_comment>username_1: As stated in this [question](https://stackoverflow.com/questions/38177068/is-there-a-way-to-create-package-info-java-for-existing-packages-in-one-move-in), no, there is no specific shortcut to create package-info.java, however copy-paste it from an other existing package works.
Upvotes: 1 <issue_comment>username_2: Yes you can create a package-info.java after creation of the package also, Just Right click the on the existing package then click new -> package, In New Java Package input box, name should be the same as existing package name and tick the checkbox "create package-info.java" and click finish button, then package-info.java will be created in your existing package.
Upvotes: 3 [selected_answer] |
2018/03/21 | 764 | 2,374 | <issue_start>username_0: Can anyone explain why given the below code I can access myInt but not myInt2?
```
if(int.TryParse("10", out int myInt))
{
//Do Something
}
else if(int.TryParse("100", out int myInt2))
{
// Do Something else
}
System.Console.WriteLine(myInt);
System.Console.WriteLine(myInt2); //<-- Compile Error 'myInt2 doesnt exist in the current context
```<issue_comment>username_1: It's because:
```
if (condition)
{
// ...
}
else if (otherCondition)
{
// ...
}
```
Is equivalent to:
```
if (condition)
{
// ...
}
else
{
if (otherCondition)
{
// ...
}
}
```
Now you can see why the scope is different. The second `if` is nested in the `else` block.
Note that a variable introduced inside the condition for an `if` is introduced into the scope of the `else` part of that `if`, as well as the scope following the `if` - but a nested `if` will introduce a variable into the scope for the nested `if` so it won't be visible to the outer `if`'s scope.
(I had a look in the C# standard to provide a reference for this, but I haven't found a good reference yet. I will update this post if I do.)
Incidentally, this scales for multiple if/elses like so:
```
if (init(out int a))
{
// Can access 'a'here. Cannot access 'b' or 'c'.
}
else if (init(out int b))
{
// Can access 'a' and 'b' here. Cannot access 'c'.
}
else if (init(out int c))
{
// Can access 'a', 'b' and 'c' here.
}
// Cannot access 'b' or 'c' here.
```
Is logically the same as:
```
if (init(out int a))
{
// Can access 'a' here. Cannot access 'b' or 'c'.
}
else
{
if (init(out int b))
{
// Can access 'a' and 'b' here. Cannot access 'c'.
}
else
{
if (init(out int c))
{
// Can access 'a', 'b' and 'c' here.
}
}
// Cannot access 'c' here.
}
// Cannot access 'b' or 'c' here.
```
Upvotes: 3 <issue_comment>username_2: The `out int name` construct is a different way to simplify code writing. Remember that the code you posted in C# 6 equivalent is:
```
int myInt
if(int.TryParse("10", out myInt))
{
//Do Something
}
else
{
int myInt2
if(int.TryParse("100", out myInt2))
{
// Do Something else
}
}
System.Console.WriteLine(myInt);
System.Console.WriteLine(myInt2); //<-- Compile Error 'myInt2 doesn't exists
```
Upvotes: 2 |
2018/03/21 | 517 | 1,405 | <issue_start>username_0: Crashes on:
```
$Time = new DateTime('now', new DateTimeZone('UTC'));
$DBTime = DateTime::createFromFormat('Y-m-d H:i:s.u', 2000-01-01 00:00:00, new DateTimeZone('UTC'));
$Interval = $DBTime ->diff($Time);
```
>
> Call to a member function diff() on boolean
>
>
>
Wrong format?<issue_comment>username_1: `createFromFormat` returns FALSE because the format doesn't match with the time (that should be wrapped into quotes). The format is `Y-m-d H:i:s` instead of `Y-m-d H:i:s.u`:
```
$Time = new DateTime('now', new DateTimeZone('UTC'));
$DBTime = DateTime::createFromFormat('Y-m-d H:i:s', '2000-01-01 00:00:00', new DateTimeZone('UTC'));
$Interval = $DBTime->diff($Time);
```
Upvotes: 1 <issue_comment>username_2: You need to add date time string in to quotes also in format there is `u` for(microseconds) but it is not specified in string. So it will return false. change your code as below:
```
$Time = new DateTime('now', new DateTimeZone('UTC'));
$DBTime = DateTime::createFromFormat('Y-m-d H:i:s', '2000-01-01 00:00:00', new DateTimeZone('UTC'));
$Interval = $DBTime ->diff($Time);
```
Upvotes: 2 <issue_comment>username_3: Can archive with this too
```
date_default_timezone_set('UTC');
$DBTime = date_create(date('Y-m-d H:i:s', strtotime('2000-01-01 00:00:00')));
$Time = date_create(date('Y-m-d H:i:s'));
$Interval = date_diff($DBTime, $Time);
```
Upvotes: 0 |
2018/03/21 | 1,419 | 5,350 | <issue_start>username_0: Here is Repository pattern, Normally if I used **ContextDb** instead of **IdentityContextDb** ,it would have worked but i have to use Indentity for creating my Identificial things.
**Core.Repository**
```
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace XYZ.CORE.Repository
{
public class Repository : IRepository where
TEntity : class, new() where TContext : IdentityDbContext, new()
{
public void Delete(TEntity entity)
{
using (var context=new TContext())
{
var deleteEntity = context.Entry(entity);
deleteEntity.State = EntityState.Deleted;
context.SaveChanges();
}
}
public IEnumerable GetAll(Expression> filter = null)
{
using (var context = new TContext())
{
return filter == null ? context.Set().AsEnumerable() : context.Set().Where(filter).AsEnumerable();
}
}
public TEntity GetById(int id)
{
using (var context = new TContext())
{
return context.Set().Find(id);
}
}
public void Insert(TEntity entity)
{
using (var context = new TContext())
{
var addEntity = context.Entry(entity);
addEntity.State = EntityState.Added;
context.SaveChanges();
}
}
public void Update(TEntity entity)
{
using (var context = new TContext())
{
var updatedEntity = context.Entry(entity);
updatedEntity.State = EntityState.Modified;
context.SaveChanges();
}
}
}
}
```
again but :) when i inherit my context from IdentityContextDb, it wants generic type like bottom of this line and its problem for Repository.
i'll share what is like an error when we call this Repo
**DAL.Context**
```
using XYZ.DATA.Entity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
namespace XYZ.DAL.Context
{
public class XyzDb:IdentityDbContext
{
public HysWebDb(DbContextOptions options) : base(options)
{
}
}
}
```
and now lets call in Controller
**UI.Controller**
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using XYZ.UI.Models.VM;
using Microsoft.AspNetCore.Mvc;
using XYZ.DAL.Context;
using Microsoft.AspNetCore.Identity;
using XYZ.DATA.Entity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Authorization;
using XYZ.CORE.Repository;
namespace XYZ.UI.Controllers.Account
{
//[Authorize(Roles ="Admin")]
public class RegisterController : Controller
{
private readonly XyzDb _database;
private readonly UserManager \_uManager;
private readonly Repository \_userRepo;
public RegisterController(UserManager uManager, XyzDb database)
{
\_database = database;
\_uManager = uManager;
}
}
}
```
although we havent injected yet but ...
>
> **Error CS0311** The type 'XYZ.DAL.Context.XyzDb' cannot be used as type parameter 'TContext' in the generic type or method
> 'Repository'. There is no implicit reference
> conversion from 'XYZ.DAL.Context.XyzDb' to
> 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityDbContext'. ~\XYZ.UI\Controllers\Account\RegisterController.cs **21** Active
>
>
> **Error CS0310** 'XyzDb' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'TContext'
> in the generic type or method 'Repository' ~\XYZ.UI\Controllers\Account\RegisterController.cs **21** Active
>
>
> Line 21 is here **private readonly Repository
> \_userRepo;**
>
>
>
Thanks,
Özgür<issue_comment>username_1: Actually you're setting a constraint on your generic Repository class
```
public class Repository : IRepository where
TEntity : class, new() where TContext : IdentityDbContext, new()
```
which is the **new()** on your IdentityDbContext, so your IdentityDbContext should contains a parameterless constructor.
For more details check microsoft docs <https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/new-constraint>
Upvotes: 2 <issue_comment>username_2: ```
public class Repository : IRepository where
TEntity : class, new() where TContext : IdentityDbContext, new()
```
You are defining here two things:
1. The repository class must use class there TEntity & TContext has new() which means parameterless constructor, when in fact you have only 1 constructor with options - (this is your 2nd error)
>
> public HysWebDb(DbContextOptions options) : base(options)
>
>
>
2. The second problem not 100% sure about this but if you inherit a generic interface but declare the type - IdentityDbContext - it cannot be considered as only IdentityDbContext
`public class XyzDb:IdentityDbContext < AppUser>`
To solve your problem you should change the public class Repository to this:
```
public class Repository : IRepository where
TEntity : class, new() where TContext : IdentityDbContext
```
Upvotes: 2 <issue_comment>username_3: I can solve with using context referance and injection in constructor
`public class Repository : IRepository where T : class
{
private readonly ContextX \_database;
public Repository(ContextX database)
{
\_database = database;
}`
we cant find another way for solution
Thanks,
<NAME>
Upvotes: 1 [selected_answer] |
2018/03/21 | 523 | 2,161 | <issue_start>username_0: I am new to iOS Development.I am having problem with font size with phone screen size.For example Font size in iPhone 8 Plus looks fine but that text size is bigger in iPhone SE.I tried check Dynamic Type to Automatically Adjusts Font.And try to play with Autoshrink in StoryBoard.And i also tried to Add Font Variation in storyBoard.But I didnt get any good solution.Hope you understand my problem.Thanks in advance<issue_comment>username_1: Actually you're setting a constraint on your generic Repository class
```
public class Repository : IRepository where
TEntity : class, new() where TContext : IdentityDbContext, new()
```
which is the **new()** on your IdentityDbContext, so your IdentityDbContext should contains a parameterless constructor.
For more details check microsoft docs <https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/new-constraint>
Upvotes: 2 <issue_comment>username_2: ```
public class Repository : IRepository where
TEntity : class, new() where TContext : IdentityDbContext, new()
```
You are defining here two things:
1. The repository class must use class there TEntity & TContext has new() which means parameterless constructor, when in fact you have only 1 constructor with options - (this is your 2nd error)
>
> public HysWebDb(DbContextOptions options) : base(options)
>
>
>
2. The second problem not 100% sure about this but if you inherit a generic interface but declare the type - IdentityDbContext - it cannot be considered as only IdentityDbContext
`public class XyzDb:IdentityDbContext < AppUser>`
To solve your problem you should change the public class Repository to this:
```
public class Repository : IRepository where
TEntity : class, new() where TContext : IdentityDbContext
```
Upvotes: 2 <issue_comment>username_3: I can solve with using context referance and injection in constructor
`public class Repository : IRepository where T : class
{
private readonly ContextX \_database;
public Repository(ContextX database)
{
\_database = database;
}`
we cant find another way for solution
Thanks,
<NAME>
Upvotes: 1 [selected_answer] |
2018/03/21 | 710 | 2,473 | <issue_start>username_0: Experts!
I am using a class that inherits `CWnd` to make the content visible using a horizontal scroll bar
The control I want to create looks like this:
[](https://i.stack.imgur.com/s6DWK.png)
However, I have some problems and leave a question
When the button receives focus, it changes to blue. If another button is pressed, the button that received the existing focus should be unfocused.
[](https://i.stack.imgur.com/9lmtF.png)
The button does not release focus as shown in the second picture.
However, the above problem occurs when implemented in Dialog, not in SDI.
I need help solving this problem.
Custom Control Create Code;
===========================
```
m_ScrollWnd.Create(WS_CHILD | WS_VISIBLE, CRect(0, 0, 0, 0), this, 1234);
BOOL CScrollWnd::Create(DWORD dwStyle, CRect ▭, CWnd *pParent, UINT nID)
{
dwStyle |= ((WS_HSCROLL) );
return CWnd::Create(CScrollWnd::IID, nullptr, dwStyle, rect, pParent, nID);
}
m_Button3.Create(_T("Hello3"), WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, CRect(0, 0, 0, 0), this, 1238);
```<issue_comment>username_1: The so called "default button handling" is done by a function named `IsDialogMessage`.
The easiest way to control this is to make your parent control a window derived from `CDialog`, or if it's a view derive from `CFormView`. The MFC will handle all this for you in the appropriate `PreTranslateMessage` handler.
If you want to do this by your own you might insert your own `PreTranslateMessage` handler and use `IsDialogMessage`. The `CWnd` class also has a predefined implementation named `CWnd::PreTranslateInput`.
So this might be sufficient:
```
BOOL CYourParentClass::PreTranslateMessage(MSG* pMsg)
{
// allow standard processing
if (__super::PreTranslateMessage(pMsg))
return TRUE;
return PreTranslateInput(pMsg);
}
```
Using `CFormView` / `CDialog` is the better way from my point of view, because also other "problematic things about dialogs" are solved in it. Including loosing and getting focus and activation...
Upvotes: 2 [selected_answer]<issue_comment>username_2: Official document from MSDN: [Dialog Box Keyboard Interface](https://learn.microsoft.com/en-us/windows/win32/dlgbox/dlgbox-programming-considerations#dialog-box-keyboard-interface)
BTW, username_1 explains it very well.
Upvotes: 0 |
2018/03/21 | 582 | 1,838 | <issue_start>username_0: I have a df with a label "S" for anywhere my numeric column is <35.
I'd like to use each S position and label "S-1", "S-2", "S-3" for the 3 previous rows to S, then "S+1", "S+2" for the next 2 rows of S.
like this..
```
N S
45
56
67 S-3
47 S-2
52 S-1
28 S
89 S+1
66 S+2
55
76
```
I was using this to start me off, just as an example.
```
n <- sample(50:100, 10, replace=T)
data <- data.frame(N=n)
data <- rbind(data, 30)
data <- rbind(data,data,data,data,data,data)
data$S <- ifelse(data$N<35, "S", "")
```
Any ideas..?<issue_comment>username_1: The so called "default button handling" is done by a function named `IsDialogMessage`.
The easiest way to control this is to make your parent control a window derived from `CDialog`, or if it's a view derive from `CFormView`. The MFC will handle all this for you in the appropriate `PreTranslateMessage` handler.
If you want to do this by your own you might insert your own `PreTranslateMessage` handler and use `IsDialogMessage`. The `CWnd` class also has a predefined implementation named `CWnd::PreTranslateInput`.
So this might be sufficient:
```
BOOL CYourParentClass::PreTranslateMessage(MSG* pMsg)
{
// allow standard processing
if (__super::PreTranslateMessage(pMsg))
return TRUE;
return PreTranslateInput(pMsg);
}
```
Using `CFormView` / `CDialog` is the better way from my point of view, because also other "problematic things about dialogs" are solved in it. Including loosing and getting focus and activation...
Upvotes: 2 [selected_answer]<issue_comment>username_2: Official document from MSDN: [Dialog Box Keyboard Interface](https://learn.microsoft.com/en-us/windows/win32/dlgbox/dlgbox-programming-considerations#dialog-box-keyboard-interface)
BTW, username_1 explains it very well.
Upvotes: 0 |
2018/03/21 | 450 | 1,625 | <issue_start>username_0: I have a .net 2 Core web app on windows IIS. No issues with the web app. How can I successfully run:
**1)** a .net core console app;and
**2)** a regular windows executable?
The console app is needed because of the work passed to it can take several minutes - sometimes up to 10 minutes to complete. Probably too long to expect a user to keep their browser open.
I have tried using `"System.Diagnostics.Process"` on the windows app with much success. I figured before I started trying with the Core app, I would get some suggestions. Let me know if any additional information is needed.<issue_comment>username_1: I'm not sure if this will be useful, But you can try the task scheduler to call the app. Gets rid of a lot of permission problems.
Upvotes: -1 <issue_comment>username_2: Console app in .net core 2 has a lot of new features in it, explaining it in a nutshell is a little bit complicated.
I would suggest starting from this
* [guide](https://github.com/NLog/NLog.Extensions.Logging/wiki/Getting-started-with-.NET-Core-2---Console-application)
on git hub which sums it up really good.
I would also recommend looking into this post regarding [Windows Executable](https://stackoverflow.com/questions/44074121/build-net-core-console-application-to-output-an-exe?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) (which is about .net core 1.0 but is more or less the same) and this [article](https://blogs.msdn.microsoft.com/luisdem/2016/10/11/net-core-how-to-publish-a-self-contained-application-exe/).
Those will be a good place for you to start.
Upvotes: 2 |
2018/03/21 | 290 | 834 | <issue_start>username_0: is there any possibility of any variable defined in a php file in WordPress, that it can be used in another file?<issue_comment>username_1: Yes you can use global var on WordPress like as usual doing on PHP like below
**from.php**
```
global $id;
$id = 10;
```
**to.php**
```
global $id;
echo $id;
```
Edit:
As we discussed on the comment using classes is a good way.
**demo1.php**
```
class test{
public $i = 10;
public $j = 20;
public $k = 30;
}
```
**demo2.php**
```
$obj = new test();
echo $obj->i;
echo $obj->j;
echo $obj->k;
```
Upvotes: 0 <issue_comment>username_2: You can include the file with the defined variable in the second file, like this:
anything.php:
```
$var= 'test';
```
something.php:
```
include 'anything.php';
echo $var;
```
Upvotes: 3 [selected_answer] |
2018/03/21 | 321 | 958 | <issue_start>username_0: How can I use a VBA code for selecting a value that is for example the first or the last value of a series, if this series is located all in one Cell of Excel?
Is there a code using the right or left application that can be implemented?<issue_comment>username_1: Yes you can use global var on WordPress like as usual doing on PHP like below
**from.php**
```
global $id;
$id = 10;
```
**to.php**
```
global $id;
echo $id;
```
Edit:
As we discussed on the comment using classes is a good way.
**demo1.php**
```
class test{
public $i = 10;
public $j = 20;
public $k = 30;
}
```
**demo2.php**
```
$obj = new test();
echo $obj->i;
echo $obj->j;
echo $obj->k;
```
Upvotes: 0 <issue_comment>username_2: You can include the file with the defined variable in the second file, like this:
anything.php:
```
$var= 'test';
```
something.php:
```
include 'anything.php';
echo $var;
```
Upvotes: 3 [selected_answer] |
2018/03/21 | 379 | 1,091 | <issue_start>username_0: Sorry! I tried to search for the answer on Google and Stackoverflow. But can't find it.
I am using NGINX and the URL I'm trying to access is `https://www.mywebsite.com/newsfeed.rss/`
The above URL shows 404, But if I acces the same URL without `/` in the last of URL, Then It works.
`https://www.mywebsite.com/newsfeed.rss`
So how I can display content on both URLS?<issue_comment>username_1: Yes you can use global var on WordPress like as usual doing on PHP like below
**from.php**
```
global $id;
$id = 10;
```
**to.php**
```
global $id;
echo $id;
```
Edit:
As we discussed on the comment using classes is a good way.
**demo1.php**
```
class test{
public $i = 10;
public $j = 20;
public $k = 30;
}
```
**demo2.php**
```
$obj = new test();
echo $obj->i;
echo $obj->j;
echo $obj->k;
```
Upvotes: 0 <issue_comment>username_2: You can include the file with the defined variable in the second file, like this:
anything.php:
```
$var= 'test';
```
something.php:
```
include 'anything.php';
echo $var;
```
Upvotes: 3 [selected_answer] |
2018/03/21 | 493 | 1,410 | <issue_start>username_0: i'm trying to compare between two set of strings and want to update status column either as 'same' or 'changed' or 'change'.
i have try to use strcmp and concat as below in the picture, but syntax error keep prompted out.
anyone know how to use strcmp and concat at the same time like below?.
My codes :
```
UPDATE DMGE1314
SET status2 =
case
when concat(KodDM14,NamaDM14) = CONCAT(KodDM13,NamaDM13)
then "NO CHANGED",
when strcmp(concat(KodDM14,NamaDM14),concat(KodDM13,NamaDM13)) not like "0"
then "spelling different" else "changed"
end
```
[](https://i.stack.imgur.com/Fctrz.jpg)<issue_comment>username_1: Yes you can use global var on WordPress like as usual doing on PHP like below
**from.php**
```
global $id;
$id = 10;
```
**to.php**
```
global $id;
echo $id;
```
Edit:
As we discussed on the comment using classes is a good way.
**demo1.php**
```
class test{
public $i = 10;
public $j = 20;
public $k = 30;
}
```
**demo2.php**
```
$obj = new test();
echo $obj->i;
echo $obj->j;
echo $obj->k;
```
Upvotes: 0 <issue_comment>username_2: You can include the file with the defined variable in the second file, like this:
anything.php:
```
$var= 'test';
```
something.php:
```
include 'anything.php';
echo $var;
```
Upvotes: 3 [selected_answer] |
2018/03/21 | 551 | 2,103 | <issue_start>username_0: I have a complex nested array of objects like this for which I have to return a new Array(filter) based on `attributeScore > 90`. How will I accomplish this using the javascript .filter or the lodash \_.find() or \_.some function ?
```
trucks:[
{wheels:[
{name:"xyz",
mechanics: [
{engine:'50cc',
attributeScore:100},
{....} ,{...}
]
},
{name:"gcd",
mechanics: [
{engine:'80cc',
attributeScore:90},
{....} ,{...}
]
},
,{...}
]}
,{...}
]
```
I tried a filter like this
```
const fil = trucks.filter(function(item) {
return item.wheels.some(function(tag) {
return tag.mechanics.some(function(ques){
return ques.attributeScore <= 25;
});
});
});
```
but it returns an empty array . My expected return array type should be
```
trucks:[
{wheels:[
{name:"xyz",
mechanics: [
{engine:'50cc',
attributeScore:100},
{....} ,{...}
]
},
,{...}
]}
]
```
Any help appreciated!!<issue_comment>username_1: Try this now,
```
var fill = trucks.map(function(item) {
return item.wheels.map(function(tag) {
return tag.mechanics.filter(function(ques){
return ques.attributeScore == 100;
});
});
});
```
Upvotes: 2 <issue_comment>username_2: If I understand what you are asking, I think this function should do the trick:
```
_.map(trucks, truck => ({
...truck,
wheels: _.filter(_.map(truck.wheels, wheel => ({
...wheel,
mechanics: _.filter(wheel.mechanics, m => m.attributeScore > 90)
})), wheel => wheel.mechanics.length),
}));
```
It's not a terribly elegant solution, but I wind up with the same answer as you were hoping for in your original post.
Upvotes: 1 |
2018/03/21 | 548 | 1,874 | <issue_start>username_0: I am trying to use AJAX to populate my dropdown list and I am returning a 404 with error message from my controller, and Ajax is not catching it...
My return at the controller is
```
return Response()->json(array('error' => '404 car type not found'), 404);
```
And here is my JS
```
$('document').ready(function () {
$('#car_type').bind('changed.bs.select', function () {
$.ajax({
type: 'POST',
url:'carclass/'+$('#car_type').val(),
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown){
alert('status:' + XMLHttpRequest.status + ', status text: ' + XMLHttpRequest.statusText);
},
success: function( json ) {
$.each(json, function(i, obj){
$('#car_class').append($('').text(obj.name).attr('value', obj.id));
});
$('#car\_class').selectpicker('refresh');
}
});
});
});
```
It is returning
```
GET http://localhost:8000/ads/cartype/2 404 (Not Found)
```<issue_comment>username_1: Replace your `error` block with something like this where `xhr.status` will give you the status code of the response.
```
error:function (xhr, ajaxOptions, thrownError){
if(xhr.status==404) {
alert('status:' + xhr.status + ', status text: ' + xhr.statusText);
}
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Use `fail()` instead. You could also use the `done()` callback, which is an alternative to `success`.
```js
$.ajax( "example.php" )
.done(function(data) {
$.each(data.responseJSON, function(i, obj) {
$('#car_class').append($('').text(obj.name).attr('value', obj.id));
});
$('#car\_class').selectpicker('refresh');
})
.fail(function(data) {
alert('status:' + this.status + ', status text: ' + this.statusText);
})
.always(function() {
alert( "complete" );
});
```
Upvotes: 0 |
2018/03/21 | 2,089 | 6,549 | <issue_start>username_0: I need to read the date with weekday. First of all, i need to read the date and weekday then calculate the total weekday, for example:
```
total Sunday :1000
total Monday :1000
......
```
I always get the value is 0.
The input file looks like this:
```
23/10/2005, Sunday
26/07/2016, Tuesday
10/01/1995, Tuesday
14/10/2015, Wednesday
30/09/1982, Thursday
22/09/1993, Wednesday
21/05/1972, Sunday
23/01/2017, Monday
20/05/1974, Monday
27/11/1985, Wednesday
11/07/2005, Monday
06/09/2014, Saturday
16/03/1991, Saturday
09/03/1970, Monday
17/08/2015, Monday
04/05/2010, Tuesday
14/11/2013, Thursday
13/11/2015, Friday
08/10/1995, Sunday
07/09/1986, Sunday
.....
```
which there is 10000.
```
string line;
string day[7] = { "Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
ifstream infile("input.txt");
ofstream validfile("valid.txt");
ofstream invalidfile("invalid.txt");
int total = 0;
int date[2], month[2], year[4];
int Sunday = 0, Monday = 0, Tuesday = 0, Wednesday = 0, Thursday = 0, Friday = 0, Saturday = 0;
char symbol = '/';
char symbol2 = ',';
while (getline(infile, line)) {
total = total++;
}
validfile << "Valid file\n" << "The total record :" << total << endl;
while (!infile.eof()) {
infile >> day[2] >> symbol >> month[2] >> symbol >> year[4] >> symbol2 >> line;
if (line.compare(day[0]) == 0) {
Sunday++;
}
else if (line.compare(day[1]) == 0) {
Monday++;
}
else if (line.compare(day[2]) == 0) {
Tuesday++;
}
else if (line.compare(day[3]) == 0) {
Wednesday++;
}
else if (line.compare(day[4]) == 0) {
Thursday++;
}
else if (line.compare(day[5]) == 0) {
Friday++;
}
else if (line.compare(day[6]) == 0) {
Saturday++;
}
}
cout << "Total Sunday :" << Sunday << endl;
cout << "Total Monday :" << Monday << endl;
cout << "Total Tuesday :" << Tuesday << endl;
cout << "Total Wednesday :" << Wednesday << endl;
cout << "Total Thursday :" << Thursday << endl;
cout << "Total Friday :" << Friday << endl;
cout << "Total Saturday :" << Saturday << endl;
```<issue_comment>username_1: After the 1st loop you've reach to end of file.
After you've reach the end of file you need to go back to the beginning before starting the 2nd loop:
```
//this is the 1st loop in your code:
while (getline(infile, line)) {
total = total++;
}
validfile << "Valid file\n" << "The total record :" << total << endl;
//now you need to rewind:
infile.clear(); //clear EOF state
infile.seekg(0); //back to beginning
//then continue the 2nd loop
while (!infile.eof()) {
```
In addition: you have error in the following line:
```
infile >> day[2] >> symbol >> month[2] >> symbol >> year[4] >> symbol2 >> line;
```
For example:
`infile >> day[2]` will read only one character, not 2. also I guess you write to `day` instead of to `date`.
a possible solution is to use infile.get(date,2) to read 2 bytes, or to read line and copy substrings.
Upvotes: 1 [selected_answer]<issue_comment>username_2: Variables `day`, `month` and `year` will **not** have the expected values from the following line of code, because the indexing means that you are writing to specific character positions within those arrays:
```
infile >> day[2] >> symbol >> month[2] >> symbol >> year[4] >> symbol2 >> line;
```
Here's an alternative, using `getline()` with the expected separator instead:
```
string line;
string day, month, year, weekday, space;
char separator = '/';
ifstream infile("input.txt");
while (getline(infile, line))
{
++total;
}
cout << "total" << total << endl;
//do your stuff.
infile.clear();
infile.seekg(0);
total=0; // just reinitialising to check, you can ignore.
while (getline(infile, day, separator) &&
getline(infile, month, separator) &&
getline(infile, year, ',') &&
getline(infile, space, ' ') &&
getline(infile, weekday))
{
++total;
cout << day << "-" << month<< "-" << year << "-" << weekday<< endl;
//Do your stuff.
}
```
Documentation for `std::getline (string)` is available [here](http://www.cplusplus.com/reference/string/string/getline/).
Let me know if it helps.
Upvotes: 2 <issue_comment>username_3: **First problem**
Your declaration of the array holding weekday names isn't const:
```
string day[7] = ...
```
this will bite your later on (see #4).
**Second problem**
These:
```
int date[2], month[2], year[4];
```
are arrays. You don't want arrays, you simply want integers holding the value of day, month and year:
```
int date, month, year;
```
**Third problem**
Here:
```
while (getline(infile, line)) {
...
}
...
while (!infile.eof()) {
...
}
```
the second loop will **never** execute, because you get to the end of your file in the first loop.
**Fourth problem**
Everything you do here:
```
infile >> day[2] >> symbol >> month[2] >> symbol >> year[4] >> symbol2 >> line;
```
is as wrong and erroneous as it can be:
* Since your variable for storing the day integer is named `date`, you are actually writing to the third position in the array storing the names of weekdays. If `day` was const (see #1), you would get a compiler error, immediately pointing you to this mistake.
* You write outside the size of the arrays. E.g. `month` has size `2`, so you cannot write to index `2`, as it only has indices `0` and `1`. You shouldn't be using arrays anyways for this, see #2.
* You overwrite `symbol` and `symbol2`, instead of checking if the file contains them at the expected position.
* `line` will start with a space, as you only read the comma, but your file separates by comma and space.
**Fifth problem**
Your naming doesn't follow conventions:
```
int Sunday = 0, Monday = 0, Tuesday = 0, Wednesday = 0, Thursday = 0, Friday = 0, Saturday = 0;
```
While still legal code, you should stick to naming conventions, variable names start lower case. Also you should seriously think of better names for your variables. Make them **speak**, e.g. `weekDayNames` instead of `day`.
**Sixth problem**
You are not debugging your code, thus wasting everyone's time. Debug your code and you will **see** what's happening to your variables. You will **see** how often your loops are executed and what happens inside. Then you can figure out **where exactly** your code is going wrong and maybe even why.
Upvotes: 0 |
2018/03/21 | 535 | 1,967 | <issue_start>username_0: Just curious about the difference between type `Any` and `AnyRef` in Scala.
Why does int belongs to `AnyVal` but string belongs to `AnyRef`?
For example:
```
val a: AnyVal = 3
val b: AnyRef = "1"
```<issue_comment>username_1: Any is the supertype of all types. Any has two direct subclasses: AnyVal and AnyRef.
AnyVal represents value types. There are nine predefined value types and they are non-nullable: Double, Float, Long, Int, Short, Byte, Char, Unit, and Boolean.
AnyRef represents reference types. All non-value types are defined as reference types. Every user-defined type in Scala is a subtype of AnyRef. String in scala equals to java.lang.String and is the subtype of AnyRef.
[structure of scala.Any](https://i.stack.imgur.com/O4e5t.png)
Upvotes: 4 <issue_comment>username_2: All of the *Scala primitives* such as Int, Boolean etc extend `AnyVal` interface
And all the *Java primitives* or better say java objects which are in `java.lang` library extends `AnyRef`
interface
for more information read the [unified types](https://docs.scala-lang.org/tour/unified-types.html) which says the following
>
>
> >
> > AnyVal represents value types. There are nine predefined value types and they are non-nullable: Double, Float, Long, Int, Short, Byte, Char, Unit, and Boolean. Unit is a value type which carries no meaningful information. There is exactly one instance of Unit which can be declared literally like so: (). All functions must return something so sometimes Unit is a useful return type.
> >
> >
> > AnyRef represents reference types. All non-value types are defined as reference types. Every user-defined type in Scala is a subtype of AnyRef. If Scala is used in the context of a Java runtime environment, AnyRef corresponds to java.lang.Object
> >
> >
> >
>
>
>
And in your example `val b: AnyRef = "1"` `b` *immutable variable* is treated as *java.lang.Object dataType*.
Upvotes: 3 [selected_answer] |
2018/03/21 | 2,208 | 8,942 | <issue_start>username_0: I am developing web socket application using Hazelcast to share the status of the online users. Everything works fine except one thing that is when one of the application instance goes down or restarts, all user connected to that instance get disconnected and `afterConnectionClosed` of `MessagingHandler` that extends `BinaryWebSocketHandler`. In `afterConnectionClosed`, the status of users which are connected to current node will be updated and these statuses are in Hazelcast. So when it attempts removal of the status from the Hazelcast, it gives the following error:
```
com.hazelcast.core.HazelcastInstanceNotActiveException: State: SHUT_DOWN Operation: class com.hazelcast.map.impl.operation.RemoveOperation
at com.hazelcast.spi.impl.operationservice.impl.Invocation.engineActive(Invocation.java:490)
at com.hazelcast.spi.impl.operationservice.impl.Invocation.doInvoke(Invocation.java:523)
at com.hazelcast.spi.impl.operationservice.impl.Invocation.invoke0(Invocation.java:513)
at com.hazelcast.spi.impl.operationservice.impl.Invocation.invoke(Invocation.java:207)
at com.hazelcast.spi.impl.operationservice.impl.InvocationBuilderImpl.invoke(InvocationBuilderImpl.java:60)
at com.hazelcast.map.impl.proxy.MapProxySupport.invokeOperation(MapProxySupport.java:423)
at com.hazelcast.map.impl.proxy.MapProxySupport.removeInternal(MapProxySupport.java:563)
at com.hazelcast.map.impl.proxy.MapProxyImpl.remove(MapProxyImpl.java:207)
at com.nisheeth.spring.MessageHandler.afterConnectionClosed(MessageHandler.java:57)
at org.springframework.web.socket.handler.WebSocketHandlerDecorator.afterConnectionClosed(WebSocketHandlerDecorator.java:85)
at org.springframework.web.socket.handler.LoggingWebSocketHandlerDecorator.afterConnectionClosed(LoggingWebSocketHandlerDecorator.java:72)
at org.springframework.web.socket.handler.ExceptionWebSocketHandlerDecorator.afterConnectionClosed(ExceptionWebSocketHandlerDecorator.java:78)
at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter.onClose(StandardWebSocketHandlerAdapter.java:141)
at org.apache.tomcat.websocket.WsSession.fireEndpointOnClose(WsSession.java:535)
at org.apache.tomcat.websocket.WsSession.doClose(WsSession.java:481)
at org.apache.tomcat.websocket.WsSession.close(WsSession.java:445)
at org.apache.tomcat.websocket.WsWebSocketContainer.destroy(WsWebSocketContainer.java:960)
at org.apache.tomcat.websocket.server.WsContextListener.contextDestroyed(WsContextListener.java:48)
at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:4792)
at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5429)
at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:226)
at org.apache.catalina.core.ContainerBase$StopChild.call(ContainerBase.java:1435)
at org.apache.catalina.core.ContainerBase$StopChild.call(ContainerBase.java:1424)
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 java.lang.Thread.run(Unknown Source)
at ------ submitted from ------.(Unknown Source)
at com.hazelcast.spi.impl.operationservice.impl.InvocationFuture.resolve(InvocationFuture.java:127)
at com.hazelcast.spi.impl.operationservice.impl.InvocationFuture.resolveAndThrowIfException(InvocationFuture.java:79)
at com.hazelcast.spi.impl.AbstractInvocationFuture.get(AbstractInvocationFuture.java:147)
at com.hazelcast.map.impl.proxy.MapProxySupport.invokeOperation(MapProxySupport.java:424)
at com.hazelcast.map.impl.proxy.MapProxySupport.removeInternal(MapProxySupport.java:563)
at com.hazelcast.map.impl.proxy.MapProxyImpl.remove(MapProxyImpl.java:207)
at com.nisheeth.spring.MessageHandler.afterConnectionClosed(MessageHandler.java:57)
at org.springframework.web.socket.handler.WebSocketHandlerDecorator.afterConnectionClosed(WebSocketHandlerDecorator.java:85)
at org.springframework.web.socket.handler.LoggingWebSocketHandlerDecorator.afterConnectionClosed(LoggingWebSocketHandlerDecorator.java:72)
at org.springframework.web.socket.handler.ExceptionWebSocketHandlerDecorator.afterConnectionClosed(ExceptionWebSocketHandlerDecorator.java:78)
at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter.onClose(StandardWebSocketHandlerAdapter.java:141)
at org.apache.tomcat.websocket.WsSession.fireEndpointOnClose(WsSession.java:535)
at org.apache.tomcat.websocket.WsSession.doClose(WsSession.java:481)
at org.apache.tomcat.websocket.WsSession.close(WsSession.java:445)
at org.apache.tomcat.websocket.WsWebSocketContainer.destroy(WsWebSocketContainer.java:960)
at org.apache.tomcat.websocket.server.WsContextListener.contextDestroyed(WsContextListener.java:48)
at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:4792)
at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5429)
at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:226)
at org.apache.catalina.core.ContainerBase$StopChild.call(ContainerBase.java:1435)
at org.apache.catalina.core.ContainerBase$StopChild.call(ContainerBase.java:1424)
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 java.lang.Thread.run(Unknown Source)
```
I am disabling default shutdown using following properties:
```
config.setProperty(GroupProperty.SHUTDOWNHOOK_ENABLED.getName(), "false");
config.setProperty(GroupProperty.SHUTDOWNHOOK_POLICY.getName(), "GRACEFUL");
```
But still it is still shutdown before the users were disconnecting. Is there a way to configure hazelcast in a way that hazelcast shutdown in the end of the application?<issue_comment>username_1: @nisheeth-shah, It's more like a Spring related issue, since it's Spring that decides the shutdown order of the beans.
What you can do, you can annotate your `MessageHandler` bean with `@DependsOn` annotation and give name of the `HazelcastInstance` bean, like this `@DependsOn("hazelcastInstance")`. Please see this [link](https://nixmash.com/post/using-postconstruct-and-dependson-in-spring) for the explanation. Basically, Spring will start `HazelcastInstance` before creating `MessageHandler` and won't shut down `HazelcastInstance` before `MessageHandler` bean destroyed.
Also, don't disable Hazelcast shutdown hook.
Upvotes: 2 <issue_comment>username_2: I have been trying different methods to handle graceful shutdown of spring websocket connection which also modifies the hazelcast map of online users, but none worked. I finally used `SmartLifecycle` interface. Documentation of this class can be found [here](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/SmartLifecycle.html).
Here is the code that I used for proper shutdown. And yes, it is called before Hazelcast shutdown:
```
@Component
public class AppLifecycle implements SmartLifecycle {
private Logger log = LoggerFactory.getLogger(AppLifecycle.class);
@Autowired
private SampleService sampleService;
@Override
public boolean isAutoStartup() {
log.debug("=========================auto startup=========================");
return true;
}
@Override
public void stop(Runnable runnable) {
sampleService.getSessionMap().forEach((key, session) -> {
try {
session.close(CloseStatus.SERVICE_RESTARTED);
log.debug("disconnecting : {}", key);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
});
log.debug("=========================stop runnable=========================");
new Thread(runnable).start();
}
@Override
public void start() {
log.debug("=========================start=========================");
}
@Override
public void stop() {
log.debug("=========================stop=========================");
}
@Override
public boolean isRunning() {
return true;
}
@Override
public int getPhase() {
return Integer.MAX_VALUE;
}
}
```
Upvotes: 4 [selected_answer]<issue_comment>username_3: You can use `hazelcastInstance.shutdown()` in `@PreDestroy`
ie.
```
@PreDestroy
public void shutDownHazelcast(){
hazelcastInstance.shutdown()
}
```
This will shut down you the hazelcast instance gracefully
Upvotes: 0 |
2018/03/21 | 696 | 2,492 | <issue_start>username_0: I use this script below for show or hidden a few .
The `selected` class in the script is associated with a `display:block` and my start with a class with a `display:none`.
When the page is load all `div` are hidden. But I will like show the first of this, but I can do this?
```
$(document).ready(function(){
$("select[name*='material']").change(function(){
select_changed();
});
});
function select_changed(){
$("div[id*='mat-']").each(function(){
$(this).removeClass('selected');
});
$("select[name*='material']").each(function(){
var selected = $(this).val();
$('#'+selected).addClass('selected');
});
}
```
I have already set an option like first items, but this not show up. I think the problem is all `div` in the begin have a `display:none` class.
How I can do.
For let more clear:
HTML
```
Material 1
Material 2
Materail 1
Materail 2
```
CSS
```
.boxx{
display: none
}
.selected{
display: block;
}
```<issue_comment>username_1: Since you already have written a function for `select_changed()` just invoke that function on ready function do as follows:
```js
$(document).ready(function(){
$("select[name*='material']").change(function(){
select_changed();
});
select_changed() //here you can invoke your function on page ready
});
function select_changed(){
$("div[id*='mat-']").each(function(){
$(this).removeClass('selected');
});
$("select[name*='material']").each(function(){
var selected = $(this).val();
$('#'+selected).addClass('selected');
});
}
```
```css
.boxx{
display: none
}
.selected{
display: block;
}
```
```html
Material 1
Material 2
Materail 1
Materail 2
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: ```js
$(document).ready(function(){
function select_changed(){
$("div[id*='mat-']").each(function(){
$(this).removeClass('selected');
});
$("select[name*='material']").each(function(){
var selected = $(this).val();
$('#'+selected).addClass('selected');
});
};
$("select[name*='material']").change(function(){
select_changed();
});
$("select[name*='material']").change();
});
```
```css
.boxx{
display: none
}
.selected{
display: block;
}
```
```html
Material 1
Material 2
Materail 1Materail 2
```
Upvotes: 0 |
2018/03/21 | 1,184 | 4,121 | <issue_start>username_0: I've got a script that basically access email through IMAP and then finds all the .wav audio and download them into a folder locally on the server.
I'm struggling to get it to access Office 365 through IMAP.
Keeps saying Couldn't open stream {outlook.office365.com:993/imap/ssl/novalidate-cert}Inbox.
&
Cannot connect to {outlook.office365.com:993/imap/ssl/novalidate-cert}INBOX: Too many login failures
See whole script below;
```
php
$MSG_DIR = "D:/Voicemail/Messages/";
$USER = "xx";
$PASS = "xx";
// connect to JARVIS
echo "<div style ='font:11px/21px Arial,tahoma,sans-serif;font-weight: bold;color:#2471b6'Connecting to J.A.R.V.I.S.\n
";
$host = "{outlook.office365.com:993/imap/ssl/novalidate-cert}Inbox";
$mbox=imap_open($host,$USER,$PASS, NULL, 1, array('DISABLE_AUTHENTICATOR' => 'GSSAPI')) or die("Can't connect: " . imap_last_error());
// Look over mailbox
echo "Connection Complete...\n
";
$MC = imap_check($mbox) or die("Can't check for messages");
$overview = imap_fetch_overview( $mbox, "1:".$MC->Nmsgs, 0 ) or die( "Can't get headers");
$countThis = 0;
foreach ( $overview as $email )
{
$subject = $email->subject;
$udate = $email->udate;
if( preg_match('/Voice Message from ([0-9]+)/', $subject, $groups) ||
preg_match('/Voice Message from ([a-zA-Z]\w+)/', $subject, $groups) )
{
$filename = $MSG_DIR."/".$groups[1].date(" d-m H-i-s", $udate).".wav";
if( file_exists( $filename ) )
{
echo "Skipping $filename...\n";
}
else
{
echo "Extracting $filename...\n";
$structure = imap_fetchstructure($mbox,$email->uid, FT_UID) or die( "could not fetch structure");
foreach ( $structure->parts as $part )
{
if( $part->subtype == "X-WAV" || $part->subtype=="WAV" || $part->subtype=="OCTET-STREAM")
{
// found it!
$body = imap_base64( imap_fetchbody( $mbox, $email->uid, 2, FT_UID ) ) or die( "Could not fetch part");
file_put_contents( $filename, $body );
}
else
{
}
}
}
$countThis++;
}
}
echo "Found $countThis Voicemails\r\n";
echo "Disconnecting from J.A.R.V.I.S.\r\n";
imap_close($mbox);
?>
```
This was previously used on Exchange 2010.
Hope someone can help.
Thank you!<issue_comment>username_1: Since you already have written a function for `select_changed()` just invoke that function on ready function do as follows:
```js
$(document).ready(function(){
$("select[name*='material']").change(function(){
select_changed();
});
select_changed() //here you can invoke your function on page ready
});
function select_changed(){
$("div[id*='mat-']").each(function(){
$(this).removeClass('selected');
});
$("select[name*='material']").each(function(){
var selected = $(this).val();
$('#'+selected).addClass('selected');
});
}
```
```css
.boxx{
display: none
}
.selected{
display: block;
}
```
```html
Material 1
Material 2
Materail 1
Materail 2
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: ```js
$(document).ready(function(){
function select_changed(){
$("div[id*='mat-']").each(function(){
$(this).removeClass('selected');
});
$("select[name*='material']").each(function(){
var selected = $(this).val();
$('#'+selected).addClass('selected');
});
};
$("select[name*='material']").change(function(){
select_changed();
});
$("select[name*='material']").change();
});
```
```css
.boxx{
display: none
}
.selected{
display: block;
}
```
```html
Material 1
Material 2
Materail 1Materail 2
```
Upvotes: 0 |
2018/03/21 | 393 | 1,356 | <issue_start>username_0: I have a popup message which is shown every time when users visit my web page. This is annoying and l want to show the pop up message only once. how to do that?
```js
$(document).ready(function () {
$("#popup").hide().fadeIn(1000);
//close the POPUP if the button with id="close" is clicked
$("#close").on("click", function (e) {
e.preventDefault();
$("#popup").fadeOut(1000);
});
});
```
```html
×
CLOSE

```<issue_comment>username_1: Once they've seen it, save it in localStorage.
```
$(document).ready(function () {
const popup = $("#popup");
popup.hide()
if (localStorage.seenPopup) return;
popup.fadeIn(1000);
//close the POPUP if the button with id="close" is clicked
$("#close").on("click", function (e) {
e.preventDefault();
$("#popup").fadeOut(1000);
localStorage.seenPopup = 'true'; // value doesn't matter as long as it's not falsey
});
});
```
Upvotes: 2 <issue_comment>username_2: You could write and check a cookie, like that:
```
...
const showPopup = $.cookie('noPopup');
if (!noPopup) {
$("#popup").hide().fadeIn(1000);
$("#close").on("click", function (e) {
e.preventDefault();
$("#popup").fadeOut(1000);
$.cookie('noPopup', true);
});
}
....
```
Upvotes: 0 |
2018/03/21 | 842 | 2,532 | <issue_start>username_0: I'm trying to convert time statistics from one of our scripts to JSON format for further processing, but have failed to do so. Here's an example of what the statistics output looks like:
```
cmd ls -lah
0m1.964s
cmd echo something
0m4.183s
cmd setup-environment
0m0.401s
```
I would like to have the line starting with "cmd" as the key, and the time value in the next line as "value".
I can get "cmd" as key name and the actual command as cmd.value but that is not exactly what I'm aiming for:
```
cat statistics.txt | jq -R 'split("\n") - [""]' | jq '.[] | if select( contains("cmd")) then { "cmd": . } else { "time": . } end'
```
I also know that "if" and "select" can mean pretty much the same thing with jq, but I don't know how else I could achieve what I want ("else" doesn't even produce anything in my example). This is what I get currently:
```
{
"cmd": "cmd ls -lah"
}
{
"cmd": "cmd echo something"
}
{
"cmd": "cmd setup-environment"
}
```
Can someone help me on this?<issue_comment>username_1: How about combining shell variables and [command substitution](https://www.gnu.org/software/bash/manual/bashref.html#Command-Substitution)?
You can do something like this in a bash script:
```
cmd="cmd ls -lah"
cat << EOF
{
\"cmd\": \"$cmd\",
\"time\": \"$(time $cmd)\"
}
EOF
```
If you don't like the output of `time` or other commands, you can enclose it in a shell function.
```
chrono() {
command=$1
result=$(/bin/time $command >/dev/null 2>&1)
# Awk or sed to give format to the output
}
```
Upvotes: -1 <issue_comment>username_2: **`jq`** + **`paste`** solution:
```
jq -R 'split(",") | {(.[0]) : .[1]}' <(paste -d, - -
```
The output:
```
{
"cmd ls -lah": "0m1.964s"
}
{
"cmd echo something": "0m4.183s"
}
{
"cmd setup-environment": "0m0.401s"
}
```
Upvotes: 0 <issue_comment>username_3: All-jq solution:
```
jq -Rn '{ (inputs): input }' statistics.txt
```
The command-line options are:
* -R for raw input
* -n so that the `inputs` filter sees the first line
### {"cmd": \_, "value": \_}
It might make more sense to produce JSON objects with more structure, e.g. of the form `{"cmd": _, "value": _}`. Assuming the "cmd" line always begins as in statistics.txt, this can also easily be achieved, e.g. by:
```
jq -Rn '{ cmd: inputs[4:], value: input }' statistics.txt
```
### If your jq does not have `inputs`
```
jq -R -s 'split("\n")
| recurse( .[2:] | select(length>0))
| {(.[0]): .[1]}' statistics.txt
```
Upvotes: 1 [selected_answer] |
2018/03/21 | 2,138 | 6,123 | <issue_start>username_0: I transfered some data from infobright to TiDB.
My php code like:
```
$sql='delete from xxx where xxx';
doQuery($sql);
$sql='insert into xxx (...)';
doQuery($sql);
```
I inserted 48595 records, but sum of them is float with 8 digits.
While, the field is defined as float(10,2):
```
mysql> SELECT COUNT(*) FROM adpay;
+----------+
| COUNT(*) |
+----------+
| 48595 |
+----------+
1 row in set (0.28 sec)
mysql> SELECT SUM(t.spends) FROM (SELECT spends FROM adpay LIMIT 90000) t;
+---------------+
| SUM(t.spends) |
+---------------+
| 42583533.50 |
+---------------+
1 row in set (0.37 sec)
mysql> SELECT SUM(spends) FROM adpay;
+-------------------+
| SUM(spends) |
+-------------------+
| 42583533.50033116 |
+-------------------+
1 row in set (0.35 sec)
mysql> show create table adpay;
...
CREATE TABLE `adpay` (
`date` date NOT NULL DEFAULT '0000-00-00',
`adname` varchar(50) NOT NULL DEFAULT '',
`country` char(10) NOT NULL DEFAULT '',
`pf` char(20) NOT NULL DEFAULT '',
`paydate` date NOT NULL DEFAULT '0000-00-00',
`num` int(10) DEFAULT NULL,
`spends` float(10,2) NOT NULL,
`todaynum` int(11) DEFAULT '0',
`todayspends` float(10,2) DEFAULT '0.00',
UNIQUE KEY `sdate` (`date`,`adname`,`country`,`pf`,`paydate`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
```
So, is there a bug with TiDB, or i do some thing wrong ? Any suggestion is appreciated.
---
updating:
```
mysql> show create table test;
+-------+------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+-------+------------------------------------------------------------------------------------------------------------+
| test | CREATE TABLE `test` (
`t` float(10,2) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin |
+-------+------------------------------------------------------------------------------------------------------------+
1 row in set (0.01 sec)''
INSERT INTO test VALUES (1.11);
INSERT INTO test VALUES (1.111);
mysql> SELECT t,t-1.11 FROM test;
+------+----------------------------+
| t | t-1.11 |
+------+----------------------------+
| 1.11 | 0.000000014305114648394124 |
| 1.11 | 0.000000014305114648394124 |
| 1.11 | 0.000000014305114648394124 |
+------+----------------------------+
3 rows in set (0.01 sec)
```
updating 2:
I use just float ,with no digits specified.
```
mysql> show create table test1;
+-------+-------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+-------+-------------------------------------------------------------------------------------------------------+
| test1 | CREATE TABLE `test1` (
`t` float DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin |
+-------+-------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
mysql> INSERT INTO test1 VALUES (1.11);
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO test1 VALUES (1.111);
Query OK, 1 row affected (0.00 sec)
mysql>
mysql> SELECT COUNT(*) FROM test1 WHERE t>ROUND(t, 2) ;
+----------+
| COUNT(*) |
+----------+
| 4 |
+----------+
1 row in set (0.00 sec)
mysql>
mysql> SELECT t,t-1.11 FROM test1;
+-------+----------------------------+
| t | t-1.11 |
+-------+----------------------------+
| 1.11 | 0.000000014305114648394124 |
| 1.111 | 0.0009999418258666015 |
| 1.11 | 0.000000014305114648394124 |
| 1.111 | 0.0009999418258666015 |
+-------+----------------------------+
4 rows in set (0.00 sec)
```
Updating 3:
This table have fields with different type , all of them have 2 digits.
Then I insert 1.11 and 1.111 for each field.
**Only float field will takes data as 8 digits in TiDB:**
```
mysql> create table test2(f float(10,2),db double(10,2), de decimal(10,2));
Query OK, 0 rows affected (1.01 sec)
mysql> insert into test2(f,db,de) values(1.11,1.11,1.11);
Query OK, 1 row affected (0.01 sec)
mysql> insert into test2(f,db,de) values(1.111,1.111,1.111);
Query OK, 1 row affected, 1 warning (0.01 sec)
mysql> select *,f-1.11,db-1.11,de-1.11 from test2;
+------+------+------+----------------------------+---------+---------+
| f | db | de | f-1.11 | db-1.11 | de-1.11 |
+------+------+------+----------------------------+---------+---------+
| 1.11 | 1.11 | 1.11 | 0.000000014305114648394124 | 0 | 0 |
| 1.11 | 1.11 | 1.11 | 0.000000014305114648394124 | 0 | 0 |
+------+------+------+----------------------------+---------+---------+
2 rows in set (0.00 sec)
```
It is ok for all the 3 fields in local mysql 5.6:
```
mysql> create table test2(f float(10,2),db double(10,2), de decimal(10,2));
Query OK, 0 rows affected (0.29 sec)
mysql> insert into test2(f,db,de) values(1.11,1.11,1.11);
Query OK, 1 row affected (0.06 sec)
mysql> insert into test2(f,db,de) values(1.111,1.111,1.111);
Query OK, 1 row affected, 1 warning (0.04 sec)
mysql> select *,f-1.11,db-1.11,de-1.11 from test2;
+------+------+------+--------+---------+---------+
| f | db | de | f-1.11 | db-1.11 | de-1.11 |
+------+------+------+--------+---------+---------+
| 1.11 | 1.11 | 1.11 | 0.00 | 0.00 | 0.00 |
| 1.11 | 1.11 | 1.11 | 0.00 | 0.00 | 0.00 |
+------+------+------+--------+---------+---------+
2 rows in set (0.00 sec)
```<issue_comment>username_1: You can use the ROUND or FORMAT function:
```
SELECT ROUND(SUM(spends), 2) FROM adpay;
```
Upvotes: 0 <issue_comment>username_2: the problem is caused by the improper type inferring of function `sum` and `minus`. We'll fix it soon.
You can create an issue in <https://github.com/pingcap/tidb/issues> next time if you get any problem when using TiDB. ^\_^
Upvotes: 2 [selected_answer] |
2018/03/21 | 3,151 | 10,861 | <issue_start>username_0: how to select the dropdown using md-select and md-option in selenium webdriver.
Select class in not supported.
```html
Filter
Pending
Posted
Checks & eChecks
Deposit
Withdrawal
```<issue_comment>username_1: Suppose you want to select `Pending` from the options. You can do something like this:
```
WebElement option = driver.findElement(By.id("select_option_93"));
option.click();
```
Upvotes: 1 <issue_comment>username_2: The following codes gives the perfecto device connection from selenium driver
```
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import com.perfectomobile.selenium.api.IMobileDevice;
import com.perfectomobile.selenium.api.IMobileDriver;
import com.perfectomobile.selenium.api.IMobileWebDriver;
import com.perfectomobile.selenium.params.analyze.text.MobileTextMatchMode;
public class BofaApp_app extends PerfectoMobileBasicTest implements Runnable{
/*
*
* Class Name : PerfectoMobileBasicTest
* Author : <NAME>
\* Date : Dec 6th 2013
\*
\* Description :
\* Mobile Native application test
\* The test open the BOFA app (on a real device) and looks for an ATM.
\* This test contains IMobileWebDriver (extension to webdriver), which allows the to get native and visual objects on mobile app
\*
\*/
public BofaApp\_app(IMobileDriver driver) {
super(driver);
}
@Override
public void execTest() {
IMobileDevice device = ((IMobileDriver) \_driver).getDevice(\_DeviceId);
device.open();
device.home();
IMobileWebDriver webDriver = \_driver.getDevice(\_DeviceId).getVisualDriver();
webDriver.findElement(By.linkText("Bofa")).click();
IMobileWebDriver init = \_driver.getDevice(\_DeviceId).getVisualDriver();
init.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
init.manageMobile().visualOptions().textMatchOptions().setMode(MobileTextMatchMode.LAST);
init.findElement(By.linkText("Account")).click();
webDriver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
webDriver.findElement(By.linkText("Save this online"));
webDriver.manageMobile().visualOptions().textMatchOptions().setMode(MobileTextMatchMode.LAST);
webDriver.findElement(By.linkText("Locations")).click();
webDriver.findElement(By.linkText("Find Bank of America ATMs"));
IMobileWebDriver zip = \_driver.getDevice(\_DeviceId).getVisualDriver();
zip.manageMobile().visualOptions().textMatchOptions().setMode(MobileTextMatchMode.LAST);
zip.findElement(By.linkText("zip code")).click();
sleep(2000);
zip.findElement(By.linkText("zip code")).click();
sleep(2000);
webDriver.manageMobile().visualOptions().textMatchOptions().setMode(MobileTextMatchMode.LAST);
webDriver.manageMobile().visualOptions().ocrOptions().setLevelsLow(120);
webDriver.findElement(By.linkText("Code")).sendKeys("02459");
zip.findElement(By.linkText("Done")).click();
zip.findElement(By.linkText("Go")).click();
webDriver.findElement(By.linkText("Newton MA"));
}
}\*
public class Constants
{
/\*\* Project Constants \*/
public static final String REPORT\_LIB = "C:\\Test\\";
public static final String HTML\_REPORT\_NAME = "Total.html";
public static final String PM\_USER = "<EMAIL>";
public static final String PM\_PASSWORD = "\*\*\*\*\*\*\*\*\*\*\*\*\*";
public static final String PM\_CLOUD = "prerelease.perfectomobile.com";
}
public interface ExecutionReporter {
/\*
\*
\* Class Name : ExecutionReporter
\* Author : <NAME>
\* Date : Dec 6th 2013
\*
\* Description :
\* Reporter allows you to build an summary report which aggregate all the executions the results and the link for the specific test report
\* You can find an HTML reporter in this project
\*
\*/
public void reportHeader (String title);
public void addLine(String testName,String deviceID,String repID,boolean status);
public void closeRep();
}
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/\*
\*
\* Class Name : HTMLReporter
\* Author : <NAME>
\* Date : Dec 6th 2013
\*
\* Description :
\* implements ExecutionReporter and create an HTML summary report
\*
\*/
public class HTMLReporter implements ExecutionReporter {
BufferedWriter \_bw = null;
public HTMLReporter (String title )
{
reportHeader(title);
}
public void reportHeader (String title)
{
String repName = Constants.REPORT\_LIB+ Constants.HTML\_REPORT\_NAME;
File f = new File (repName) ;
try {
\_bw = new BufferedWriter(new FileWriter(f));
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
\_bw.write(" Date :"+dateFormat.format(cal.getTime())+"
");
\_bw.write(" Test Name: "+title+"
");
\_bw.write("");
\_bw.write("");
\_bw.write("
");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void addLine(String testName,String deviceID,String repID,boolean status)
{
try {
\_bw.write("|");
\_bw.write(" "+testName+" |");
\_bw.write(" "+deviceID+" |");
\_bw.write(" [Report](\""+repID+"\") |");
\_bw.write(" "+status+" |");
\_bw.write("
");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void closeRep()
{
try {
\_bw.write("
");
\_bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
import java.lang.reflect.Constructor;
import com.perfectomobile.selenium.\*;
import com.perfectomobile.selenium.api.\*;
public class MobileTest {
/\*
\*
\* Class Name : MobileTest
\* Author : <NAME>
\* Date : Dec 6th 2013
\*
\* Description :
\* Mobile Executer gets list of test and devices and execute it on the available devices
\* in this example the list arrive form array [] []
\* The tests run on real devices in Perfecto Mobile cloud
\*/
public static void main(String[] args) {
System.out.println("Script started");
String host = Constants.PM\_CLOUD;
String user = Constants.PM\_USER;
String password = Constants.PM\_PASSWORD;
String[] [] testcase ={
// {"PerfectoTestCheckFlight","3230D2<PASSWORD>CF6D"},
// {"PerfectoTestCheckFlight","4A8203C8DBAB382EE6BB8021B825A736CA734484"},
{"BofaApp\_app","4A8203C8DBAB382EE6BB8021B825A736CA734484"},
// {"usAirways","3230D2D238BECF6D"}
};
ExecutionReporter reporter = new HTMLReporter("Regression Test Tesults");
try {
for(int i =0; i < testcase.length; i++)
{
IMobileDriver driver = new MobileDriver(host, user, password);
String className = testcase[i][0];
String device = testcase[i][1];
PerfectoMobileBasicTest test = null;
Constructor con = null;
try {
con = Class.forName(className).getConstructor(IMobileDriver.class);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
test = (PerfectoMobileBasicTest)con.newInstance(driver);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
//PerfectoMobileBasicTest test = new PerfectoTestCheckFlight(driver);
test.setDeviceID(device);
Thread t = new Thread(test);
t.start();
reporter.addLine(className,device,test.getRepName(),test.getStatus());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
reporter.closeRep();
}
}
}
import java.io.File;
import java.io.InputStream;
import com.perfectomobile.httpclient.MediaType;
import com.perfectomobile.httpclient.utils.FileUtils;
import com.perfectomobile.selenium.api.IMobileDriver;
/\*
\*
\* Class Name : PerfectoMobileBasicTest
\* Author : <NAME>
\* Date : Dec 6th 2013
\*
\* Description :
Basic abstract perfecto mobile test - Each test need to extend this class and implement the actual test in the PerfectoMobileBasicTest
\* This basic test handles the driver and the device
\*/
public abstract class PerfectoMobileBasicTest implements Runnable{
String \_DeviceId = null;
IMobileDriver \_driver;
boolean \_status = true;
@Override
public void run() {
try
{
execTest();
}catch (Exception e)
{
\_status = false;
}
closeTest();
getRep(MediaType.HTML);
}
public PerfectoMobileBasicTest (IMobileDriver driver)
{
\_driver = driver;
}
public Boolean getStatus() {
return \_status ;
}
public void setDeviceID(String Device) {
\_DeviceId= Device;
}
public String getRepName() {
String className = this.getClass().getName();
String name = Constants.REPORT\_LIB+className+\_DeviceId+".HTML";
return name;
}
public void getRep(MediaType Type) {
InputStream reportStream = ((IMobileDriver) \_driver).downloadReport(Type);
if (reportStream != null) {
File reportFile = new File(getRepName());
FileUtils.write(reportStream, reportFile);
}
}
public void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
}
}
public void closeTest( ) {
\_driver.quit();
}
public abstract void execTest() throws Exception ;
}\*
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import com.perfectomobile.selenium.api.IMobileDevice;
import com.perfectomobile.selenium.api.IMobileDriver;
import com.perfectomobile.selenium.api.IMobileWebDriver;
/\*
\*
\* Class Name : PerfectoTestCheckFlight
\* Author : <NAME>
\* Date : Dec 6th 2013
\*
\* Description :
\* Mobile web test
\* the test go to united.com (on a real device) and check the status of flights number 84
\* it use a web driver which connected to Perfecto Mobile cloud.
\* the test is based on a webDriver test
\*/
public class PerfectoTestCheckFlight extends PerfectoMobileBasicTest implements Runnable{
public PerfectoTestCheckFlight(IMobileDriver driver) {
super(driver);
}
@Override
public void execTest() {
IMobileDevice device = ((IMobileDriver) \_driver).getDevice(\_DeviceId);
device.open();
device.home();
//device.getScreenText()
//device.checkpointText("search");
WebDriver webDriver = device.getDOMDriver ("www.united.com");
webDriver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
webDriver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
//sleep(2000);
question?
String url = webDriver.getCurrentUrl();
String title = webDriver.getTitle();
System.out.println("url: " + url + ", title: " + title);
WebElement webElement = webDriver.findElement(By.xpath("(//#text)[53]"));
webElement.click();
webElement = webDriver.findElement(By.xpath("(//@id=\"FlightNumber\")[1]"));
webElement.sendKeys("84");
webDriver.findElement(By.xpath("(//INPUT)[5]")).click();
}\*
```
Upvotes: 0 |
2018/03/21 | 2,090 | 6,304 | <issue_start>username_0: I'm currently trying to code a Shiny-App and close to solution, I want to reach. However, there are some issues, that I'm not able to solve...
```
if(!require(shiny)){
install.packages("shiny")
require(shiny)
}
if(!require(tidyverse)){
install.packages("tidyverse")
require(tidyverse)
}
if(!require(readxl)){
install.packages("readxl")
require(readxl)
}
if(!require(lubridate)){
install.packages("lubridate")
require(lubridate)
}
prodpromonat <- tibble(prodmonat = c("2008-01-01", "2008-02-01", "2008-03-01", "2008-04-01", "2008-05-01", "2008-06-01", "2008-07-01", "2008-08-01"),
n = c("3216", "3268", "2398", "2987", "4003", "3103", "3064", "2786"))
prodpromonat$prodmonat <- as.Date(prodpromonat$prodmonat)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
sliderInput(
"zeitraum",
"Produktionszeitraum",
min = min(prodpromonat$prodmonat),
max = max(prodpromonat$prodmonat),
value = c(max(prodpromonat$prodmonat)-90, max(prodpromonat$prodmonat))
),
fluidRow(
radioButtons(
"farbschema",
"Farbschema",
choices = c("Einfarbig", "Zweifarbig"),
selected = "Einfarbig"
)
),
fluidRow(
uiOutput("farbwahl")
)
),
mainPanel(
tabsetPanel(
tabPanel(
title = "Produktionsmenge" ,
plotOutput(
outputId = "produktionsmenge"
)
)
)
)
))
server <- function(input, output, session){
farbeninput <- reactive({
switch(input$farbschema,
"Zweifarbig" = c(input$farbe1, input$farbe2),
"Einfarbig" = c(input$farbe1, input$farbe1)
)
})
filter_produktionsmenge <- reactive({
min <- filter(prodpromonat, prodmonat >= floor_date(input$zeitraum[1], "month"))
max <- filter(prodpromonat, prodmonat <= floor_date(input$zeitraum[2], "month"))
semi_join(min, max, by = "prodmonat")
})
output$farbwahl <- renderUI({
switch(input$farbschema,
"Zweifarbig" = tagList(textInput("farbe1", "Farbe 1", value = "#808080"), textInput("farbe2", "Farbe 2", value = "#1E90FF")),
"Einfarbig" = textInput("farbe1", "Farbe", value = "#808080")
)
})
output$produktionsmenge <- renderPlot({
ggplot(filter_produktionsmenge(), aes(factor(prodmonat), n)) +
geom_bar(stat="identity", aes(fill = factor(as.numeric(month(prodmonat) %% 2 == 0)))) +
scale_fill_manual(values=rep(farbeninput())) +
xlab("Produktionsmonat") +
ylab("Anzahl produzierter Karosserien") +
theme(legend.position = "none")
})
}
shinyApp(ui, server)
```
Issue #1: In the sliderInput i provide every single day within the selected timespan, whereas i only want to provide only the existing months, preferably without giving any hint for the day. Every solution i tried to just print "%Y-%m" produces an error, so i sticked to the days...
Issue #2: Is there any possibility to define a color-vector before using the uiOutput? Right now it does almost work as i planned, but there is an error shown before the rendered UI is finished rendering and shown in the sidebar. My guess is, that the vector is not existing until the renderUI is finished, as the error reads "Insufficient values in manual scale. 2 needed but only 0 provided.". So i'd like to initialise it. Same is valid for changing to the two-color mode for the first time.
Do you have any ideas on how to solve those issues? Thanks alot!
Cheers!
**EDIT:**
Found solutions to issues before. However, issues #1 and #2 still exist.
\*edit: removed a bracket from the code<issue_comment>username_1: For issue #1, you just have to add the timeFormat argument to your sliderInput, like this
```
sliderInput(
"zeitraum",
"Produktionszeitraum",
min = min(prodpromonat$prodmonat),
max = max(prodpromonat$prodmonat),
timeFormat = "%Y-%m",
value = c(max(prodpromonat$prodmonat)-90, max(prodpromonat$prodmonat))
),
```
Upvotes: 0 <issue_comment>username_2: Issue #1:
---------
Add `timeFormat = "%Y-%m"` to the sliderInput (already answered by username_1)
Issue #2:
---------
The problem stems from some dependency issue:
* `renderPlot` is depending on `farbeninput` and `filter_produktionsmenge`. The plot will be rendered every time when:
+ `farbeninput` changes,
+ The sliders are modified, thus the data is recalculated via `filter_produktionsmenge`.
If you add print statements to every block you can see that `renderPlot` is called twice because `farbeninput` changes twice.
```
[1] "renderUI"
[1] "renderPlot"
[1] "farbeninput"
[1] "renderPlot"
[1] "farbeninput"
[1] "filter_produkt"
```
Why is this happening?
----------------------
`farbeninput` is dependent of `input$farbschema`, `input$farbe1` and `input$farbe2`. This means that if any of those inputs change, `farbeninput` will be recalculated.
When changing `input$farbschema` `farbeninput` is rendered twice:
1. Because `input$farbschema` changed.
2. When the `textInput`s are rendered in the UI.
This is what caused the warnings shown!
Solution
--------
You need to make `farbeninput` so that it is only calculated after the `textInput`s have been rendered. You can achieve this using `req`.
For example: If the value of `input$farbschema` is `"Zweifarbig"`, and either `input$farbe1` or `input$farbe2` is not rendered a `NULL` value is returned. If both are rendered then `c(input$farbe1, input$farbe2)` is returned as normal.
```
farbeninput <- reactive({
switch(input$farbschema,
"Zweifarbig" = {
req(input$farbe1)
req(input$farbe2)
c(input$farbe1, input$farbe2)
},
"Einfarbig" = {
req(input$farbe1)
c(input$farbe1, input$farbe1)
}
)
})
```
Add `req(farbeninput())` to `renderPlot` to avoid rendering when `farbeninput` is `NULL`:
```
output$produktionsmenge <- renderPlot({
req(farbeninput())
ggplot(filter_produktionsmenge(), aes(factor(prodmonat), n)) +
geom_bar(stat="identity", aes(fill = factor(as.numeric(month(prodmonat) %% 2 == 0)))) +
scale_fill_manual(values=rep(farbeninput())) +
xlab("Produktionsmonat") +
ylab("Anzahl produzierter Karosserien") +
theme(legend.position = "none")
})
```
Upvotes: 2 [selected_answer] |
2018/03/21 | 434 | 1,843 | <issue_start>username_0: We are using Hangfire, failing jobs should be retried. We use the following approach to specify the number of retry attempts:
```
GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute { Attempts = 3 });
```
Our question is: where do we have to configure this filter? At the program which puts the items into the queue or at the processing service which processes the queue items?<issue_comment>username_1: You configure the filter at the processing service, it is the same as the per method attribute as stated in the docs
Upvotes: 1 [selected_answer]<issue_comment>username_2: Hope this solution may help to those guys, who are still looking for the solution on Hangfire Retries flow.
If you are using .Net6 then in the Program.cs
OR
If you are using .NetCore5 or older version then in the Startup.cs
In "configure the HTTP request pipeline section"
app.UseHangfireDashboard();//below to the this line add below global filter
GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute { Attempts = 3, DelaysInSeconds = new int[] { 1200 } });
Where Attempts = 3 re-tries thrice on failure and DelaysInSeconds is the duration gap to retry after 20 mins = 60\*20 = 1200 seconds.
Upvotes: 0 <issue_comment>username_3: For .NET Core 7.0
```
// Add Hangfire services.
builder.Services.AddHangfire(x=> x
..........................................
..........................................
..........................................
..........................................
).UseFilter(new AutomaticRetryAttribute
{
Attempts = 5,
LogEvents = true,
OnAttemptsExceeded = AttemptsExceededAction.Fail,
DelaysInSeconds = new int[5] { 1, 2, 3}
})
```
Upvotes: 1 |
2018/03/21 | 799 | 2,411 | <issue_start>username_0: I have table with this data.
```
ID IMPACT TICKETID OWNER OWNERGROUP
1 1 TICKET1001 GROUP1
2 2 TICKET1001 USER1
3 3 TICKET1001 USER1
4 4 TICKET1001 GROUP1
5 5 TICKET1001 USER2
6 6 TICKET1001 GROUP1
7 7 TICKET1001 USER1
8 8 TICKET1002 GROUP1
9 9 TICKET1003 GROUP1
10 10 TICKET1003 USER1
```
I want to summarize based on the OWNER column IMPACT value for all Tickets and I know how to do that part.
```
SELECT OWNER, SUM (IMPACT)
FROM TABLE
WHERE OWNER IS NOT NULL
GROUP BY OWNER
```
So the result in that case will be:
```
USER1 22 (2+3+7+10)
USER2 5 (5)
```
BUT, I need also to get the the value from the previous row where user wasn't the owner of the ticket but after that row he took the ownership.
Ticket is always first delegated to the group (GROUP1) and then user takes the ownership.
So it means that I should count for the USER1 value from the ID 1 and 6 and 9 (because he was the next first owner after those rows) and for the USER2 value from the ID 4 (because USER2 was the first next owner of the ticket).
So the final result for my grouping should be:
```
USER1 38 (1+2+3+6+7+9+10)
USER2 9 (4+5)
```
TICKET1002 does not have OWNER value at all so it should not be counted!!!
Is this possible to have this calculation?
Thank you in advance<issue_comment>username_1: Here is the solution for your problem:
```
SELECT Owner, SUM(Impact)
FROM
(
SELECT
@id:=ID, IMPACT, TICKETID,
CASE WHEN OWNER IS NULL
THEN (SELECT OWNER FROM TABLE1 WHERE ID = @id + 1 AND OWNERGROUP IS NULL)
ELSE
OWNER
END AS OWNER,
OwnerGroup
FROM Table1 AS s
) AS t
WHERE OWNER IS NOT NULL
Group BY OWNER;
```
**OUTPUT:**
```
Owner SUM(Impact)
USER1 38
USER2 9
```
Here is the link to the demo:
>
> <http://sqlfiddle.com/#!9/5a614b/22>
>
>
>
Upvotes: 1 <issue_comment>username_2: Simply use `lag()`:
```
select owner,
(sum(impact) +
coalesce(sum(case when prev_owner is null then prev_impact end), 0)
) as impact
from (select t.*,
lag(impact) over (order by id) as prev_impact,
lag(owner) over (order by id) as prev_owner
from t
) t
where owner is not null
group by owner;
```
Upvotes: 3 [selected_answer] |
2018/03/21 | 486 | 1,375 | <issue_start>username_0: I am really dumb. Please help me out by explaining the output:
```
#include
union x
{
int a;
char b;
double c;
};
int main()
{
union x x[3] = {{1}, {'a'}, {1.2}};
int i;
for(i = 0; i < 3; i++)
printf("%d , %d , %lf\n", x[i].a, x[i].b, x[i].c);
return 0;
}
```
Output:
[](https://i.stack.imgur.com/biIxj.png)<issue_comment>username_1: Here is the solution for your problem:
```
SELECT Owner, SUM(Impact)
FROM
(
SELECT
@id:=ID, IMPACT, TICKETID,
CASE WHEN OWNER IS NULL
THEN (SELECT OWNER FROM TABLE1 WHERE ID = @id + 1 AND OWNERGROUP IS NULL)
ELSE
OWNER
END AS OWNER,
OwnerGroup
FROM Table1 AS s
) AS t
WHERE OWNER IS NOT NULL
Group BY OWNER;
```
**OUTPUT:**
```
Owner SUM(Impact)
USER1 38
USER2 9
```
Here is the link to the demo:
>
> <http://sqlfiddle.com/#!9/5a614b/22>
>
>
>
Upvotes: 1 <issue_comment>username_2: Simply use `lag()`:
```
select owner,
(sum(impact) +
coalesce(sum(case when prev_owner is null then prev_impact end), 0)
) as impact
from (select t.*,
lag(impact) over (order by id) as prev_impact,
lag(owner) over (order by id) as prev_owner
from t
) t
where owner is not null
group by owner;
```
Upvotes: 3 [selected_answer] |
2018/03/21 | 504 | 1,491 | <issue_start>username_0: What is the regular expression to be used to catch anything in the database which is **not** of the expression **MM/DD/YYYY**.
(I want everything which is apart from the above mentioned format, could be dd-mon-yy or yyyy/mm/dd etc)
I am using the below regexp query
```
select birth_date FROM table_name where not regexp_like (birth_date, '[0-9][0-9]/[0-9][0-9]/[0-9]{4}');
```<issue_comment>username_1: Firstly, a suggestion to you , don't use a `VARCHAR2 / CHAR` type for DATEs in database.
You may create a function using `TO_DATE`
```
CREATE OR REPLACE FUNCTION validmmddyyyy (p_str IN VARCHAR2)
RETURN NUMBER
AS
V_date DATE;
BEGIN
V_Date := TO_DATE (p_str, 'MM/DD/YYYY');
RETURN 1;
EXCEPTION
WHEN OTHERS
THEN
RETURN 0;
END;
select validmmddyyyy('09/12/2018') from DUAL;
1
select validmmddyyyy('13/12/2018') from DUAL;
0
select validmmddyyyy('2018/12/01') from DUAL;
0
```
Use your query like,
```
select birth_date FROM table_name where validmmddyyyy(birth_date) = 0
```
If you are lucky enough to use Oracle 12c R2, you could make use of `DEFAULT..ON..CONVERSION ERROR` clause of `TO_DATE`
```
SELECT *
FROM table_name
WHERE TO_DATE (birth_date default null on conversion error,'MM/DD/YYYY') IS NULL
```
Upvotes: 2 <issue_comment>username_2: You can use the below query to get other than the required format :
select \* from dual where not regexp\_like('2013/24/feb','[0-9]{2}.[[:alpha:]]{3}.[0-9]{4}')
Upvotes: -1 |
2018/03/21 | 721 | 2,852 | <issue_start>username_0: I know that there are limitations in Kotlin to inherit from a data class. I learn't more while going through this [discussion](https://discuss.kotlinlang.org/t/data-class-inheritance/4107).
As data class in Kotlin are similar to POJO in Java. Should we not follow inheritance in Java POJO classes as well? To sum it up, is it because of the limitations in Kotlin that we are are not allowed to inherit from data classes or there is a flaw in design if you are doing so.
To break it down into a simpler question. Is it wrong to inherit from a POJO class in Java?<issue_comment>username_1: In Kotlin, you can't inherit from a data class because there is no sensible way for the compiler to generate all the methods that are automatically provided for data classes.
In Java, there are no compiler-generated implementations of methods such as `equals`, `hashCode` and `toString`, and you're free to implement them in a way which would be the most sensible in your situation. Therefore, there's no reason why it would be wrong to inherit from a POJO.
Upvotes: 3 <issue_comment>username_2: A `data class` is not the equivalent of a POJO, it does more than that, which is why its inheritance is restricted.
Take a simple POJO:
```
public class User {
private String name;
private int age;
public String getName() { return name; }
public int getAge() { return age; }
public void setName(final String name) { this.name = name; }
public void setAge(final int age) { this.age = age; }
public User(final String name, final int age) {
this.name = name;
this.age = age;
}
}
```
The equivalent of this in Kotlin is *not* a data class, but just a simple class like this:
```
class User(var name: String, var age: Int)
```
This will create two mutable properties (fields, plus getters and setters), and the constructor. This is already equivalent to the above POJO.
What adding the [`data`](https://kotlinlang.org/docs/reference/data-classes.html) modifier does on top of this is generate `equals`, `hashCode`, `toString` methods. It also adds some Kotlin-specific methods: `componentN` methods for [destructuring declarations](https://kotlinlang.org/docs/reference/multi-declarations.html#destructuring-declarations), and the `copy` method.
These generated methods, specifically the first three mentioned above get complicated to define if data classes inherit from each other. See this in detail in the [KEEP](https://github.com/Kotlin/KEEP/blob/master/proposals/data-class-inheritance.md) about this topic. See also [this](https://stackoverflow.com/questions/35921234/kotlin-sealed-class-cannot-contain-data-classes-why) and [this](https://blog.jetbrains.com/kotlin/2015/09/feedback-request-limitations-on-data-classes/) discussion on the topic.
Upvotes: 5 [selected_answer] |
2018/03/21 | 693 | 2,345 | <issue_start>username_0: Firstly, I wanted to say that I am quite new to javascript, thus I would ask you not to criticise me that much.
I wonder, how can I implement the dynamical update of webpage image and it should load a photo from another webpage. I was working with javascript and implemented some functionality, but it is not giving the desired results.
I have searched the Web, but there wasn't anything fitting the above mentioned requirements.
Thus, could anyone please help me figure out the solution to my issue?
```
var imageRep = document.createElement('img'), src='http://www.free.fr/freebox/im/logo\_free.png';
var parent=document.getElementById("div1");
var child=document.getElementById('change').src;
parent.replaceChild(imageRep,child);
```
Here is html part:
```
[](story-ck.html)
```<issue_comment>username_1: ```
var imageRep = document.createElement('img');
imageRep.src = 'http://www.free.fr/freebox/im/logo_free.png';
var oldImage = document.getElementById('change');
parent.replaceChild(imageRep, oldImage);
```
Though if you want to do this more than once, and if there's nothing preventing you from doing so, it would be easier to just replace the `.src` of the target image element, rather than replacing the image entirely:
```
document.querySelector('#change').src = 'http://www.free.fr/freebox/im/logo_free.png';
```
Upvotes: 1 [selected_answer]<issue_comment>username_2: Just change the `src` attribute and set its value to the new image url:
```
var image = document.getElementById('change');
image.src = 'http://www.free.fr/freebox/im/logo_free.png';
```
Upvotes: 0 <issue_comment>username_3: ```js
var current=0;
var images = ["1.jpg", "2.jpg", "3.jpg"];
setInterval(function(){
document.getElementById('main').src=images[current++%images.length];
},2000);
```
```html
![]()
```
Here's the clear way to handle image rotation.
Upvotes: 0 <issue_comment>username_4: ```js
var change = document.getElementById('change');
function changeImg(){
change.src = 'http://s5.tinypic.com/98yjb6_th.jpg'
}
```
```html
"
change image
```
Upvotes: 1 <issue_comment>username_5: well you need jquery..
```
$(div).html("
```
this will change your content dynamically by pushing html tags to your page
Upvotes: 0 |
2018/03/21 | 1,038 | 3,512 | <issue_start>username_0: I am new in swift.I have created simple login screen .I have two issues coming with loginviewController.swift
Issue 1 # i dont know how to compare the two image that is displayed in button . I have used if checkbox.setImage(img, for: .normal) for comparing image that is displayed in side button for toggle action between checked and unchecked
```
let img = UIImage(named:"check [email protected]")
let img2 = UIImage(named:"uncheck box.png")
@IBOutlet weak var checkbox: UIButton!
@IBAction func checkbox(_ sender: Any) {
if checkbox.setImage(img, for: .normal)
{
checkbox.setImage(img , for: .normal)
}
else{
checkbox.setImage(img2, for: .normal)
}
}
```
Issue 2 # I am trying to high light the bottom borders of text field .i am writing the code for highlighting two text field but it is highlighting only single text field
```
func boaderSetting() {
let border = CALayer()
let width = CGFloat(1.0)
border.borderColor = UIColor.orange.cgColor
border.frame = CGRect(x: 0, y: username_input.frame.size.height - width, width: username_input.frame.size.width, height: username_input.frame.size.height)
border.borderWidth = width
username_input.layer.addSublayer(border)
username_input.layer.masksToBounds = true
///
let border1 = CALayer()
let width1 = CGFloat(1.0)
border1.borderColor = UIColor.orange.cgColor
border1.frame = CGRect(x: 0, y: password_input.frame.size.height - width1, width: password_input.frame.size.width, height: password_input.frame.size.height)
border1.borderWidth = width1
password_input.layer.addSublayer(border)
password_input.layer.masksToBounds = true
}
```
how to
->compare image displayed in button with other image
-> hight light the bottom border of both text field .
you can download the project from this link <https://drive.google.com/file/d/1zjNUBXZ-9WL4DTglhMXIlN-TpaO5IXBz/view?usp=sharing><issue_comment>username_1: ```
var imageRep = document.createElement('img');
imageRep.src = 'http://www.free.fr/freebox/im/logo_free.png';
var oldImage = document.getElementById('change');
parent.replaceChild(imageRep, oldImage);
```
Though if you want to do this more than once, and if there's nothing preventing you from doing so, it would be easier to just replace the `.src` of the target image element, rather than replacing the image entirely:
```
document.querySelector('#change').src = 'http://www.free.fr/freebox/im/logo_free.png';
```
Upvotes: 1 [selected_answer]<issue_comment>username_2: Just change the `src` attribute and set its value to the new image url:
```
var image = document.getElementById('change');
image.src = 'http://www.free.fr/freebox/im/logo_free.png';
```
Upvotes: 0 <issue_comment>username_3: ```js
var current=0;
var images = ["1.jpg", "2.jpg", "3.jpg"];
setInterval(function(){
document.getElementById('main').src=images[current++%images.length];
},2000);
```
```html
![]()
```
Here's the clear way to handle image rotation.
Upvotes: 0 <issue_comment>username_4: ```js
var change = document.getElementById('change');
function changeImg(){
change.src = 'http://s5.tinypic.com/98yjb6_th.jpg'
}
```
```html
"
change image
```
Upvotes: 1 <issue_comment>username_5: well you need jquery..
```
$(div).html("
```
this will change your content dynamically by pushing html tags to your page
Upvotes: 0 |
2018/03/21 | 359 | 1,232 | <issue_start>username_0: I want to do a simple file rename in a gradle task. I have a jar called project-1.5.jar under the folder src and I want the jar to be renamed to just project.jar
So,
project/**project-1.5.jar** to project/**project.jar** using **gradle**
Any ideas are much appreciated.<issue_comment>username_1: The rename method should do the trick.
```
task renameArtifacts (type: Copy) {
from ('project/')
include 'project-1.5.jar'
destinationDir file('project/')
rename 'project-1.5.jar', "project.jar"
}
```
Upvotes: 5 [selected_answer]<issue_comment>username_2: For me this worked - does not leave source files (no duplications).
```
task pdfDistributions(type: Sync) {
from('build/asciidoc/pdf/docs/asciidoc/')
into('build/asciidoc/pdf/docs/asciidoc/')
include '*.pdf'
rename { String filename ->
filename.replace(".pdf", "-${project.version}.pdf")
}
}
```
Upvotes: 3 <issue_comment>username_3: Gradle allows to call ant tasks from your task implementation.
It makes moving files as easy as
```
ant.move(file:'oldFile.txt', tofile:'newfile.txt')
```
Upvotes: 2 <issue_comment>username_4: Late .. but gradle provide project.file('xxx').renameTo('zzz')
Upvotes: 0 |
2018/03/21 | 2,624 | 9,024 | <issue_start>username_0: Im trying to make an image spin when you click it. The more you click it the faster it spins, and if you stop clicking it will slow down over time.
The problem is that the only way to spin an object without jQuery is with the "transform" property in CSS (What I know of at least). Is there any way to use JavaScript variables in CSS? Or is there another way to spin my image? Or will I need to use jQuery?
Code:
```js
var spinner = document.getElementById("spinner");
var speed = 0;
var addSpeed = 10;
var slowSpeed = 2;
//Activates Slowdown
window.onload = loop();
//Speed up
function spin() {
if (speed < 0) {
speed = speed + 10;
loop()
} else {
speed = speed + 10;
}
}
spinner.addEventListener('click', spin);
//Slowdown
function loop() {
setTimeout(
function slow() {
speed = speed - slowSpeed;
document.getElementById("speed").innerHTML = speed;
if (speed > 0) {
loop();
}
}, 1000)
}
//Selectors
function wheel() {
spinner.src = "http://pngimg.com/uploads/car_wheel/car_wheel_PNG23305.png";
}
function spiral() {
spinner.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/Black_bold_spiral.svg/2000px-Black_bold_spiral.svg.png";
}
```
```css
#spinner {
width: 500px;
}
#spinner {
transform: rotate("speed"deg);
}
/* The "speed" is the variable I want to use from the JavaScript */
```
```html

#### N/A
Wheel
Spiral
```<issue_comment>username_1: No, you can not use javascript variables inside css, but you can change the style of an element dynamically via javascript's DOM elements, style property.
```
document.getElementById("speed").style.transform = "rotate(" + speed + "deg)";
```
In your case:
```
var spinner = document.getElementById("spinner");
var speed = 0;
var addSpeed = 10;
var slowSpeed = 2;
//Activates Slowdown
window.onload = loop();
//Speed up
function spin() {
if (speed < 0) {
speed = speed + 10;
loop()
} else {
speed = speed + 10;
}
}
spinner.addEventListener('click', spin);
//Slowdown
function loop() {
setTimeout(
function slow() {
speed = speed - slowSpeed;
document.getElementById("speed").innerHTML = speed;
if (speed > 0) {
loop();
}
document.getElementById("speed").style.transform = "rotate(" + speed + "deg)";
}, 1000)
}
//Selectors
function wheel() {
spinner.src = "http://pngimg.com/uploads/car_wheel/car_wheel_PNG23305.png";
}
function spiral() {
spinner.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/Black_bold_spiral.svg/2000px-Black_bold_spiral.svg.png";
}
```
**EDIT:**
As per [username_2's answer](https://stackoverflow.com/questions/49402471/how-to-use-javascript-variables-in-css/49402686#49402736) , we can use variables in CSS.
Advantages:
1. It works in modern browsers.
Disadavantage:
1. It does not work in old browsers like:
1. IE
2. EDGE <= 15
3. Chrome < 49, etc..
...
...
**EDIT:2, Update the code, as per the comment**
```js
var spinnerImg = undefined;
var speedTxt = undefined;
var wheelImgUrl = "http://pngimg.com/uploads/car_wheel/car_wheel_PNG23305.png";
var spiralImgUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/Black_bold_spiral.svg/2000px-Black_bold_spiral.svg.png";
var speed = 0;
var maxSpeedChange = 10;
var slowSpeed = 2;
var speedParam = slowSpeed;
/**
* Function to change the image to wheel
*
* @Arguments: none
*
* @Returns: void
*/
function changeToWheel() {
spinnerImg.src = wheelImgUrl;
}
/**
* Function to change the image to spiral
*
* @Arguments: none
*
* @Returns: void
*/
function changeToSpiral() {
spinnerImg.src = spiralImgUrl;
}
/**
* Function to update speed display
*
* @Arguments: void
*
* @Returns: void
*/
function updateSpeedTxt() {
speedTxt.innerHTML = speed;
}
/**
* @Function to rotate the image
*
* @Arguments: void
*
* @Returns: void
*/
function rotateImg() {
spinnerImg.style.transform = "rotate(" + speed + "deg)";
}
window.addEventListener("load", function() {
spinnerImg = document.getElementById("spinner");
speedTxt = document.getElementById("speed");
speed = speedParam;
setInterval(function() {
updateSpeedTxt();
rotateImg();
if (speedParam > slowSpeed) {
speedParam -= 0.05;
}
if (speedParam < slowSpeed) {
speedParam = slowSpeed;
}
speed += speedParam;
}, 50);
spinnerImg.addEventListener("click", function() {
speedParam += maxSpeedChange;
});
});
```
```css
#spinner {
width: 500px;
transform-origin: center;
}
```
```html

#### N/A
Wheel
Spiral
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: You can declare variables in css (See the specifications--> <https://www.w3.org/TR/css-variables/>)
```
:root {
--deg: 10deg;
}
```
and then you can use it
```
#spinner {
transform: rotate( var(--deg));
}
```
How to access variables with JavaScript
**get**
```
var root = document.querySelector(':root');
var rootStyles = getComputedStyle(root);
var deg= rootStyles.getPropertyValue('--deg');
console.log(deg);
--> 10deg
```
**set**
```
root.style.setProperty('--deg', '20deg');
```
Currently, 88 percent of global website traffic [supports CSS Variables](https://caniuse.com/#search=CSS%20Variables)
Upvotes: 5 <issue_comment>username_3: Answer is no. you can not use a javascript variable inside css. But you can apply css style using javascript. here is the solution for your question
```js
var spinner = document.getElementById("spinner");
var speed = 0;
var addSpeed = 10;
var slowSpeed = 2;
//Activates Slowdown
window.onload = loop();
//Speed up
function spin() {
if (speed < 0) {
speed = speed + 10;
loop()
} else {
speed = speed + 10;
}
document.getElementById("spinner").style.transform = "rotate(" + speed + "deg)";
}
spinner.addEventListener('click', spin);
//Slowdown
function loop() {
setTimeout(
function slow() {
speed = speed - slowSpeed;
document.getElementById("speed").innerHTML = speed;
if (speed > 0) {
loop();
}
}, 1000)
}
//Selectors
function wheel() {
spinner.src = "http://pngimg.com/uploads/car_wheel/car_wheel_PNG23305.png";
}
function spiral() {
spinner.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/Black_bold_spiral.svg/2000px-Black_bold_spiral.svg.png";
}
```
```css
#spinner {
width: 500px;
}
#spinner {
transform: rotate(90deg);
}
/* The "speed" is the variable I want to use from the JavaScript */
```
```html

#### N/A
Wheel
Spiral
```
Upvotes: 1 <issue_comment>username_4: If you want to reduce boilerplate you could use sass mixin to generate all speed level classes for you;
```js
var box = document.getElementById('box');
var speed = 0;
var countdown;
box.addEventListener('click', function(e) {
if(speed === 3) return;
speed++;
box.className = "box-"+speed;
clearInterval(countdown);
})
box.addEventListener('mouseout', function(e) {
countdown = setInterval(function(){
if(speed === 0) {
clearInterval(countdown);
} else {
speed --;
box.className = "box-"+speed;
}
}, 2000);
})
```
```css
#box {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top: 250px;
left: 250px;
}
#box:hover{
cursor: pointer;
}
.box-1 {
-webkit-animation: rotation 3s infinite linear;
}
.box-2 {
-webkit-animation: rotation 2s infinite linear;
}
.box-3 {
-webkit-animation: rotation 1s infinite linear;
}
@-webkit-keyframes rotation {
from {
-webkit-transform: rotate(0deg);
}
to {
-webkit-transform: rotate(359deg);
}
}
```
```html
spin box animation
```
Upvotes: 0 |
Subsets and Splits