text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
About the intertwiners of a real representation and its complex conjugate
i am currently trying to understand a proof in Trautman's "The Spinorial Chessboard", namely theorem 4.2 on page 48. It states the following:
If $\rho:\mathcal{A}\to\operatorname{End}_\mathbb{C} S$ is a complex, faithful and irreducible representation of a finite-dimensional, central simple algebra over $\mathbb{R}$ over a finite-dimensional complex vector space $S$, then there is a $\mathbb{C}$-linear isomorphism $C:S\to\overline{S}$ intertwining $\rho$ and its complex conjugate $\overline{\rho}$. Moreover, $C$ can be chosen so that $\overline{C}C=\pm\operatorname{id}_S$.
The proof is quite straightforward: The complexified algebra $\mathcal{A}_\mathbb{C}$ is also simple and the complexifications $\rho_\mathbb{C}$,$\overline{\rho}_\mathbb{C}$ are also irreducible. Therefore $\rho_\mathbb{C}$ and $\overline{\rho}_\mathbb{C}$ are equivalent via a $\mathbb{C}$-linear isomorphism $C:S\to\overline{S}$ and since $\mathcal{A}\subset\mathcal{A}_\mathbb{C}$, it is clear that $C$ also intertwines $\rho$ and $\overline{\rho}$. Moreover, $\overline{C}C$ is in the commutator of $\rho_\mathbb{C}$ (observe the canonical isomorphism $S\cong\bar{\bar{S}}$), which is equal to $\mathbb{C}\cdot\operatorname{id}_S$, by Schur's Lemma.
But now he assumes $\overline{C}C=\lambda\cdot\operatorname{id}_S$ for $\lambda\in\mathbb{R}$ (!), and i have no idea why this should be true. I suspect one should exploit the property of $\mathcal{A}$,$\mathcal{A}_\mathbb{C}$ being central, since this is not used anywhere else in the proof.
I would be grateful if anyone would have some hint for me.
kind regards,
Robert Rauch
A:
Ok, I have found a solution: writing $\overline{C}C=\lambda\cdot\operatorname{id}_S$, we conclude $C\overline{C}=\overline{\lambda}\cdot\operatorname{id}_{\overline{S}}$. Multiplying this equation with $C$ from the right then gives $C\overline{C}C=\overline{\lambda}C$, but $C(\overline{C}C)=\lambda C$. Since $C\ne 0$ (we should require $S\ne 0$ for this, which is equivalent to $\mathcal{A}\ne 0$ in our setting), it follows $\lambda=\overline{\lambda}$.
Robert
| {
"pile_set_name": "StackExchange"
} |
Q:
Laravel lumen illuminate/console won't update
I am trying to install Laravel Dusk on my lumen project but I keep getting the following error:
Problem 1
- Installation request for illuminate/queue (installed at v5.4.36) -> satisfiable by illuminate/queue[v5.4.36].
- Can only install one of: illuminate/console[5.8.x-dev, 5.4.x-dev].
- Can only install one of: illuminate/console[5.9.x-dev, 5.4.x-dev].
- Can only install one of: illuminate/console[v5.8.0, 5.4.x-dev].
- Can only install one of: illuminate/console[v5.8.11, 5.4.x-dev].
- Can only install one of: illuminate/console[v5.8.12, 5.4.x-dev].
- Can only install one of: illuminate/console[v5.8.14, 5.4.x-dev].
- Can only install one of: illuminate/console[v5.8.15, 5.4.x-dev].
- Can only install one of: illuminate/console[v5.8.17, 5.4.x-dev].
- Can only install one of: illuminate/console[v5.8.18, 5.4.x-dev].
- Can only install one of: illuminate/console[v5.8.19, 5.4.x-dev].
- Can only install one of: illuminate/console[v5.8.2, 5.4.x-dev].
- Can only install one of: illuminate/console[v5.8.3, 5.4.x-dev].
- Can only install one of: illuminate/console[v5.8.4, 5.4.x-dev].
- Can only install one of: illuminate/console[v5.8.8, 5.4.x-dev].
- Can only install one of: illuminate/console[v5.8.9, 5.4.x-dev].
- Conclusion: install illuminate/console 5.4.x-dev
- Installation request for illuminate/console ^5.8 -> satisfiable by illuminate/console[5.8.x-dev, 5.9.x-dev, v5.8.0, v5.8.11, v5.8.12, v5.8.14, v5.8.15, v5.8.17, v5.8.18, v5.8.19, v5.8.2, v5.8.3, v5.8.4, v5.8.8, v5.8.9].
I have tried:
composer require illuminate/console
composer dump-autoload
composer update
composer install
With no luck. In my composer.json there is no illuminate/console so I can't update it in there.
"require": {
"php": ">=5.6.4",
"laravel/lumen-framework": "5.4.*",
"vlucas/phpdotenv": "~2.2",
"krisanalfa/lumen-dingo-adapter": "^0.0.3",
"sorskod/larasponse": "*",
"league/flysystem": " ~1.0",
"league/flysystem-aws-s3-v3": "^1.0",
"maatwebsite/excel": "^2.1",
"barryvdh/laravel-dompdf": "^0.8.0",
"illuminate/mail": "5.4"
},
"require-dev": {
"fzaninotto/faker": "~1.4",
"phpunit/phpunit": "~5.0",
"mockery/mockery": "~0.9",
"flipbox/lumen-generator": "^5.4"
},
However when I look in the composer.lock that gets created I can see it here:
"name": "illuminate/console",
"version": "v5.4.36",
"source": {
"type": "git",
"url": "https://github.com/illuminate/console.git",
"reference": "4f0413ffd240d2004c3e9e4cd8f63df249939a15"
},
Any way I can get this pack age to update? I believe dusk requires 5.7.* at minimum.
A:
I was not able to replicate your issue with the illuminate/console package, but I did manage to install the specified packages in a test project on my local machine.
Make sure you have the following in your composer.json file:
{
"minimum-stability": "dev",
"prefer-stable": true
}
Delete your vendor folder:
cd ~/path/to/project
rm -rf vendor/
Then run composer update to ignore and generate a new lock file.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use Dapper.QueryMultiple with Sqlite
The Dapper documentation states you can send off multiple queries at once and iterate over the results using the QueryMultiple method like so:
var sql = @"
select * from foo where id = @paramname
select * from bar where id = @paramname";
conn.QueryMultiple(sql, new {paramname = paramval});
It would appear using sqlite like this doesn't work, throwing up invalid sql near "select". How do I use querymultiple with sqlite?
A:
After some playing, I noted that you appear to need to use a semicolon between the commands
so the above code corrected becomes:
var sql = @"
select * from foo where id = @paramname;
select * from bar where id = @paramname";
conn.QueryMultiple(sql, new {paramname = paramval});
No, don't use the code like this, use the return of a QueryMultiple as a using statement, so it can be automatically disposed of.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create static/dyanmic libraries in c++ using makefile ?
I have a situation in which I have three very large files A.cpp B.cpp C.cpp n.cpp
I don't want to compile these files, every time when i run the program,
any ideas what is the best possible way to exclude these files from compiling.
A:
Every time you run your program the program will not get compiled.
Compilation is one time process and linking is one time if you link statically on the time to compilation. The other one is linking at run time (dynamic linking).
In either case code will be compiled once that too if the source file is not changed then the compilation happens if you use the make file.
make clean; #if you execute this command before make all or make build, then all the .cpp files will be compiled
here clean, all, build are the target of the make file.
Refer the link for make
| {
"pile_set_name": "StackExchange"
} |
Q:
What is an example of Infrastructure as a Code(IaC)?
I ran into the word "IaaC" (or IaC) many times. When I googled it, it told me :
Infrastructure as code(IaC) is the process of managing and provisioning computer data centers through machine-readable definition files, rather than physical hardware configuration or interactive configuration tools.
Can yaml files used in Kubernetes be an example of IaC? Maybe even Dockerfile can be considered as such? If not, could you give me some examples of IaC?
For example :
apiVersion: v1
kind: Service
metadata:
name: my-nginx-svc
labels:
app: nginx
spec:
type: LoadBalancer
ports:
- port: 80
selector:
app: nginx
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-nginx
labels:
app: nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.7.9
ports:
- containerPort: 80
A:
There are a number of steps which a IP Ops need to do to release/update the application running on the internet. Few examples of the tasks are
Provisioning new virtual machines, like starting the VM with the required memory and specs.
Installing the required software and dependency
Managing and scaling the infrastructure.
Repeating all of the configurations we've made again and again.
Infrastructure as a code means automating the steps required to deploy our application on the internet. Since using docker and k8s we are automating the deployment process, it is also considered infrastructure as a code.
Example
# define services (containers) that should be running
services:
mongo-database:
image: mongo:3.2
# what volumes to attach to this container
volumes:
- mongo-data:/data/db
# what networks to attach this container
networks:
- raddit-network
raddit-app:
# path to Dockerfile to build an image and start a container
build: .
environment:
- DATABASE_HOST=mongo-database
ports:
- 9292:9292
networks:
- raddit-network
# start raddit-app only after mongod-database service was started
depends_on:
- mongo-database
# define volumes to be created
volumes:
mongo-data:
# define networks to be created
networks:
raddit-network:
This docker compose file installs the dependency mongo-database by itself also it installs the main application raddit-app, and specifies the port the application listens for.
Source: https://github.com/Artemmkin/infrastructure-as-code-tutorial
| {
"pile_set_name": "StackExchange"
} |
Q:
Custom Content Query Web Part in a Sandbox Solution
I am looking to create an "image slider" web part for my SharePoint 2010 site home page to display a nice glossy roll-up of our recent news articles. There are literally hundreds of jQuery plugins that will take any list of images display them in a very cool slider / rotator / accordian / carrousel for you -- so all I need to do is build a SharePoint web part which can be configured to point to a particular picture or assets library, load the media files from it, and then tell the jQuery plugin do it's thang.
Given that I am working in a sandboxed solution, what is my best approach for creating this web part?
My first instinct was to create a custom web part which inherits from
the
Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart class, as this would allow me to use the in-built methods of the CQWP
to select all items of a particular content
type and then present them in the jQuery plugin's expected format
using some XSLT. Easy! The only problem howver, is that the
ContentByQueryWebPart isn't available in the sandbox, and nor are the DataFormWebPart or XsltListViewWebPart classes.
I know I can create a completely custom web part, but it seems like that should be a last resort. What can I leverage out-of-the-box programmatically to make this all a little easier?
FYI: For those that are interested, this is the jQuery plugin that I am using: http://www.evoslider.com/examples.html
A:
For those playing at home, I never found a way to inherit and implement the CQWP in the sandbox. Instead, I created a custom base class which provides some basic and common functionality which is used across all our "get data from list and display it" web parts (for example, this base class is used for a custom Image Slider web part, a Media Gallery web part, an Events Calendar web part, a Corporate Announcements web part etc.)
Similar to the CQWP, my base class takes care of adding a "Datasource Settings" panel to the web part's settings pane. This allows the user to select that list / library that the web part shall retrieve its data from. Internally, it uses the SPQuery object to retrieve data from the source list and pass it back to the derived web part for processing. Plus it also takes care of all the list validation, and also deiplaying messages such as "No items to display" when the list is empty etc.
| {
"pile_set_name": "StackExchange"
} |
Q:
Reading/writing a resultcode in Android
In have a problem either with reading the resultcode of an Activity or writing the resultcode in the SharedPreferences.
The app is a quiz which should show the player's highscore.
Frist my Start Menu Activity:
@Override
protected void onCreate( Bundle savedInstanceState ) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start_menu);
init();
}
private void init() {
// init Ui Elements
Button startTimeQuizBT = (Button) findViewById(R.id.StartTimeQuiz);
// init onClickListeners for Buttons
startTimeQuizBT.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick( View v ) {
Intent intent = new Intent(getApplicationContext(), QuizTimeActivity.class);
startActivityForResult(intent, 1);
}
});
}
@Override
protected void onResume() {
super.onResume();
TextView ScoreTV = (TextView) findViewById(R.id.highscoreTV);
ScoreTV.setText("Aktueller Highscore : " + Integer.toString(readHighscore()));
}
private int readHighscore() {
SharedPreferences pref = getSharedPreferences("GAME", 0);
return pref.getInt("HIGHSCORE", 0);
}
@Override
protected void onActivityResult( int requestCode, int resultCode, Intent data ) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode ==1) {
if (resultCode > readHighscore()) {
writeHighscore(resultCode);
}
}
}
private void writeHighscore( int highscore ) {
SharedPreferences pref = getSharedPreferences("GAME", 0);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("HIGHSCORE", highscore);
editor.apply();
}
}
This Activity is basically the main menu and should start QuizTimeActivity for Result and showing the player's current highscore.
Secondly the QuizTimeActivity:
QuestionLib qLib = new QuestionLib();
String TAG = "QuizTimeActivity";
private Button choice1;
private Button choice2;
private Button choice3;
private Button choice4;
private TextView questionTV;
private TextView scoreTV;
private int score = 0;
private int randomNumber = 0;
private String correctAnswer;
private TextView countdownTV;
@Override
protected void onCreate( Bundle savedInstanceState ) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_time);
countdownTV = (TextView) findViewById(R.id.countdown);
CountDownTimer timer = new CountDownTimer(90 * 1000, 100) {
@Override
public void onTick( long millisUntilFinished ) {
countdownTV.setText(String.valueOf(millisUntilFinished / 1000));
}
@Override
public void onFinish() {
setResult(score);
Log.i(TAG, "current score : " + score);
startActivity(new Intent(getApplicationContext(), StartMenuActivity.class));
finish();
}
}.start();
choice1 = (Button) findViewById(R.id.choice1);
choice2 = (Button) findViewById(R.id.choice2);
choice3 = (Button) findViewById(R.id.choice3);
choice4 = (Button) findViewById(R.id.choice4);
questionTV = (TextView) findViewById(R.id.question);
scoreTV = (TextView) findViewById(R.id.scoreTV);
generateRandomNumber(0, 162);
updateQuestion();
choice1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick( View view ) {
if (choice1.getText() == correctAnswer) {
blinkEffectGreen(choice1);
score++;
}
else {
blinkEffectRed(choice1);
}
}
});
choice2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick( View view ) {
if (choice2.getText() == correctAnswer) {
blinkEffectGreen(choice2);
score++;
}
else {
blinkEffectGreen(choice2);
}
}
});
choice3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick( View view ) {
if (choice3.getText() == correctAnswer) {
blinkEffectGreen(choice3);
score++;
}
else {
blinkEffectRed(choice3);
}
}
});
choice4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick( View view ) {
if (choice4.getText() == correctAnswer) {
blinkEffectGreen(choice4);
score++;
}
else {
blinkEffectRed(choice4);
}
}
});
Somehow the highscore stays at zero when QuiztimeActivty ends after 90 seconds.
Am I doing something wrong here(I guess yes, otherwise it would bn working...)?
I hope these infos are enough, if not I will provide more.
Thank you!
A:
First you need to change the code in the onFinish() method:
@Override
public void onFinish() {
Intent intent = new Intent();
intent.putExtra("MY_SCORE", score);
setResult(RESULT_OK, intent);
finish();
}
Then you need to change the code in the onActivityResult() method:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK){
int score = data.getIntExtra("MY_SCORE", -1);
if (score > readHighscore()) {
writeHighscore(resultCode);
}
}
}
}
You should not use startActivity() in your onFinish() method because that will start a new instance of the Activity. Just let the Activity finish and the focus will return to the Activity that started it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Setting the orientation for only 1 fragment in my activity while the rest is in portrait
My app needs to be in portrait mode so I set it in the manifest by:
android:screenOrientation="portrait"
But I just recently added another fragment (FragA) that just looks and functions 10x better in landscape. Is there something I can put inside of my FragA to just make that fragment in landscape while retaining the rest of the app in portrait or by doing this will I have to add something to my other fragments to keep them retained as portrait?
A:
Use the following code line in the fragment where you want a specific (in this case portrait) orientation.
getActivity().setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
If you want to have a orientation in a fragment, that is based on the way the user holds his device, then use the following code line.
getActivity().setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
Hope, this will give you the intended solution.
A:
In each of your fragments, set the requested orientation.
Reference doc: http://developer.android.com/reference/android/content/pm/ActivityInfo.html
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Fragment locked in portrait screen orientation
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Fragment locked in landscape screen orientation
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
// Fragment screen orientation normal both portait and landscape
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
A:
Orientation attribute is per activity so you can declare the orientation for only the activity that contains the fragment so that it is in landscape and the rest of the activities will remain as they are.
| {
"pile_set_name": "StackExchange"
} |
Q:
std::is_floating_point returns false for float in some cases
In some cases, see one example below, std::is_floating_point is returning false for float.
#include <iostream>
#include <type_traits>
#include <vector>
int main()
{
::std::cout << typeid(decltype(::std::vector< float >()[::std::vector< float >().size()])).name() << ::std::endl;
if (::std::is_floating_point< decltype(::std::vector< float >()[::std::vector< float >().size()]) >::value)
{
::std::cout << "floating point" << ::std::endl;
}
else
{
::std::cout << "not floating point" << ::std::endl;
}
return 0;
}
Output from GCC
f
not floating point
In this example, one can see that typeid considers ::std::vector< float >()[::std::vector< float >().size()] as a float as it returns the correct name. One can also check that typeid(decltype(::std::vector< float >()[::std::vector< float >().size()])) == typeid(flat) returns true. However, std::is_floating_point is returning false. Why? Is that a bug from C++?
FYI, I checked with both GCC and VisualStudio. In this example, I used std::vector, but one can also try with other libraries, such as Eigen.
A:
There is no bug, and std::is_floating_point is giving you the right answer.
vector<float>[n] doesn't give you a float; it gives you a float&.
typeid ignores this for convenience but, as more "powerful" tools, decltype and std::is_floating_point do not.
You can use std::remove_reference to fix this:
if (::std::is_floating_point_v<std::remove_reference_t<
decltype(::std::vector< float >()[::std::vector< float >().size()])
>>)
You might also consider std::decay.
You don't need decltype anyway as containers have handy type aliases for times like this.
Here's what I'd do:
#include <iostream>
#include <type_traits>
#include <vector>
int main()
{
using V = std::vector<float>;
::std::cout << typeid(V::value_type).name() << '\n';
if (::std::is_floating_point_v<V::value_type>)
::std::cout << "floating point\n";
else
::std::cout << "not floating point\n";
}
// Output:
// f
// floating point
Live demo
| {
"pile_set_name": "StackExchange"
} |
Q:
How to change number of decimal places displayed in output of multilevel model
I am displaying a multilevel model and would like to show three decimal places when output to screen.
M3 <- lmer(stflife ~ sclmeet + health + wkdcorga + hincfel + fltlnl
+ rshpsts + dosprt + c_corruption_2014 + c_ticpi_2014 +
(1 | cntry), data = countries)
display(M3)
A:
Assuming this is the display function from the arm package, display(M3, digits=3) will display results to three decimal places. The digits argument is documented in the help for display, which can be accessed by running ?display.
| {
"pile_set_name": "StackExchange"
} |
Q:
.htaccess to redirect specific index file when url is visited
My product url looks like this: http://www.example.com/products/handbags/leather-handbag-model-ba123
where handbags is the category name and it is changing dynamically.
leather-handbag-model-ba123 is a product unique url and is also changing dynamically.
In the .htaccess file I have this:
RewriteCond %{THE_REQUEST} /(products)/([^\s&]+)/([^\s&]+) [NC]
RewriteRule /%1/%2/index.php [L]
which is supposed to load index.php file which is located in /products/handbags/index.php, but the code returns error 404.
What will be the correct code that will load index.php file of the specific category (handbags in the example)?
A:
Use:
RewriteCond %{REQUEST_URI} !index\.php$ [NC]
RewriteRule ^(products)/([^/]+)/.+/? /$1/$2/index.php [L]
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get notified as soon as new data gets inserted in azure table storage
I have an Azure Table Storage where data is expected to be inserted from a web service.
My App (ASP.Net MVC , VS 2017) has SignalR implemented to receive any changed data from Azure Table Storage.
My Problem
After a new data arrives in Table Storage, only if I refresh a browser, the latest data automatically gets reflected in any other opened browsers - either in same or different computer systems.It doesn't automatically display the changed value in any opened browser as soon new data gets into Table Storage.
I guess this may be because when I refresh the browser, as per my code it gets the data from Table and SignalR fires to send the data to other clients.
So there is a gap here in sending notification from the Table whenever new data arrives.
My Query
What is that I am missing here - it doesn't show the latest data on the browser automatically?
Or is it that Table Storage do not have any notification mechanism to notify new-data-arrived?
If so what should be done receive notification whenever a new data arrives into Azure Table Storage?
My Action Method
[HttpGet]
public ActionResult Index()
{
var model = SignalRepository.LatestSignalCollection();// Connects with Azure to fetch the latest 5 records
return View(model);
}
My SignalR Hub Code
public SignalHub()
{
SignalRepository.SignalSubscriber();
var signalData = SignalRepository.LatestSignalCollection(); //LatestSignalCollection() ===> Connects with Azure to fetch the latest 5 records
GetAllClients().All.SendSignalData(signalData);
}
My js file - SignalR Connect code
var signalHub = $.connection.signalHub; //alert("ACCC");
$.connection.hub.logging = true;
// Start the hub
$.connection.hub.start();
signalHub.client.SendSignalData = function (signalData) {
updateSignalData(signalData);// updates the elements in Index.cshtml
}
A:
It seems that you’d like to push notification to all connected clients when new data that inserted from a web service arrives into your Azure Table storage. I suggest that you could invoke your hub method to broadcast new data to all connected clients after you execute the code to insert the data into Azure Table storage.
var hub = new HubConnection("http://xxx/signalr/hubs");
var proxy = hub.CreateHubProxy("{HubName}");
hub.Start().Wait();
//invoke hub method
proxy.Invoke("{HubMethod}", "{partitionkey&rowkey}");
In your hub method, you will get the partition key and row key of the latest data, and then you can retrieve the entity based on partition key and row key, and call JavaScript side function SendSignalData to update web page elements.
| {
"pile_set_name": "StackExchange"
} |
Q:
Algebra solve for x
I tried to solve for x in the equation $x^3=x$. I did
$$x^3=x$$
$$x^2=1$$
$$x=\pm1$$
but it's wrong, can anyone help.
A:
You forgot 0. You shouldn't divide by x, or else you will miss it. You can solve it like this:
$$x^3=x$$ subtract x from both sides$$x^3-x=0$$ factor out x$$x(x^2-1)=0$$factor $x^2-1$ $$x(x+1)(x-1)=0$$ Simplify $$x=-1,0,1$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Why some URL's of websites doesn't show the .php extention just shows words like stackoverflow.com/questions/ask
Hello guys I was wondering why some websites which uses php (or any other server side scripting language) doesn't show the extention and even the file.
like this url stackoverflow.com/questions/ask
and also some websites gets data from users, let's say a website that lets users post some random post, ok so when we click on that post it sends us to :
domain.com/post/what-user-posted-goes-here
and if we try to go to domain.com/post/ we get an error of page not found.
I'm asking this question because because I want to know what is the method used and is it related to php ? and because I want to use it.
A:
What you are talking about is the search engine optimization (SEO) of URLs.
See How to Make your URLs SEO Friendly and SEO friendly URL in PHP for more details as this subject is very well documented already here on SO and on the Web in general.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to know whether am the administrator of my Ubuntu?
Is there a way to know whether am the administrator of my Ubuntu 14.04 ? If not, how can I became the administrator ?
A:
Simply type id in a terminal. It outputs user id, group id, and group memberships of your account. In my case:
UID=1000(jacob) GID=1000(jacob) groepen=1000(jacob),4(adm),24(cdrom),27(sudo),30
"27(sudo)" means I am member of the group "sudo", and that I have the option to run commands with sudo, in other words: I am an administrator.
In comparison, a "normal" user's output:
UID=1001(testpersoon) GID=1001(testpersoon) groepen=1001(testpersoon),1000(jacob)
To turn a "normal" user into an administrator, add the user to the group sudo:
sudo adduser <username> sudo (from an administrator's user account)
A:
In the default GUI, open the System Settings and go to the “User Accounts” tool. This shows your “Account Type”: “Standard” or “Administrator”.
On the command line, run the command id or groups and see whether you are in the sudo group. On Ubuntu, normally, administrators are in the sudo group.
You may have administrative access if you've been directly added to the list of sudoers — this is more likely if the administrator is familiar with Linux or Unix in general and didn't use the default Ubuntu method. Try running sudo echo ok and enter your password; if this prints ok, you're an administrator.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to anticipate and avoid "code too large"?
I am writing SQL grammar using Antlr 3.5 (which I cannot share due to company policy).
I am providing only for the statements which I need to parse but the grammar is huge and complex.
I ran into "code too large" issue where the generated java file was exceeding 65535 bytes- sometimes in static initializer, other times in some method.
As suggested at various places, I split the grammar into multiple grammars and used them via import keyword.
This approach is working fine for now but I have to keep adding to this grammar
and I believe at some point it will again run into this code too large problem.
Also, I do not know exactly how much gain I have by splitting the grammar.
My questions are:
How do we know we are nearing code too large problem again?
Is there a way by which we can measure exactly how much improvement/gain
we are getting by splitting the grammars.
The generated files are still huge - SqlParserParser.java is 1.77MB and
SqlParser_SqlSubParser.java is 1.36MB.
Is the file size an indication of this problem?
Is there anything else that can also be done besides grammar splitting.
Few points:
I cannot switch to Antlr4 as of now.
Please try not to down vote my question for the lack of example as I cannot post the real grammar and a small example would not recreate my problem.
A:
As far as I remember, the problem isn't the class size itself, but rather method size. For us, the problem was the static initializer (to compiler, it's a method too!) - it initializes all the follow sets and DFAs.
We ended up splitting our SQL grammars into multiple grammar files (got even to 6 files for some SQL dialects), and also directly modifying parts of ANTLR (Java.stg template) to split the large methods and static initializers into smaller ones.
| {
"pile_set_name": "StackExchange"
} |
Q:
What does "mostly" modify?
"My friends are mostly non-smokers."
Is "mostly" a focusing adverb that modifies "non-smokers"?
A:
Mostly is an adverb modifying the verb are, and means ‘on the whole’. Its grammatical function is no different from a number of other adverbs you might put in its place, such as predominantly, mainly, largely, principally or primarily.
| {
"pile_set_name": "StackExchange"
} |
Q:
What level are fread thread locks on? What level do they need to be on?
Visual Studio's fread "locks out other threads." There is an alternate version _fread_nolock, which reads "without locking other threads", which should only be used "in thread-safe contexts such as single-threaded applications or where the calling scope already handles thread isolation."
Even after reading other somewhat relevant discussions on the two, I'm confused if the locking fread implements is on a specific FILE struct, a specific actual file, or on all fread calls on totally different files.
If you use the nolock versions, what level of locking do you need to provide? Can multiple threads in parallel be reading separate files without any locking? Can multiple threads in parallel be writing separate files without any locking? Or are there global or static variables involved that would be corrupted?
So, by using the nolock versions, are you able to potentially achieve better I/O throughput (if you aren't needlessly moving heads, like reading off separate drives, or a SSD drive), or is the potential gain just reducing redundant locks to a single lock (which should be negligible.)
Does VS' ifstream.read function work just like the regular fread? (I don't see a nolock version of it.)
A:
The MS standard library implementation fully supports multi-threading. The C++ standard explain this requirement:
27.2.3: Concurrent access to a stream object, stream buffer object, or C Library stream by multiple threads may result in a data
race unless otherwise specified.
If one thread makes a library call a that writes a value to a stream
and, as a result, another thread reads this value from the stream
through a library call b such that this does not result in a data
race, then a’s write synchronizes with b’s read.
This means that if you write on a stream, a locking (not file locking, but concurrent access locking to the in-memory stream data structure) is done, to be sure that concurrency is well manageged for all the other threads using the same stream.
This locking overhead is always there, even if not needed. This could have a performance aspect, according to Microsoft:
the performance of the multithreaded libraries has been improved and
is close to the performance of the now-eliminated single-threaded
libraries. For those situations when even higher performance is
required, there are several new features.
This is why _nolock functions are provided. They access the stream directly without thread locking. It must be used with extreme care, for example:
if your application is single threaded (another process using the same stream has its own data structure, and OS manageds concurrency here)
if you're sure that no two threads use the same stream (for example if you have only one reader thread and writing is done outside your porgramme).
if you have other synchronisation mechasnism that protect a critical section of your code. For example, if you use a mutex lock, or an thread safe non blocking algorithm that makes use of atomics.
In such cases, the additional lock for stream access is not needed/redundant. For file intensive functions, it could be worth using the no_lock then.
Note: as you've pointed out: it's only worth using the nolock for intensive file accesses where you make millions of accesses.
| {
"pile_set_name": "StackExchange"
} |
Q:
Poker etiquette on split pots
Is it considered bad etiquette to raise on a fairly obvious split-pot?
e.g. straight/royal flush on the board, or quads on the board when its fairly expected that both players have an Ace.
I get quite annoyed with it currently (online play-money), as the rake is %-based. I know its not against any rules i know of.
A:
No, it's not bad etiquette to want to try win a pot. You'd be surprised how many players don't realise an obvious split-pot.
A:
When the nuts is actually on board, like T♠J♥Q&diamondK♣A♠, I would say it's probably bad etiquette to continue raising in a cash game where the rake will be affected accordingly (although I have in the past seen people fold on the river in situations like this, albeit infrequently, but it happened!).
In a tournament (where rake is not a consideration), it's only likely to be a small handful of raises until you're all-in anyway, so unless someone is taking an age to make each raise, I don't see that there's any significant detriment or inconvenience caused, so I wouldn't consider this bad etiquette either.
While most games are governed by rules which include one to penalise players for not raising on the river with the nuts (to prevent soft-playing), I've never seen this enforced when the nuts is on board and would expect Rule #1 to take effect (i.e. common sense or an unusual situation can permit a floor to make a decision contrary to the rest of the rules).
However, when it is possible that it's not a split pot, I think anyone is well within their rights to raise as many times as they would like. If you have Ax on a 22223 board, why should you give up potential value against someone playing Kx who might be willing to get all-in?
All that said, what is and isn't good etiquette is basically a matter of (mass) opinion, so one person's view is not necessarily particularly relevant - it matters what "most" poker players think. If enough players started changing their mind and felt that some particular behaviour was unacceptable, it would become bad etiquette where it might not have been previously.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cannot make an object uncopyable
I'm making a server interface for network programming and I ran into a problem. I want to make a server object uncopyable, mostly because it doesn't really make sense to do so and would probably make problems, and also because it uses threads which can't be copied. However, when I make the copy constructor and assignment operator private, I get an error:
Error 2 error C2248: '(namespaces..)::Server::Server' : cannot access private member declared in class '(namespaces..)::Server' (path..)\type_traits 1545 1 Server
The error seems to be in the type_traits file? I haven't used it at all, though it might be possible that some of the other std files I'm including use it? I'm using iostream, sstream, string, thread, map.
Here's the server class definition:
class DLL_PUBLIC Server
{
public:
Server(unsigned int);
~Server();
(...)
private:
class PvtImpl; //Private implementation, so it isn't seen in the header file
PvtImpl *pvtImpl;
Server(const Server &par_other){}
Server& operator=(const Server &par_other){ return *this; }
(...)
};
and the private implementation:
class Server::PvtImpl
{
public:
bool running;
unsigned int port, backlog, currentlyConnected;
SOCKET listenSocket;
std::thread *acceptConnectionsThread;
std::thread* *receiveDataThreads; //I am using pointers instead of vectors because I want it to be fixed
ClientObj* *clients;
std::map<ClientObj*, unsigned int> clientIndexMap;
};
Since I don't know what code to post because I don't even know where the error is coming from, then tell me if you need a specific part of it posted. If I comment out the private copy constructor and assignment operator then it works, but I don't want this to be copyable and especially not through default constructor. Doubt it, but does it have something to do with it being a DLL?
Anyway that's it, thanks for your time
Update
So I added a = delete to the constructor as suggested, and also made it public:
class DLL_PUBLIC Server
{
public:
Server(unsigned int);
Server(const Server &par_other) = delete;
~Server();
Server& operator=(const Server &par_other) = delete;
(...)
};
I am getting a bit of a different error now, but also in the type_traits file:
Error 2 error C2280: '(namespaces..)::Server::Server(const (namespaces..)::Server &)' : attempting to reference a deleted function (path..)\type_traits 1545 1 Server
A bit of code it is complaining about in that file:
// TEMPLATE FUNCTION _Decay_copy
template<class _Ty> inline
typename decay<_Ty>::type _Decay_copy(_Ty&& _Arg)
{ // forward _Arg as value of decayed type
return (_STD forward<_Ty>(_Arg));
}
_STD_END
Update 2
So this is the output window from VS as requested:
1>(path...)\type_traits(1545): error C2280: '(namespaces..)::Server::Server(const (namespaces..)::Server &)' : attempting to reference a deleted function
1> (path..)\Server.h(19) : see declaration of '(namespaces..)::Server::Server'
1> (path..)\thread(47) : see reference to function template instantiation '(namespaces..)::Server std::_Decay_copy<(namespaces..)::Server&>(_Ty)' being compiled
1> with
1> [
1> _Ty=(namespaces..)::Server &
1> ]
1> Server.cpp(94) : see reference to function template instantiation 'std::thread::thread<void(__cdecl &)(const (namespaces..)::Server &),(namespaces..)::Server&>(_Fn,(namespaces..)::Server &)' being compiled
1> with
1> [
1> _Fn=void (__cdecl &)(const (namespaces..)::Server &)
1> ]
The line 19 in the Server.h it's mentioning is the copy constructor declaration. Line 94 in Server.cpp is thread creation:
pvtImpl->acceptConnectionsThread = new std::thread(acceptConnections, *this);
The acceptConnections function takes the server by constant reference so it shouldn't copy, here's the declaration:
friend void acceptConnections(const Server&);
A:
Your problem is most likely in the thread constructor:
pvtImpl->acceptConnectionsThread = new std::thread(acceptConnections, *this);
Try this instead:
pvtImpl->acceptConnectionsThread = new std::thread(acceptConnections, std::ref(*this));
because without the std::ref() wrapper, a copy of your server instance will be passed into the thread constructor, which in turn will pass that copy by reference to your acceptConnections() method. Or at least try to, but it never got that far, as the compiler failed the initial copy.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a way to close a particular instance of explorer with C#?
I'm looking for a way to close a Windows explorer window that's open to a certain folder. Say c:\users\bob\folder. I can close all explorers with the code below, but this is obviously not what I want to do. Is this possible?
foreach (Process p in Process.GetProcessesByName("explorer"))
{
p.Kill();
}
Thanks
A:
This article that got me most of the way there: http://omegacoder.com/?p=63
I found a way using a COM library called "Microsoft Internet Controls" that looks more intended for Internet Explorer, but I gave up trying to use the process ID's and MainWindowTitle stuff since explorer.exe only uses one process for all open windows and I couldn't pin down how to get the window title text or file system location from that.
So first, add a reference to Microsoft Internet Controls from the COM tab, then:
using SHDocVw;
This little routine did the trick for me:
ShellWindows _shellWindows = new SHDocVw.ShellWindows();
string processType;
foreach (InternetExplorer ie in _shellWindows)
{
//this parses the name of the process
processType = Path.GetFileNameWithoutExtension(ie.FullName).ToLower();
//this could also be used for IE windows with processType of "iexplore"
if (processType.Equals("explorer") && ie.LocationURL.Contains(@"C:/Users/Bob"))
{
ie.Quit();
}
}
One caveat, and probably owing to the fact this library is geared toward IE, is you have to use forward slashes in your folder path... That's because the true LocationURL that comes back from the ie object is in the form file:///C:/Users/...
| {
"pile_set_name": "StackExchange"
} |
Q:
Sidekiq worker is leaking memory
Using the sidekiq gem - I have sidekiq worker that runs a process (git-tf clone of big repository) using IO.popen and tracks the stdout to check the progress of the clone.
When I am running the worker, I see that sidekiq memory is getting larger over the time until I get kernel OOM and the process get killed. the subprocess (java process) is taking only 5% of the total memory.
How I can debug/check the memory leak I have in my code? and does the sidekiq memory is the total of my workers memory with the popen process?
And does anyone have any idea how to fix it?
EDIT
This is the code of my worker -
https://gist.github.com/yosy/5227250
EDIT 2
I ran the code without sidekiq, and I have no memory leaks.. this is something strange with sidekiq and big repositories in tfs
A:
I didn't find the cause for the memory leak in sidekiq, but I found a away to get a way from sidekiq.
I have modified git-tf to have server command that accepts command from redis queue, it removes lot of complexity from my code.
The modified version of git-tf is here:
https://github.com/yosy/gittf
I will add documentation later about the sever command when I will fix some bugs.
| {
"pile_set_name": "StackExchange"
} |
Q:
Include TikZ code in bookdown figure environment
I'd like to add a TikZ figure to a bookdown document in order to include some fancy graphics.
My primary output format is LaTeX which means that I could essentially just include the TikZ graphics verbatim in the Rmarkdown file and it would render fine. However, two problems are haunting me:
I'd like for the TikZ graphics to be part of a figure environment (for the numbering, caption etc).
I'd like to be able to render the same code to both PDF (LaTeX) and Gitbook (HTML).
Right now I have the following chunk which nicely produces the relevant graph as a figure when I render to pdf.
```{r, echo=FALSE, engine='tikz', out.width='90%', fig.ext='pdf', fig.cap='Some caption.'}
\begin{tikzpicture}[scale=.7]
\draw [fill=gray!30,very thick] (0,-1) rectangle (5,1);
\draw [very thick] (5, 0) -- (13,0);
\node [below] at (2,-1) {\large Hello};
\node [below, align=center] at (0,-1) {\large Two\\ lines};
\end{tikzpicture}
```
However, there are two problems with the code:
I do not get any output when rendering to gitbook (using knitr and bookdown). I do get the figure caption, however, and if I render to html_document then it works too and I can see the graph.
For PDF the text is rendered using the computer modern font. I'd really like to change this, and the main font in the LaTeX document has already been set to something else. However, because the code is rendered locally by the TikZ engine and then inserted, it is not part of the full LaTeX document. Can I add some LaTeX options, packages etc. that are included by the TikZ engine before the code is rendered?
If there are other ways to include the TikZ code as part of a figure environment then I'd be happy to know.
Update: I guess the second point could be fixed by setting engine.opts = list(template = "latex/tikz2pdf.tex") where the necessary setup for LaTeX is included in the tikz2pdf.tex file. That file is read using LaTeX but I'd like to use xelatex to parse the file since I'm using the fontspec LaTex package. Can that be changed anyway?
A:
I think I found an answer to both of my questions. It did take - as Yihui pointed out - quite some time. I'm including the answer here in case someone else turns out to need this (or myself at a later point).
Re 1) Render TikZ code to both pdf and gitbook
This turned out to be easier than I anticipated. Setting the argument fig.ext=if (knitr:::is_latex_output()) 'pdf' else 'png' as part of the chunk arguments helps this along. If I'm not knitting to PDF then imagemagick or some other software automatically converts it to PNG.
Re 2) Modifying the font
As listed in my updated question this can be set by tweaking the file tikz2pdf.tex that is part of knitr. A copy of it is included below so you don't have to search for it yourself. Setting the chunk argument engine.opts = list(template = "latex/tikz2pdf.tex") enables you to put any desired fonts, LaTeX packages etc in preamble before the TikZ code is rendered.
Looking through the knitr code, you can see that texi2dvi is used to parse the tikz2pdf.tex file with the TikZ code inserted. texi2dvi calls pdflatex which messes things up in case you need to use XeLaTeX or LuaLaTeX to include TrueType fonts using fontspec.
I'm sure it would be possible to fix that somehow in the texi2dvi code but a much simpler solution (at least for me) was to change the environment. If I set the two environmental variable before starting R and rendering the book then xelatex is automatically used for compiling all the code. In my bash terminal this is done using
export LATEX="xelatex"
export PDFLATEX="xelatex"
Voila!
The chunk becomes
```{r, echo=FALSE, engine='tikz', out.width='90%', fig.ext=if (knitr:::is_latex_output()) 'pdf' else 'png', fig.cap='Some caption.', engine.opts = list(template = "latex/tikz2pdf.tex")
}
\begin{tikzpicture}[scale=.7]
\draw [fill=gray!30,very thick] (0,-1) rectangle (5,1);
\draw [very thick] (5, 0) -- (13,0);
\node [below] at (2,-1) {\large Hello};
\node [below, align=center] at (0,-1) {\large Two\\ lines};
\end{tikzpicture}
```
and tikz2pdf.tex is
\documentclass{article}
\include{preview}
\usepackage[pdftex,active,tightpage]{preview}
\usepackage{amsmath}
\usepackage{tikz}
\usetikzlibrary{matrix}
%% INSERT YOUR OWN CODE HERE
\begin{document}
\begin{preview}
%% TIKZ_CODE %%
\end{preview}
\end{document}
I'm still surprised at the whole flexibility of knitr and related packages. Nice work Yihui!
| {
"pile_set_name": "StackExchange"
} |
Q:
Python: create multiple new columns based on patterns
I have a file like this:
#chr start end count colX colY
1 100 200 1
1 300 400 2 blabla_pattern_a,blabla_pattern_b,blabla_pattern_c
2 100 400 1 blabla_pattern_a
2 500 600 4 blabla_pattern_e,blabla_pattern_c blabla_pattern_d
I am looking for 5 different patterns (a-e) that could be present in colX and colY. ColX and/or ColY can also be empty in some cases. Based on presence/absence of these patterns, I would like to create 5 different columns with values X, Y or NA like this:
#chr start end count pattern_a pattern_b pattern_c pattern_d pattern_e
1 100 200 1 NA NA NA NA NA
1 300 400 2 X X X NA NA
2 100 400 1 Y NA NA NA NA
2 500 600 4 NA NA X Y X
I know how to do this for one pattern, but I need help to do this efficiently for multiple patterns. Here is my code so far -- which works for one pattern:
#!/usr/bin/env python
import csv
import sys
input_file = sys.argv[1]
with open(input_file, 'rU') as f:
data = csv.reader(f,delimiter='\t')
a=[]
for row in data:
if "pattern_a" in row[4]:
a = "X"
elif "pattern_a" in row[5]:
a = "Y"
else:
a = "NA"
print (row,a)
A:
Something like that might work:
import csv
import sys
input_file = sys.argv[1]
patterns = ['pattern_a', 'pattern_b', 'pattern_c', 'pattern_d', 'pattern_e']
with open(input_file, 'rU') as f:
data = csv.reader(f,delimiter='\t')
for row in data:
a=[]
for pattern in patterns:
if pattern in row[4]:
a.append("X")
elif pattern in row[5]:
a.append("Y")
else:
a.append("NA")
print (a)
Output of this is:
['NA', 'NA', 'NA', 'NA', 'NA']
['X', 'X', 'X', 'NA', 'NA']
['X', 'NA', 'NA', 'NA', 'NA']
['NA', 'NA', 'X', 'Y', 'X']
| {
"pile_set_name": "StackExchange"
} |
Q:
unable to access click event of a button in javascript
I want to access the click event of an element on my HTML page.
So, in chrome, I right-clicked the element -> selected Inspect element and got the following
<button type="submit" class="btn btn-primary" id="ben-count-submit">Update</button>
I then went to a js page and wrote the following
$("#ben-count-submit").click(function () {
console.log("clicked on the update button");
});
However, when I click on the button, I don't see any console log. It just takes me back to the home page of the web site and shows the url as the start page of the site appended with a '?' at the end as follows
http://localhost/myproject/start/?
How do I access the click event of this button? Where am I going wrong?
A:
Since your button is submit type, the button causes page refresh, you need to use preventDefault().
$("#ben-count-submit").click(function (event) {
event.preventDefault();
});
| {
"pile_set_name": "StackExchange"
} |
Q:
getRecyclerView returns null object
I am trying to create a View from code for a Fragment, where I had it inflate in the standard way. In the onCreateView from the Fragment I changed
View view = inflater.inflate(R.layout.list_layout, container, false);
mDragListView = (DragListView) view.findViewById(dlid); //R.id.drag_list_view
mDragListView.getRecyclerView().setVerticalScrollBarEnabled(true);
to
RelativeLayout rl = new RelativeLayout(getActivity());
DragListView dlv = new DragListView(getActivity());
int dlid = View.generateViewId();
dlv.setId(dlid);
rl.addView(dlv);
View view = rl;
mDragListView = (DragListView) view.findViewById(dlid);
mDragListView.getRecyclerView().setVerticalScrollBarEnabled(true);
with the list_layout being
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
android:id ="@+id/viewer_layout">
<com.woxthebox.draglistview.DragListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drag_list_view"
android:layout_width="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_height="match_parent"/>
In the second version it throws the stated error, that getRecyclerView() returns a nullobject, where it worked in the first version.
Help is appreciated and cheers
EDIT: could it be possible via this, that I can load the layout, when I inflate it in the "method" in ClassToBeImported.class?
A:
You are not calling
inflater.inflate(R.layout.list_layout, container, false);
in the new version. All layout elements will be null without it.
EDIT:
Since you already have a reference to the DragListView, you can use the instead of calling
view.findViewById(dlid);
Also return rl from onCreateView method.
EDIT2
If you have a local copy of DragListView implementation, try adding call to onFinishInflate in the constructor, so that it works when created from code as well.
public DragListView(Context context) {
super(context);
onFinishInflate();
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Cannot load main class from JAR file
I have an application Spark-scala, I tried to dispaly a simple message "Hello my App". when I compile it by sbt compile it's fine, also I run it by sbt run it's fine, I displayed my message with success but he display an error; like this:
Hello my application!
16/11/27 15:17:11 ERROR Utils: uncaught error in thread SparkListenerBus, stopping SparkContext
java.lang.InterruptedException
ERROR ContextCleaner: Error in cleaning thread
java.lang.InterruptedException
at org.apache.spark.ContextCleaner$$anon$1.run(ContextCleaner.scala:67)
16/11/27 15:17:11 INFO SparkUI: Stopped Spark web UI at http://10.0.2.15:4040
[success] Total time: 13 s, completed Nov 27, 2016 3:17:12 PM
16/11/27 15:17:12 INFO DiskBlockManager: Shutdown hook called
I can't understand, it's fine or no!
Also when i try to load my file jar after the run, he dispaly also an error:
my command line look like:
spark-submit "appfilms" --master local[4] target/scala-2.11/system-of-recommandation_2.11-1.0.jar
And the error this is:
Error: Cannot load main class from JAR file:/root/projectFilms/appfilms
Run with --help for usage help or --verbose for debug output
16/11/27 15:24:11 INFO Utils: Shutdown hook called
Please can you answers me!
A:
The error is due to the fact that the SparkContext is not stopped, this is required in versions higher than Spark 2.x.
This should be stopped to prevent this error by SparkContext.stop(), or sc.stop(). Inspiration for solving this error is gained from own experiences and the following sources: Spark Context, Spark Listener Bus error
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is the time a piece of the whole computaion (benchmking_f in this case) takes in parallel so much longer than the one in sequential approach?
I am trying to compare sequential computation and parallel computation in Python.
This is the bench mark function.
def benchmking_f(n=0):
import time
items = range(int(10**(6+n)))
def f2(x):return x*x
start = time.time()
sum_squared = 0
for i in items:
sum_squared += f2(i)
return time.time() - start
this sequential computation
problem_size = 2
import time
start = time.time()
tlist = []
for i in range(5):
tlist.append(benchmking_f(problem_size))
print('for loop took {}s'.format(time.time() - start))
print('each iterate took')
print(tlist)
took about 70s to finish the job; each iterate took
[14.209498167037964, 13.92169737815857, 13.949078798294067, 13.94432258605957, 14.004642486572266]
this parallel approach
problem_size = 2
import itertools
import multiprocessing
start = time.time()
pool = multiprocessing.Pool(5)
tlist = list(pool.map(benchmking_f, itertools.repeat(problem_size, 5)))
print('pool.map took {}s'.format(time.time() - start))
print('each iterate took')
print(tlist)
took about 42.45s; each iterate took
[41.17476940155029, 41.92032074928284, 41.50966739654541, 41.348535776138306, 41.06284761428833]
question
A piece of the whole computation (benchmking_f in this case) took about 14s in sequential and 42.45s in parallel
Why is that?
Note:
I am not asking the total time. I am asking the time that A piece of the whole computation, which takes on one iteration in for loop, and one process/thread in parallel.
1-iter benchmking_f takes.
A:
How many physical (not logical) cores do you have? You're trying to run 5 copies of the function simultaneously, the function takes 100% of one core for as long as it runs, and unless you have at least 5 physical cores they're going to fight each other tooth and nail for cycles.
I have 4 physical cores, but want to use my machine for other things too, so reduced your Pool(5) with Pool(3). Then the per-iterate timings were about the same either way.
Back of the envelope
Suppose you have a task that nails 100% of a CPU for T seconds. If you want to run S copies of that task simultaneously, that requires T*S cpu-seconds in total. If you have C entirely free physical cores to throw at it, at most min(C, S) cores can be working on the aggregate simultaneously, so to a first approximation the time needed will be:
T*S / min(C, S)
As another reply said, when you have more processes running than cores, the OS cycles through the processes for the duration, acting to make them all take about the same amount of wall-clock time (during some amount of which each process is doing nothing at all except waiting for the OS to let it run again for a while).
I'm guessing you have 2 physical cores. For your example, T is about 14 seconds, and S is 5, so if you had C=2 cores that works out to
14*5 / min(2, 5) = 14*5/2 = 35
seconds. You're actually seeing something closer to 41. Overheads account for part of that, but seems likely your machine was also doing other work at the same time, so your test run didn't get 100% of the 2 cores.
| {
"pile_set_name": "StackExchange"
} |
Q:
Reading from pasted input with line breaks in a Bash Script
I've been trying for a couple nights to get this Script to run with no luck. I'm trying to write a script using Bash that allows a user to paste a block of text, and the script will grep out the valid IP addresses from the text, and automatically ping them in order.
So far, after much modification, I'm stuck at this point:
#!/bin/sh
echo Paste Text with IP Addresses
read inputtext
echo "$inputtext">inputtext.txt
grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}" inputtext.txt > address.txt
awk '{print $1}' < address.txt | while read ip; do
if ping -c1 $ip >/dev/null 2>&1; then
echo $ip IS UP
else
echo $ip IS DOWN
fi
done
rm inputtext.txt
rm address.txt
After running this script, the user is prompted as desired, and if an IP address was included in the first line of text, the ping check will succeed, but then all the text after that line will be spat out onto the following command prompt. So it seems that my issue lies in when I read from user input. The only part that is being read is the first line, and once a break is encountered, the script does not considered any lines past the first in its work.
A:
As written, you just need an outer loop to actually read each line of user input.
#!/bin/sh
echo Paste Text with IP Addresses
while read -r inputtext
do
echo "$inputtext">inputtext.txt
grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}" inputtext.txt > address.txt
awk '{print $1}' < address.txt | while read ip; do
if ping -c1 $ip >/dev/null 2>&1; then
echo $ip IS UP
else
echo $ip IS DOWN
fi
done
rm inputtext.txt
rm address.txt
done
However, you can actually simplify this much further and eliminate the temporary files.
#!/bin/sh
echo Paste Text with IP Addresses
while read -r inputtext
do
ip=$(echo "$inputtext" | grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}" | awk '{print $1}')
if ping -c1 $ip >/dev/null 2>&1; then
echo $ip IS UP
else
echo $ip IS DOWN
fi
done
| {
"pile_set_name": "StackExchange"
} |
Q:
How to avoid exceptions thrown in onCompleted to be swallowed
Using rxJava 1.1.3, when throwing an exception in the onCompleted handling, the onErroris not called nor is the error propagated to the calling thread. It simply disappears.
As an example consider the following spock test:
def "when a onCompleted throws an IllegalStateException, it's handled by the onError handler"() {
given:
boolean onErrorCalledFromSubscribe = false
when:
Observable.just(1, 2, 3)
.subscribe(
Actions.empty(),
{ onErrorCalledFromSubscribe = true},
{throw new IllegalStateException("I'm behaving badly")})
then:
noExceptionThrown()
onErrorCalledFromSubscribe == true
}
The above test fails because onErrorCalledFromSubscribe is never called and is false at the end of the test.
Now, I can imagine that once onCompleted is called, onError shouldn't be called because either the one or the other should be called.
However, I wonder how do you handle such situations where a RuntimeException is called in your onCompleted method and you want to handle the error.
Do you simply wrap the onCompleted call in a try-catch and handle the error there?
A:
Just use a try-catch in onCompleted if you think there might be an exception thrown in there.
As I mentioned in the comments, RxJava should not be swallowing exceptions from onCompleted but currently is; still, if you know that there is going to be the possibility of an exception, you should just handle it yourself.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do you compute the time complexity of distributed algorithms?
How to compute the run-time of distributed algorithms in message passing systems? I was reading across and found it very weird that any computation done in each node is considered to take $\mathcal{O}(1)$ time due to the unreliability in the time it takes to pass messages. Since this approach is not practical at all, I am assuming that I have not understood it properly. Could someone please explain?
By impractical, I mean that I can simply solve any NP-Hard problem in distributed computing trivially in $\mathcal{O}(n^2)$ time by passing information throughout the network and then brute-forcing for the solution in $\mathcal{O}(1)$ time and this obviously seems stupid since in real life message passing shouldn't take more time than a brute-force solution over the search space.
A:
Time complexity is always measured relative to some model. For example, the $\Theta(n \log n)$ bound on sorting is the number of comparisons performed. If comparisons are not constant time, then the total number of operations will be higher.
Because of the high variability, and the overall time taken, often distributed algorithms are measured in terms of the number of messages sent. So in your example, you'd only solve it in $O(n^2)$ time if you assume that there is no cost to sending messages. If you're sending each possibility to a node, a good model will incorporate that cost, and you won't get magically fast solutions to $NP$-hard problems.
Also, for parallel computing, you model (approximately) how many nodes you have. It's a safe-bet to assume that you don't have more than $O(\log n)$ nodes for an input of size $n$. You certainly won't be able to scale your nodes exponentially, so brute-forcing doesn't always work.
Often, the computation done in distributed algorithms is minimal, or the computational content itself is intense, but orthogonal to the distributed nature of the algorithm (i.e. the algorithm is written over some abstract, computationally intensive task). In these cases, you usually only care about the messages sent or some other cost metric, since you might never know how many steps your computation takes.
A:
You understood it right. The standard models of distributed computing typically assume that local computation is free. It follows that in the LOCAL model of distributed computing, you can solve any graph problem in time $O(n)$, and in the CONGEST model of distributed computing, you can solve any graph problem in time $O(m)$ by brute force; here $n$ is the number of nodes and $m$ is the number of edges.
However, we are not interested in such running times in these models. For example, for the LOCAL model, the key question is what can be solved e.g. in polylogarithmic time time, or $O(\log n)$ time, or $O(\log^* n)$ time, or even $O(1)$ time. Now these are highly non-trivial questions even if you assume that local computation is free.
LOCAL and CONGEST are usually the wrong models if you are interested in studying e.g. NP-hard problems. However, if you consider "easy" problems (e.g. something that you can trivially solve in linear time with a centralised algorithm), then these models become much more interesting. Yes, of course you can find a maximal matching or a maximal independent set in linear time, but can you find it in sublinear time?
Here are the key definitions for reference:
LOCAL model: running time = number of synchronous rounds until all nodes stop and announce their local outputs; in each round each node can send a message to each of its neighbours; the message size is unbounded; local computation is free.
CONGEST model: as above, but messages are bounded to $O(\log n)$ bits.
| {
"pile_set_name": "StackExchange"
} |
Q:
Azure - Not Redirecting to Default Page and showing "Could not load file or assembly 'DotNetOpenAuth.Core'" Error
I have been working with a Project which is split into the following:
(1) Client Application (HTML5, CSS3, JS / AngularJS) and
(2) WebAPI.
It works fine locally, when I run the application, however, when I deployed the application to Azure and I attempt to access the client application, I get the below error:
Could not load file or assembly 'DotNetOpenAuth.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=2780ccd10d57b246' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
When I type /index.html within the browser, the default page then loads correctly, however, I would like that the redirection happens automatically, without showing the error.
I have set the redirection to the default page in IIS as well, but it is not redirecting by default.
I was reading some of the other questions similar to this error, however, I do not even have a packages.config file since the Client application I have, is mostly a HTML5 / CSS and JS application.
A:
I have found the solution from a Microsoft Azure support agent. When re-deploying the site with the the option "Remove additional files at destination", this is now working.
This may be because of some default code Azure Websites is trying to run as a default page, so by checking that option, any previous code is replaced.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python - Convertir float en string
Tengo una matriz de floats de 3000 por 17, el tema es que en la primer columna quiero guardar strings.
Con el siguiente código:
tabla = numpy.empty((3000, 17))
nombres = ['i0{i}_0{d}_{n}.bmp'.format(i = imagen, d = distorsion, n =
nivel) for imagen in range(1,26) for distorsion in range(1,25) for
nivel in range(1,6)]
tabla[:, 0] = nombres
Obviamente python da el siguiente error:
ValueError: could not convert string to float: 'i01_01_1.bmp'
Pero yo no quiero convertir los strings en float, sino guardar strings en ESA columna, en el resto de la matriz tendré valores float.
Espero puedan ayudarme.
Desde ya muchas gracias.
Saludos.
Lucía
A:
tienes un array bidimensional
a=[[1,2,3],[2,3,4],[3,4,5]]
tienes un array unidimensional
b=['bar','foo','car']
y cambias el primer valor de cada una por el valor en b
for x in a[:]:
x[0]=b[a.index(x)]
[['bar', 2, 3], ['foo', 3, 4], ['car', 4, 5]]
aplicado en tu ejemplo
a=tabla.tolist()
for x in a[:]:
x[0]=nombres[a.index(x)]
print a
| {
"pile_set_name": "StackExchange"
} |
Q:
The way into logic, Gödel and Turing
I have always read about the geniuses of Alan Turing and Kurt Gödel . Many websites mention their works in logic as revolutionary. I want to understand their works, but I don't exactly know the way through which I should go in order to understand their work. To be precise, I want to know the prerequisites required to learn their theories. I hope that members here can suggest the correct way.
A:
For a (freely available) route into Gödel, you could always try my notes, Gödel Without (too many) Tears.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set property value in instance time?
In C# is usual set object property in instance time
Like this code
People p = new People(){Name = "John", Age = 18};
Have any solution like this in PHP?
A:
At the moment, other than the normal constructor methods, no, you can't do that in PHP. However, there are RFC's here and here for something similar to this, so maybe in a few version's time it will be available.
| {
"pile_set_name": "StackExchange"
} |
Q:
Limit comparisons on series with difficult comparisons?
For example, suppose I have the following series: $$\sum_{k = 1}^\infty sin\left(\frac{1}{k}\right)$$
Since the inside doesn't converge, does $sin(1/x)$ diverge? I have to use the limit test somehow.
A:
In this case, you have
$$
\lim_{k\to\infty}\frac{\sin\frac1k}{\frac1k}=1,
$$
which tells you that the behaviour of your series is the same as that of the harmonic series $\sum_{k=1}^\infty\frac1k$.
Note that for big $k$, $\sin1/k>0$, so the limit comparison test applies.
| {
"pile_set_name": "StackExchange"
} |
Q:
Probability question involving derangements
$n$ married couples came to a dancing night. For a dance women randomly choose men, $X$ is the number of dancing married couples, we need to find the distribution of $X$ and its probability generating function.
My attempt:
If $k$ married couples are dancing, then there are $\binom n k$ ways to select those $k$ couples out of $n$, also all other $n-k$ women and $n-k$ men are mixed so that $n-k$ married couples do not dance together. The number of ways to do that mixing is the number of derangements for $n-k$ elements, i.e. $(n-k)!\sum_{i=0}^{n-k}\frac{(-1)^i}{i!}$. There are $n!$ possible ways to build dancing couples. Thus:
$$P(X=k)=\binom n k \frac{(n-k)!}{n!}\sum_{i=0}^{n-k}\frac{(-1)^i}{i!}=\frac{1}{k!} \sum_{i=0}^{n-k}\frac{(-1)^i}{i!} \tag{A}$$
$$g_X(t)=E[t^X]=\sum_{k=0}^{n}t^k\frac{1}{k!} \sum_{i=0}^{n-k}\frac{(-1)^i}{i!} \tag{B}$$
I know that $g_X(t)$ is supposed to be $\sum_{k=0}^{n}\frac{(t-1)^k}{k!}$.
Any ideas how can I get there?
A:
Binomial expansion:
$$\sum_{k=0}^n \frac{(t-1)^k}{k!} = \sum_{k=0}^n \sum_{i = 0}^{k} \frac{1}{k!} {k \choose i} t^i (-1)^{k - i}$$
Use $\sum_{x = 0}^b \sum_{y=0}^x f(x,y) = \sum_{y = 0}^b \sum_{x=y}^b f(x, y)$ as both are sums over $(x, y)$ with $0 \le y \le x \le b$:
$$ = \sum_{i = 0}^{n} \sum_{k=i}^n \frac{1}{k!} {k \choose i} t^i (-1)^{k - i}$$
Reverse the variable names for $i$ and $k$:
$$ = \sum_{k = 0}^{n} \sum_{i=k}^n \frac{1}{i!} {i \choose k} t^k (-1)^{i - k}$$
Substitute $j = i-k$:
$$ = \sum_{k = 0}^{n} \sum_{j=0}^{n-k} \frac{1}{(j+k)!} {j+k \choose k} t^k (-1)^{j}$$
Expand the combination:
$$ = \sum_{k = 0}^{n} \sum_{j=0}^{n-k} \frac{1}{(j+k)!} \frac{(j+k)!}{k!(j+k-k)!} t^k (-1)^{j}$$
Tidy:
$$ = \sum_{k = 0}^{n} \frac{t^k}{k!}\sum_{j=0}^{n-k} \frac{(-1)^{j}}{j!} $$
| {
"pile_set_name": "StackExchange"
} |
Q:
why isnt my dialog taking up entire screen width
I am using a custom dialog to display something on the screen
the green part is the dialog - and it is supposed to be entire screen width
why isnt it taking up entire screen width ?
this is my code for the dialog
participantsPanelDialog = new Dialog(getSherlockActivity(), R.style.ParticipantsDialog);
// Making sure there's no title.
participantsPanelDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Making dialog content transparent.
participantsPanelDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
// Removing window dim normally visible when dialog are shown.
participantsPanelDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
participantsPanelDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
// Setting position of content, relative to window.
WindowManager.LayoutParams params = participantsPanelDialog.getWindow().getAttributes();
params.gravity = Gravity.TOP | Gravity.LEFT;
params.x = 0;
params.y = 0;
// params.width = ((Activity) getActivity()).getWindow().getAttributes().width;
// Toast.makeText(getActivity(), "width: " +params.width, Toast.LENGTH_LONG).show();
participantsPanelDialog.getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
this is my layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<RelativeLayout
android:id="@+id/topPanelOpen"
android:layout_width="match_parent"
android:layout_height="210dp"
android:background="@drawable/top_pannel_open"
android:orientation="horizontal"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:paddingTop="5dp" >
<RelativeLayout
android:id="@+id/lytOneParticipant"
android:layout_width="match_parent"
android:layout_height="145dp"
android:visibility="gone" >
<RelativeLayout
android:id="@+id/lytInfoOneParticipant"
android:layout_width="match_parent"
android:layout_height="@dimen/abs__action_bar_default_height"
android:orientation="vertical" >
<ImageView
android:id="@+id/ivPeopleIcon"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_gravity="left"
android:scaleType="centerCrop"
android:src="@drawable/ic_people_normal" />
<TextView
android:id="@+id/tvParticipantName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/ivPeopleIcon"
android:text="ParticipantName"
android:textColor="@android:color/white" />
<ImageView
android:id="@+id/btnAddParticipants"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@+id/btnClose"
android:gravity="center"
android:onClick="onParticipantsMenuItemSelected"
android:paddingRight="12dp"
android:scaleType="centerInside"
android:src="@drawable/ic_add_normal" />
<ImageView
android:id="@+id/btnClose"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:onClick="onParticipantsMenuItemSelected"
android:paddingLeft="12dp"
android:src="@drawable/ic_close_normal" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/lytInfoOneParticipant" >
<ImageView
android:id="@+id/leftArrow"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:paddingRight="16dp"
android:onClick="onParticipantsMenuItemSelected"
android:src="@drawable/ic_arrow_left_normal" />
<ImageView
android:id="@+id/avatar"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_above="@+id/itemCount"
android:layout_toRightOf="@+id/leftArrow" />
<TextView
android:id="@+id/itemCount"
android:layout_width="60dp"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/avatar"
android:layout_alignParentBottom="true"
android:gravity="center_horizontal"
android:text="TEXT"
android:textColor="@android:color/white"
android:textSize="24sp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignBottom="@+id/avatar"
android:layout_alignTop="@+id/avatar"
android:layout_marginLeft="5dp"
android:layout_toLeftOf="@+id/rightArrow"
android:layout_toRightOf="@+id/avatar"
android:orientation="vertical" >
<TextView
android:id="@+id/tvEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="1dp"
android:layout_weight="1"
android:background="@drawable/white_round_corners"
android:gravity="center_vertical"
android:paddingLeft="5dp"
android:text="Email Address"
android:textSize="18sp" />
<TextView
android:id="@+id/tvName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginTop="1dp"
android:layout_weight="1"
android:background="@drawable/white_round_corners"
android:gravity="center_vertical"
android:paddingLeft="5dp"
android:text="Full Name"
android:textSize="18sp" />
</LinearLayout>
<ImageView
android:id="@+id/rightArrow"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:paddingBottom="1dp"
android:paddingLeft="16dp"
android:onClick="onParticipantsMenuItemSelected"
android:src="@drawable/ic_arrow_right_normal" />
</RelativeLayout>
</RelativeLayout>
<RelativeLayout
android:id="@+id/lytAllParticipants"
android:layout_width="match_parent"
android:layout_height="145dp"
android:orientation="horizontal"
>
<LinearLayout
android:id="@+id/lytInfo"
android:layout_width="match_parent"
android:layout_height="@dimen/abs__action_bar_default_height"
android:layout_toLeftOf="@+id/lytControls"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/tvNumPhotosInAlbum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:gravity="top"
android:text="645"
android:textColor="@android:color/white"
android:textSize="22sp" />
<View
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="1" />
<TextView
android:id="@+id/tvNumPhotosInAlbumText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:gravity="bottom"
android:text="@string/numPhotosInAlbumText"
android:textColor="@android:color/white" />
</LinearLayout>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="@drawable/divider" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ImageView
android:id="@+id/ivPeopleIcon"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_gravity="center_horizontal"
android:scaleType="centerCrop"
android:src="@drawable/ic_people_normal" />
<TextView
android:id="@+id/tvPeopleSharing"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:gravity="top"
android:includeFontPadding="false"
android:paddingLeft="5dp"
android:text="5"
android:textColor="@android:color/white"
android:textSize="24dp" />
</LinearLayout>
<TextView
android:id="@+id/tvPeopleSharingText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:gravity="bottom"
android:text="@string/numPeopleSharingText"
android:textColor="@android:color/white" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/lytControls"
android:layout_width="wrap_content"
android:layout_height="150dp"
android:layout_alignParentRight="true"
android:orientation="vertical" >
<ImageView
android:id="@+id/btnEditAlbum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onParticipantsMenuItemSelected"
android:src="@drawable/selector_settings" />
<ImageView
android:id="@+id/btnAddParticipants"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:onClick="onParticipantsMenuItemSelected"
android:scaleType="centerInside"
android:src="@drawable/ic_add_normal" />
</LinearLayout>
<com.devsmart.android.ui.HorizontalListView
android:id="@+id/participantsListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/lytInfo"
android:layout_marginTop="5dp"
android:layout_toLeftOf="@+id/lytControls" />
</RelativeLayout>
<!-- this view opens the panel do NOT delete it -->
<View
android:id="@+id/openPanel"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:layout_marginLeft="24dp"
android:alpha="0.4" />
</RelativeLayout>
</RelativeLayout>
and this is the result:
A:
My problem was that when I was creating the dialog, I was extending the Android.Theme.Dialog style
which made it shrink
In this style R.style.ParticipantsDialog - I removed the parent theme, and it grew to full size like i wanted
| {
"pile_set_name": "StackExchange"
} |
Q:
Css-what kinds of "IF" statements there are?
I'm dealing with crossbrowser issues... So I׳m looking for the best and clean CSS
One of the most important issues is the "IF" statements for each browser
A:
Take a look at this page:
http://www.conditional-css.com/usage
It contains every information you'll need.
| {
"pile_set_name": "StackExchange"
} |
Q:
What to do with 'looking for a good tutorial on X' questions?
Most of them are very straightforward candidates for lmgtfy-like answer, but sometimes it's not quite simple: even the search term to start with is difficult to guess (that's especially true with the freshest techs).
The problem, as I see it, is that the good answer on those is essentially a link-only answer, and link-only answers are bad (by many reasons).
So should these questions be closed? If so, what reason to choose? The questions are NOT about opinions/recommendations: it's not about the best tutorials - any will do, usually.
A:
Such questions should still be closed as
Questions asking us to recommend or find a tool, library or favorite
off-site resource are off-topic for Stack Overflow as they tend to
attract opinionated answers and spam. Instead, describe the problem
and what has been done so far to solve it.
Just because its not looking for the best tutorial it is still looking for a tutorial which is an "off-site resource" recommendation
A:
I mean, does asking for external resource matter that much? –
raina77ow
These questions often go something like this...
Q: Where can I find a tutorial on X?
A: I've written a dozen blog entries about X check out my site here - link.
Basically the whole answer is a link, with a little shameless self promotion sprinkled on top.
Even if the question somehow doesn't attract a lot of self promotion, it will still at best end up as just a list of tangentially related tutorials, blogs, book recommendations, and so on...
Also note that no matter how you word these kinds of recommendation questions people will inevitably boil over into some non-constructive discussion about the pros and cons of the tutorials mentioned.
(To test this theory: mention w3schools w3fools and watch the sparks fly)
Rather than asking for a tutorial for X, just ask a specific question about X.
How do I W the X for Y and Z?
| {
"pile_set_name": "StackExchange"
} |
Q:
all column data in one column separated by special character say -
I have table as below
create table myTable (id int,
col1 varchar(20),
col2 varchar(20),
col3 varchar(20),
col4 varchar(20),
col5 varchar(20),
col6 varchar(20),
col7 varchar(20),
col8 varchar(20),
col9 varchar(20)
);
And have data as
insert into myTable values
(1, 'col1','col2','col3','col4','col5','col6','col7','col8','col9');
What I want is output as
id + AllInOne
++++++++++++++++++++++++++++++++++++++++++++++++++
1 + col1-col2-col3-col4-col5-col6-col7-col8-col9
++++++++++++++++++++++++++++++++++++++++++++++++++
Any idea how to get this done with smallest query? I know I could do above with use of CONCATENATE. But I would need is some other way. Maybe some pre-defined MySQL function?
Data at sqlfiddle
A:
Use CONCAT_WS, that concatenates strings (skipping null ones) with a separator:
SELECT id, CONCAT_WS('-', col1, col2, col3, col4, col5, col6, col7, col8, col9)
FROM your_table
| {
"pile_set_name": "StackExchange"
} |
Q:
Posting video on facebook wall using fb sdk
i am getting error in log cat
{Response: responseCode: 400, graphObject: null, error: {HttpStatus:
400, errorCode: 353, errorType: OAuthException, errorMessage: (#353)
Missing video file}, isFromCache:false}
using below Method
private void postVideo() {
try {
File file = new File(videoPath);
ParcelFileDescriptor descriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
Bundle parameters = new Bundle(1);
parameters.putParcelable(file.getName(), descriptor);
new Request(Session.getActiveSession(), "me/videos", parameters, HttpMethod.POST, new Request.Callback() {
@Override
public void onCompleted(Response response) {
Constants.showLog(TAG, "In Response " + response.getGraphObject().getProperty("id"));
JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
String postId = null;
try {
postId = graphResponse.getString("id");
Constants.showLog(TAG, "In Response id " + postId);
} catch (JSONException e) {
Constants.showLog(TAG,"JSON error "+ e.getMessage());
}
}
}).executeAsync();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
please help
A:
I see you are using the Android SDK 3.0, and with that we included a simple way to upload videos. Here is my code that I use to upload videos to Facebook:
Request.Callback callback5 = new Request.Callback() {
public void onCompleted(Response response) {
// response will have an id if successful
}
};
File tempFile;
try {
tempFile = Util.createTempFileFromAsset(getApplicationContext(), "video.mp4");
Request request5 = Request.newUploadVideoRequest(session,
tempFile, callback5);
RequestAsyncTask task5 = new RequestAsyncTask(request5);
task5.execute();
} catch (IOException e) {
Log.e(Util.TAG, "failed to create temp file");
e.printStackTrace();
}
and the code for createTempFileFromAsset:
public static File createTempFileFromAsset(Context context, String assetPath)
throws IOException {
InputStream inputStream = null;
FileOutputStream outStream = null;
try {
AssetManager assets = context.getResources().getAssets();
inputStream = assets.open(assetPath);
File outputDir = context.getCacheDir(); // context being the
// Activity pointer
File outputFile = File.createTempFile("prefix", assetPath,
outputDir);
outStream = new FileOutputStream(outputFile);
final int bufferSize = 1024 * 2;
byte[] buffer = new byte[bufferSize];
int n = 0;
while ((n = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, n);
}
return outputFile;
} finally {
Utility.closeQuietly(outStream);
Utility.closeQuietly(inputStream);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Neo4j long lasting query to be split/executed in smaller chunks?
My import.csv creates many nodes and merging creates a huge cartesian product and runs in a transaction timeout since the data has grown so much. I've currently set the transaction timeout to 1 second because every other query is very quick and is not supposed to take any longer than one second to finish.
Is there a way to split or execute this specific query in smaller chunks to prevent a timeout?
Upping or disabling the transaction timeout in the neo4j.conf is not an option because the neo4j service needs a restart for every change made in the config.
The query hitting the timeout from my import script:
MATCH (l:NameLabel)
MATCH (m:Movie {id: l.id,somevalue: l.somevalue})
MERGE (m)-[:LABEL {path: l.path}]->(l);
Nodecounts: 1000 Movie, 2500 Namelabel
A:
You can try installing APOC Procedures and using the procedure apoc.periodic.commit.
call apoc.periodic.commit("
MATCH (l:Namelabel)
WHERE NOT (l)-[:LABEL]->(:Movie)
WITH l LIMIT {limit}
MATCH (m:Movie {id: l.id,somevalue: l.somevalue})
MERGE (m)-[:LABEL {path: l.path}]->(l)
RETURN count(*)
",{limit:1000})
The below query will be executed repeatedly in separate transactions until it returns 0.
You can change the value of {limit : 1000}.
Note: remember to install APOC Procedures according the version of Neo4j you are using. Take a look in the Version Compatibility Matrix.
| {
"pile_set_name": "StackExchange"
} |
Q:
Android Studio "Wrong argument type for formatting Error" in String.format()
TextView textview = (TextView)findViewById(timeScore);
i = (int)(gridView.getTime() / 1000L);
String s = getString(time_score);
Object aobj[] = new Object[1];
aobj[0] = Integer.valueOf(i);
textview.setText(String.format(s, aobj));
Getting Error in Android Studio in last conversion aobj
"Wrong Argument type for formatting argument #1 in time_score: conversion 'd', recevied Object (argument #2 in method call)"
A:
I think it's because of textview.setText(String.format(s, aobj));
Your string format require integer value but you pass a array to it.
Try this: textview.setText(String.format(s, i));
Hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
response redirect from .ashx file
I have ashx file and I want to redirect from ashx to aspx page. Some solution?
A:
void ProcessRequest(HttpContext context)
{
context.Response.Redirect(newUrl);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
System.Runtime.Serialization.Json.DataContractJsonSerializer.WriteObject ignores NonSerialized attribute while serializing
If i try to serialize an object of the following ClassToSerialize class with System.Runtime.Serialization.Json.DataContractJsonSerializer
[DataContract,Serializable]
public class ClassToSerialize
{
[NonSerialized] private bool _mf;
public bool IsMf
{
get { return _mf};
set{ _mf = value;}
}
[DataMember]
public char PrimaryExc { get; set; }
}
public class TestClass
{
ClassToSerialize obj = new ClassToSerialize{PrimaryExchange = 'a', NoResults = true};
var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(ClassToSerialize);
var ms = new MemoryStream();
serializer.WriteObject(ms, obj);
return Encoding.UTF8.GetString(ms.ToArray());
}
The return string still contains IsMf property and its value. The NOnSerialized attribute is ignored. Can someone please suggest what attribute to use when using DataContractJsonSerializer so as to not serialize some properties
A:
The following code worked for me (it's almost identical to your's with a few small compilation errors fixed):
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
class Program
{
static void Main()
{
var obj = new ClassToSerialize
{
PrimaryExc = 'a',
NoResults = true
};
var serializer
= new DataContractJsonSerializer(typeof(ClassToSerialize));
var ms = new MemoryStream();
serializer.WriteObject(ms, obj);
Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
}
}
[DataContract]
[Serializable]
public class ClassToSerialize
{
[NonSerialized]
private bool _mf;
public bool IsMf
{
get { return _mf; }
set { _mf = value; }
}
[DataMember]
public bool NoResults { get; set; }
[DataMember]
public char PrimaryExc { get; set; }
}
Output:
{"NoResults":true,"PrimaryExc":"a"}
| {
"pile_set_name": "StackExchange"
} |
Q:
C compiler expecting additional argument in function despite not being declared
I am declaring a function with 2 arguments and calling it with 2 arguments however the compiler seems to be converting it into a function that requires an additional argument of type FILE * __restrict.
I'm on Mac OSX 10.11.6
using both cc and gcc produces the same error.
What argument should I be giving the function or should I be changing a setting with my compiler? Or have I just missed a typo somewhere...
Errors are:
longest-line.c:6:5: error: conflicting types for 'getline'
int getline(char line[], int maxline);
^
/usr/include/stdio.h:442:9: note: previous declaration is here
ssize_t getline(char ** __restrict, size_t * __restrict, FILE * __restrict) __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3);
^
longest-line.c:17:37: error: too few arguments to function call, expected 3, have 2
while ((len = getline(line, MAXLINE)) > 0)
~~~~~~~ ^
/usr/include/stdio.h:442:1: note: 'getline' declared here
ssize_t getline(char ** __restrict, size_t * __restrict, FILE * __restrict) __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3);
^
longest-line.c:28:5: error: conflicting types for 'getline'
int getline(char s[], int lim)
^
/usr/include/stdio.h:442:9: note: previous declaration is here
ssize_t getline(char ** __restrict, size_t * __restrict, FILE * __restrict) __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3);
^
3 errors generated.
Code is:
#include <stdio.h>
#define MAXLINE 1000
int getline(char line[], int maxline);
void copy(char to[], char from[]);
int main()
{
int len; /* current line length */
int max; /* maximum length so far */
char line[MAXLINE]; /* current input line */
char longest[MAXLINE]; /* longest line saved here */
max = 0;
while ((len = getline(line, MAXLINE)) > 0)
if (len > max) {
max = len;
copy(longest, line);
}
if (max > 0) /* there was a line */
printf("%s", longest);
return 0;
}
int getline(char s[], int lim)
{
int c, i;
for (i = 0; i<lim-1 && (c=getchar()) != 'X' && c!='\n'; ++i)
s[i] = c;
if (c == '\n') {
s[i] = c;
i++;
}
s[i] = '\0';
return i;
}
void copy(char to[], char from[])
{
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
++i;
}
A:
getline is a name reserved (in POSIX), you can't use it without trouble, change your function name.
| {
"pile_set_name": "StackExchange"
} |
Q:
Slick: query multiple tables/databases with getting column names
I have methods in my Play app that query database tables with over hundred columns. I can't define case class for each such query, because it would be just ridiculously big and would have to be changed with each alter of the table on the database.
I'm using this approach, where result of the query looks like this:
Map(columnName1 -> columnVal1, columnName2 -> columnVal2, ...)
Example of the code:
implicit val getListStringResult = GetResult[List[Any]] (
r => (1 to r.numColumns).map(_ => r.nextObject).toList
)
def getSomething(): Map[String, Any] = DB.withSession {
val columns = MTable.getTables(None, None, None, None).list.filter(_.name.name == "myTable").head.getColumns.list.map(_.column)
val result = sql"""SELECT * FROM myTable LIMIT 1""".as[List[Any]].firstOption.map(columns zip _ toMap).get
}
This is not a problem when query only runs on a single database and single table. I need to be able to use multiple tables and databases in my query like this:
def getSomething(): Map[String, Any] = DB.withSession {
//The line below is no longer valid because of multiple tables/databases
val columns = MTable.getTables(None, None, None, None).list.filter(_.name.name == "table1").head.getColumns.list.map(_.column)
val result = sql"""
SELECT *
FROM db1.table1
LEFT JOIN db2.table2 ON db2.table2.col1 = db1.table1.col1
LIMIT 1
""".as[List[Any]].firstOption.map(columns zip _ toMap).get
}
The same approach can no longer be used to retrieve column names. This problem doesn't exist when using something like PHP PDO or Java JDBCTemplate - these retrieve column names without any extra effort needed.
My question is: how do I achieve this with Slick?
A:
import scala.slick.jdbc.{GetResult,PositionedResult}
object ResultMap extends GetResult[Map[String,Any]] {
def apply(pr: PositionedResult) = {
val rs = pr.rs // <- jdbc result set
val md = rs.getMetaData();
val res = (1 to pr.numColumns).map{ i=> md.getColumnName(i) -> rs.getObject(i) }.toMap
pr.nextRow // <- use Slick's advance method to avoid endless loop
res
}
}
val result = sql"select * from ...".as(ResultMap).firstOption
| {
"pile_set_name": "StackExchange"
} |
Q:
django- how to serve an image in all templates of django app?
I want to show user's avatar in all pages of my django project.
I use an <img> tag in base.html and in the href I write: {{ request.user.profile.get_avatar }}.
but it does not work properly.
in the first page of project it works but in another pages does not work.
The problem is for addresses.
for example in index page with url www.mysite.com/index the image shows. but in www.mysite.com/v1/v2/v3 image does not show.
This is the get_avatar method of profile class:
def get_avatar(self):
if self.avatar:
return os.path.join(settings.MEDIA_URL + str(self.avatar))
else:
return os.path.join(settings.MEDIA_URL + str('avatars/student.jpg'))
view of not working picture
def profile_me(request):
the_profile = get_object_or_404(Profile, user=request.user)
klasses = KlassStudents.objects.filter(student=request.user.profile)
return render(request, 'ejazeostad/profile/profile.html', {'profile': the_profile, 'klasses': klasses})
A:
The MEDIA_URL setting should be an absolute URL, e.g.
MEDIA_URL = '/files/'
At the moment, you have a relative URL 'files/'. That means that the URL changes depending on which page you are on. When you visit www.mysite.com/index, the relative URL expands to www.mysite.com/files/avatars/avatar.jpg which works, but when you visit www.mysite.com/v1/v2/v3, the relative URL is expanded to www.mysite.com/v1/v2/files/avatars/avatar.jpg which is incorrect.
| {
"pile_set_name": "StackExchange"
} |
Q:
Starting a new web site, Search Engine Jumpstart yes or no
I'm starting a new webs site and they offer me for Search Engine Jumpstart, should I buy it?
What's your opinion about that?
A:
Search Engine Jumpstart says that you get rapid indexing on Google, Yahoo, and Bing (in days). There are easier ways to do this yourself: Ping your website using a service like Pingomatic.
In the end it's not worth it.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to exclude a directory in a recursive search using grep?
How to do a recursive search using grep while excluding a particular directory ?
Background : I have a large directory consisting of log files which I would like to eliminate in the search. The easiest way is to move the log folder. Unfortunately I cannot do that, as the project mandates the location.
Any idea how to do it ?
A:
are you looking for this?
from grep man page:
--exclude-dir=DIR
Exclude directories matching the pattern DIR from recursive searches.
| {
"pile_set_name": "StackExchange"
} |
Q:
Call 'structure' to save in postgres using rails
I have a 'publication' data structure, and my table name in postgres is 'publications'. I get a tweet from streaming and parse it according in class TweetFetcher. How do I call publication controller to save it to the database? PublicationController has the standard scrum abilities (new, create, show, edit...), where create is:
def create
@publication = Publications.new(params[:publication])
if @publication.save
redirect_to :action => 'list'
else
@subjects = Subject.find(:all)
render :action => 'new'
end
end
and parte of my twitter code is
class TweetFetcher
def saveTweet(parsedTweet)
pT = JSON.parse(parsedTweet)
#save here. like this?
#PublicationController.create(parsedTweet)
end
end
A:
You shouldn't be using your controller in this situation, instead you can just build your record like this:
class TweetFetcher
def saveTweet(parsedTweet)
pT = JSON.parse(parsedTweet)
publication = Publications.new
publication.sample_field = pT.sample_field
... # set additional attributes
publication.save
end
end
Additionally, here is some advice/information that is not directly related to your question, but are things you should know:
The class name of your models should be singular, so instead of Publications, it should be Publication.
Method and variable names should be in snake case rather than camel case (i.e. save_tweet instead of saveTweet or parsed_tweet instead of parsedTweet).
The new hash syntax is prefered, unless of course you are using a Ruby version below 1.9. This looks like { key: value } instead of { key => value }.
Indentation for Ruby code is typically 2 spaces.
That being said, I would change your code like this:
PublicationsController#create
def create
@publication = Publication.new(params[:publication])
if @publication.save
redirect_to action: 'list'
else
@subjects = Subject.find(:all)
render action: 'new'
end
end
TweeFetcher
class TweetFetcher
def save_tweet(tweet)
parsed_tweet = JSON.parse(tweet)
publication = Publication.new
publication.sample_field = parsed_tweet.sample_field
... # set additional attributes
publication.save
end
end
| {
"pile_set_name": "StackExchange"
} |
Q:
What does "public api" means in Semantic Versioning?
I'm learning about how to assign and increment version numbers with the rule called "Semantic Versioning" from http://semver.org/.
Among all its rules, the first one said:
Software using Semantic Versioning MUST declare a public API. This API could be declared in the code itself or exist strictly in documentation. However it is done, it should be precise and comprehensive"
I am confused about "public API". What does it refer to?
A:
Public API refers to the "point of access" that the external world (users, other programs and/or programmers, etc) have to your software.
E.g., if you're developing a library, the public API is the set of all the methods invokations that can be made to your library.
There is understanding that, unless a major version changes, your API will be backwards-compatible, i.e. all the calls that were valid on a version will be valid on a later version.
You can read at point 9 of those rules:
Major version X (X.y.z | X > 0) MUST be incremented if any backwards incompatible changes are introduced to the public API.
| {
"pile_set_name": "StackExchange"
} |
Q:
Where to place my local website starting with the 2.4.7 version of apache2?
I recently installed Ubuntu 14.04, then I installed lamp-server and placed my webpages in /var/www directory, but when I opened localhost in the browser there was nothing.
I think that happened because Zend updated Apache.
Whatever the reason may be, I want to know where to keep my php files so that I can access them from my browser.
A:
The apache2 version that was published when the Ubuntu 14.04 release was made is 2.4.7 and starting with this version it seems that, for security reasons, the new root directory for the server is:
/var/www/html
So, from now on, this is where you must place the files for your (local) website. You should not have this problem again with the future updates.
Anyway, if you want to change this directory with another one, you have to modify (as root) the following line from /etc/apache2/sites-available/000-default.conf file (sudo nano /etc/apache2/sites-available/000-default.conf):
DocumentRoot /var/www/html
to
DocumentRoot /path/to/another/directory
After this, for the new changes to take effect, you have to restart the apache server using the following command:
sudo service apache2 restart
A:
Instead of modifying /etc/apache2/sites-available/000-default.conf back to the old version, I prefer keeping default package files unmodified.
A reason for this is that so it wouldn't break during the next upgrade again which might reset the 000-default.conf file.
Besides, such modifications are not done just to annoy us, the modification was done for a good reason, as this bug report in Debian explains.
Our webservers [sic] set the default document root to /var/www, whereas
site-local administrators tend to use /var/www/example.com. This has
security implications if visitors access the default document root,
bypassing the /supposed/ document root of example.com. That's
problematic if sensitive data is placeѕ outside the supposed
document root (e.g. consider a hypothetical
/var/www/example-com-db.conf configuration file).
A better solution would be to move the sites files from /var/www to /var/www/html/.
# 1. move all files excluding the `html` directory
sudo mv /var/www/[!html]* /var/www/html
# 2. Move the hidden files as well which are skipped in previous command
sudo mv /var/www/.[!.]?* /var/www/html/
Also, another possible solution is to create another Virtual Host and disable the default one with the command sudo a2dissite 000-default
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL trying to do a JOIN to include results from multiple Tables
I'm a complete novice teaching myself SQL by writing and modifying a few queries and reports at work.
I've got something of a handle on the various types of JOINs and I've used INNER JOIN a few times with decent success.
What I'm stuck on should be a simple task, but my Google-Fu must be weak. Here's what I'm trying to do.
Say I have 3 tables, Table_A, Table_B, and Table_C, and each table has a column called [Serial_Number].
What I'm wanting to select is 3 of the other columns if A.Serial_Number = B.Serial_Number OR C.Serial_Number.
I've tried doing:
SELECT
*
FROM
Table_A AS A
INNER JOIN Table_B AS B ON A.Serial_Number = B.Serial_Number
INNER JOIN Table_C AS C ON A.Serial_Number = C.Serial_Number
But this always yields 0 results as the nature of the data dictates that if A matches B, it will never match C and vice versa. I also tried a LEFT OUTER JOIN as the second clause, but this just includes NULLs from Table_C that have already matched on Table_B.
All the searches I have done relating to JOINs on multiple tables seem to be about using JOINS to further exclude records, where I'm actually wanting to INCLUDE more records.
Like I said, I'm sure this is really simple, just needing a nudge in right direction.
Thanks!
A:
The use of two inner joins here is akin to saying
If A.Serial_Number = B.Serial_Number AND
A.Serial_Number = C.Serial_Number
Using left outer join on the second clause - by which i presume you mean second join - would perform a left join on a result set already filtered by A.Serial_Number = B.Serial_Number by the first inner join. Given that B.Serial_Number doesn't relate to C.Serial_Number you wouldn't expect the an equijoin to return any result from tablec.
What you want is a left outer join like you tried but for both tableb and tablec.
Select *
From tablea
Left join tableb on tableb.Serial_Number = tablea.Serial_Number
Left join tablec on tablec.Serial_Number = tablea.Serial_Number
This way regardless of whether tablea.Serial_Number is in tableb it will still be returned and thus available to be joined to tablec
| {
"pile_set_name": "StackExchange"
} |
Q:
Android- SetOutlineAmbientShadowColor No such method error on api < 28
I have a custom button renderer that extends MaterialButtonRenderer.
I need to use:
Control.SetOutlineAmbientShadowColor(Android.Graphics.Color.Transparent);
Control.SetOutlineSpotShadowColor(Android.Graphics.Color.Transparent);
but this works only with API >= 28.
There is a workaround to make it works with lower API?
I need to run the application from API 26.
Regards.
A:
You can add the button style in the styles.xml
<item name="android:buttonStyle">@style/Widget.MaterialComponents.Button.UnelevatedButton</item>
Here is a screenshot about it running result in android 7.0.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to show vales of a json file in HTML (Looped json format Object in Object)
I have an API and I want to print data from API into my HTML given in the script. in API I have Lopped array. At ${user.TestUrlTable} browser only shows [Object Object], but I want to get values in TestUrlTable Object, which has some other values like TestUrl, Result, and others.
Javascript code is working for main Objects like: IpAdd, PortNo, country, availability, LasteDateFound
But the Issue is to print vales of object "TestUrlTable" like: TestUrl, Result, LastTested.
These values Should be printed for a given IpAdd.
API Data:
[{
"IpAdd": "1.10.227.44",
"PortNo": "8080",
"country": "Thailand",
"availability": "Available",
"LasteDateFound": "6/21/2020",
"TestUrlTable": [{
"id": 937,
"TestUrl": "http://www.google.com",
"Result": "Working",
"LastTested": "2020-06-21T01:04:37.143"
},
{
"id": 938,
"TestUrl": "https://www.microsoft.com",
"Result": "Working",
"LastTested": "2020-06-21T01:05:19.14"
},
{
"id": 939,
"TestUrl": "https://www.w3schools.com",
"Result": "Working",
"LastTested": "2020-06-21T01:05:48.413"
}
]
},
{
"IpAdd": "102.164.248.113",
"PortNo": "8080",
"country": "Equatorial Guinea",
"availability": "Available",
"LasteDateFound": "6/21/2020",
"TestUrlTable": [{
"id": 940,
"TestUrl": "http://www.google.com",
"Result": "Working",
"LastTested": "2020-06-21T01:05:49.693"
}]
},
{
"IpAdd": "103.122.74.146",
"PortNo": "8080",
"country": "Bangladesh - Dhaka",
"availability": "Available",
"LasteDateFound": "6/21/2020",
"TestUrlTable": []
}, {
"IpAdd": "103.151.47.213",
"PortNo": "8080",
"country": "China",
"availability": "Available",
"LasteDateFound": "6/21/2020",
"TestUrlTable": []
}
]
Javascript Code
<script>
let users = [];
const api_url = "http://someapi.com/api";
async function getData() {
const response = await fetch(api_url);
const data = await response.json();
console.log(data);
for (user of data) {
users.push(
`<div class="col-md-3 col-sm-10 col-xs-10">
<div class="pricing-table">
<div class="pricing-header">
<p><h3 style="color:white">${user.IpAdd}<h3></p>
</div>
<div class="pricing-list">
<ul>
<li><i class="fa fa-calendar"></i><span>${user.LasteDateFound}</span></li>
<li><i class="fa fa-search"></i><span>${user.availability}</span></li>
<li><i class="fa fa-lock"></i><span>${user.PortNo}</span></li>
<li><i class="fa fa-mail"></i><span>${user.TestUrlTable}</span></li>
</ul>
</div>
</div>
</div>`
);
}
document.getElementById("results").innerHTML = users.join("");
}
getData();
</script>
HTML File
<body>
<section id="pricing-table">
<div class="container">
<div class="row">
<div id = "AdjResultsDiv">
<div class="pricing" id="results">
</div>
</div>
</div>
</div>
</section>
<!-- Table Section End -->
</body>
A:
you can use JSON.stringify() to convert object to string, check below example.
<li><i class="fa fa-mail"></i><span>${JSON.stringify(user.TestUrlTable)}</span></li>
or you can loop through the TestUrlTable to create the list dynamically, check below example.
for (user of data) {
let temp = ``;
if(user.IpAdd === "1.10.227.44"){
for(item of user.TestUrlTable){
temp += `<li><i class="fa fa-mail"></i><span>${item.TestUrl}</span></li>`;
}
}
users.push(
`<div class="col-md-3 col-sm-10 col-xs-10">
<div class="pricing-table">
<div class="pricing-header">
<p><h3 style="color:white">${user.IpAdd}<h3></p>
</div>
<div class="pricing-list">
<ul>
<li><i class="fa fa-calendar"></i><span>${user.LasteDateFound}</span></li>
<li><i class="fa fa-search"></i><span>${user.availability}</span></li>
<li><i class="fa fa-lock"></i><span>${user.PortNo}</span></li>
${temp}
</ul>
</div>
</div>
</div>`
);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Configuring mouse buttons to switch between apps?
I just installed 14.04, so I'm using the default setup (Unity, I guess).
I have these two extra mouse buttons on the side of my mouse. Is there any way to map these so they can switch between open apps?
What would be perfect is if clicking on button 6 (or whatever it is) would cycle forward through apps, button 7 would go backwards, and holding one of the buttons would show the task list and let you click on the app you want. That's really what I want.
A:
This is copied off of this answer, with a few changes for clarification. Please vote up that answer, not my one.
By installing a couple packages you can configure this pretty easily without too much trouble at all. No matter what version of Linux I'm using i am always sure to install two specific applications when it comes to mouse and keyboard emulation.
These being:
xautomation is a set of command line programs to control X and do "visual scraping" to find things on the screen. There are six different programs to this application but the one we are gonna be concerning ourself with is xte. This program allows us to send arbitrary mouse and keyboard events to the kernel by utilizing the "XTest" extension.
sudo apt-get install xautomation
xbindkeys is a program that enables us to bind commands to certain keys or key combinations on the keyboard and is window manager independent, so whether you are in Gnome, Unity, KDE, etc... it makes no difference.
sudo apt-get install xbindkeys
**By using these two programs together we can make the keyboard and mouse do just about anything we want them to.*
You say you want to use the thumb button in your case for instance, well first we need to find what "mouse button number" X Server is recognizing when you click it. We will use a useful tool called xev to run this program do the following:
Open up a terminal window and type the following command at the prompt
xev
Xev creates a window and then asks the X server to send it events whenever anything happens to the window (such as it being moved, resized, typed in, clicked in, etc.). You can also attach it to an existing window. It is useful for seeing what causes events to occur and to display the information that they contain; it is essentially a debugging and development tool, and should not be needed in normal usage.
Hover your mouse over the event window that opened on your screen and click your thumb button. You will see alot of things happening in your terminal window but the one thing that we are concerned with is the "button number" of the one you just clicked. This can be found at the bottom of your terminal window and should look something similar to the following line:
state 0x10, button 1, same_screen YES
The button part is what were interested in. Being yours is a thumb button its probably gonna say button 8 or button 9 but it could be any number. Remember or write down that number for we will use it later. You can now close xev we no longer need this program.
Now to get things working!!
Assuming you have installed the xautomation and xbindkeys applications as stated above, we will go ahead and do the following:
Open up your favorite text editor and create a new file inside your home directory called .xbindkeysrc this is the configuration file that xbindkeys is going to use to make your mouse or keyboard do the special things we'd like it to do.
Type the following inside the file:
"xdotool key alt+Tab"
b:X + Release
Note: **Be sure to replace X with whatever number you wrote down for your thumb button from when we ran xev earlier*.
Note: **There should also be no spaces between the first line and the second line. If you have a space you will get an error when you run xbindkeys.*
Whats were telling xbindkeys to do here is to take the action of clicking and releasing your thumb button and make it do the action of double clicking your left mouse button which is represented but 'mouseclick 1' 'mouseclick 1'
Save the file and we should be good to go.
Ok lets test it out!!
Open a terminal window and type the following so we can test the functionality:
xbindkeys -n -v
This will run the xbindkeys program in debug mode so that we can see whats happening when you click on your button. It will tell you that its reading the .xbindkeysrc file that we created and using it for its configuration. If all goes well then you should end up with a line saying Starting Loop
Now if you click on your thumb button on your mouse then you should see some things happening in your terminal, meaning that it's recognizing the button press. You should now be getting the same functionality as you would by double-clicking with the left button of your mouse.
You should be able to test this out by using the thumb button and clicking on the menu bar of the terminal, which should maximize or minimize it, thus doing the same thing as a double click would do with the left mouse button.
Now and exit the program.
Note: In order for this all to work all the time, we need to have xbindkeys running in the background at all times. If you just add a new command xbindkeys without the -n -v in your startup applications then it will start every time you log in to your window manager.
I've tried to explain in the best detail on how to go about doing this, hopefully you have been able to understand and complete this action with success. :)
| {
"pile_set_name": "StackExchange"
} |
Q:
Can C++ disambiguate the type of an exception object?
With empty exception objects such as,
class E1
{
};
class E2
{
};
Can C++('s compiler or the resulting executable) safely disambiguate between such exception objects in a catch statement? If so, does it mean that a type code for each exception object should be stored and tracked internally?
A:
Yes, the C++ runtime will choose the appropriate catch block based on the type of the exception thrown. You can use multiple catch blocks to handle different types of exceptions
try
{
throw E2();
}
catch (E1)
{
std::cout << "Caught E1";
}
catch (E2)
{
std::cout << "Caught E2";
}
// Output: "Caught E2"
| {
"pile_set_name": "StackExchange"
} |
Q:
Knowledge representation in Prolog - how to store data?
as I got critic concerning my data structure in Prolog I asked here the experts for alternative solutions.
As example, I have a data set of recipe decription in XML
<recipeml fileversion="13.8.2014">
<recipe>
<head>
<title>Green Soup</title>
</head>
<ing-div type="titled">
<title>soup</title>
<ingredients>
<ing>
<amt><qty>500</qty><unit>gramm</unit></amt>
<item>pea</item>
</ing>
<ing>
<amt><qty>200</qty><unit>ml</unit></amt>
<item>cream</item>
</ing>
...
</ingredients>
</ing-div>
<directions>
<step>Do something, cooking ....</step>
<step>Next do again something...</step>
...
</directions>
</recipe>
<recipe>
...
</recipe>
...
</recipeml>
I choose to store it in Prolog as iterative element-tree using lists:
database([element('recipeml',[version=0.5],
[element('recipe',[],
[element('head',[],
[element('title',[],['Green Soup']
)]
),
element('ing-div',[type=titled],
[element('title',[],['soup']),
element('ingredients',[],
[element(ing,[],
[ element(amt,[],
[ element(qty,[],['500']), element(unit,[],[gramm]),]),
element(item,[],['pea'])
]),
element(ing,[],
[ element(amt,[],
[ element(qty,[],['200']), element(unit,[],[ml]),]),
element(item,[],['pea'])
])
]
)]
)]
),
element('recipe',[],...
)]
)]).
What I want to do is to look easily for recipes based on user input.
The user might give an ingredient or part of the recipe name as input.
Actually I ran throught the elements by
ask_element(Name, Child, Parent) :-
(
member( element(Name,_,Child),Parent)
;
member( element(_,_,NewParent),Parent),
[_|_] = NewParent,
ask_element(Name, Child, NewParent)
).
I got all recipes with a special ingredient by
findall(RTitle,
(
ask_element('recipe',RKnot,Knot),
ask_element('item',TmpIng,RKnot),
contains(TmpIng,Ingredient),
[Ing|_] = TmpIng, % avoid brackets [Egg]
define_xml_knot(['head','title'],_,RKnot,TmpRTitle),
[RTitle|_] = TmpRTitle % avoid brackets [Soup]
,Bag),
My result is then a list of the recipes titles. If a list of ingredients is entered I need
a second analysing step to get the recipe with the most matching ingredients. Maybe this is
not really Prolog style?
One idea, following the remark by Paulo Moura (thanks), is to arrange the data as
recipe(IDnumber,'Green Soup',ingredients(item(500,gramm,'pea'),item(200,ml,'cream')),steps('Do something','Next step do again something')).
I am not sure if this would be really help. Looking for a recipe with a certain ingredient I have to look again step by step in each recipe through every item if the ingredient I am looking for (or part of the word) is contained. And if I want to add a new descriptor, e.g. "level(easy)" I have to change all data calls as the number of element in recipe() changes. With the element(element...) construction I do not have to change the calls.
But the response would be better, by returning only the IDnumber, then I get the whole recipe in one "call" (recipe(123,X,Y,Z)) for further processing. Actually I
return as response "string text in a list" as you see it in "Bag" above...
It is my first application in Prolog, so I am not very familiar with an adquate data storing. I would be grateful for every hint.
A:
If you want to access from Prolog information represented in XML files, Carlo's solution is a good one.
But let's assume that you want all recipes represented in Prolog. One solution, as you described, is to use one fact per recipe, with a structure that best fits the most common data access patterns in your application. As you also noticed, looking for e.g. recipes using a specific ingredient or requiring a specific test will not be efficient as you must go from recipe fact to list of ingredients (or steps) and then do a linear search on that list (you could use a binary search tree instead of a list but I doubt the likely low number of items would justify it computationally). Moreover, adding new descriptors like level/1 in your question requires changes to be potentially propagated to all code that accesses the recipe data. Taking this issues into account, it might be worth to look into use a module or an object representation for the recipes. The idea would be that each recipe would be represented by a module or object with one predicate per attribute. with this representation, the computational cost of accessing an ingredient would be the same as the cost of accessing the recipe name or one of its steps. When e.g. searching for recipes with a specific ingredient, the necessary step of enumerating all recipe modules or objects is a cheap operation. Adding a new descriptor is easy with an object representation and can also be hacked with a module representation (essentially, you would simply modify the recipe interface, possibly adding a default value for the new descriptor). It's also possible to have a mixed representation and there are cases where such a solution is justified. It would be easier to advice if you share more details on the access or reasoning that you to apply to your recipes database.
Update: An example, based on the Logtalk object-oriented extension to Prolog (which you can use with most Prolog implementations, including GNU Prolog and SWI-Prolog). Several variations are possible. For hacking the concept of interface/protocol using instead modules see e.g. this post.
:- protocol(recipep).
:- public([
name/1, ingredient/3, step/1 % descriptors
]).
:- end_protocol.
:- object(proto_recipe, implements(recipep)).
:- public([
ingredient/1, ingredients/1, steps/1 % utility predicates
]).
ingredient(Ingredient) :-
::ingredient(Ingredient,_,_).
ingredients(Ingredients) :-
findall(Ingredient, ::ingredient(Ingredient,_,_), Ingredients).
steps(Steps) :-
findall(Step, ::step(Step), Steps).
:- end_object.
:- object(green_soup, extends(proto_recipe)).
name('Green Soup').
ingredient(pea, 500, gr).
ingredient(cream, 200, ml).
step(...).
...
:- end_object.
:- object(mashed_peas, extends(proto_recipe)).
name('Mashed Peas').
ingredient(pea, 700, gr).
ingredient(salt, 20, gr).
...
:- end_object.
Sample queries:
?- green_soup::ingredients(Ingredients).
Ingredients = [pea, cream].
?- conforms_to_protocol(Recipe, recipep), Recipe::ingredient(pea).
Recipe = green_soup ;
Recipe = mashed_peas ;
false.
Now assume that later you want to add a level/1 descriptor to all recipes. Just for fun, let's use hot patching:
:- category(add_recipe_level_descriptor, complements(proto_recipe)).
:- public(level/1).
:- dynamic(level/1).
:- end_category.
You can now add your cooking experience. E.g. you always get into trouble while making green soup:
?- green_soup::assertz(level(hard)).
true.
But most recipes are easy, so let's add a default value to all recipes:
:- category(recipe_level_default_value, complements(proto_recipe)).
level(easy).
:- end_category.
Now you can ask:
?- mashed_peas::level(Level).
Level = easy.
I have omitted some details (e.g. setup and compilation/loading steps) but hopefully this gives you an idea of what's possible (but full running example here).
| {
"pile_set_name": "StackExchange"
} |
Q:
How to convert String of array to Integer array
I have a string as "2_5_6". i need to get the numbers in the string As numeric.
Here is what i tried:
indices = apply(strsplit("2_5_6","_" ),2 ,FUN = as.numeric)
But, it complains with:
Error in apply(strsplit("2_5_6", "_"), 2, FUN = as.numeric) :
dim(X) must have a positive length
I don't know what should be my Margin parameter ?
What is the simplest solution for it?
A:
We can use scan to convert to numeric while splitting at _
scan(text = "2_5_6", what = numeric(), sep="_", quiet = TRUE)
#[1] 2 5 6
Or if we are using strsplit, the output is a list of length 1. It can be either unlisted or extracted ([[)
as.integer(unlist(strsplit("2_5_6", "_")))
apply expects the input to have some dimensions and here it doesn't have
| {
"pile_set_name": "StackExchange"
} |
Q:
How to Clear() all elements from Entity Framework ICollection?
I have problems removing all elements from a collection in entity framework using Clear()
Consider the often used example with Blogs and Posts.
public class Blog
{
public int Id {get; set;}
public string Name {get; set;}
public virtual ICollection<Post> Posts { get; set; }
}
public class Post
{
public int Id { get; set; }
// foreign key to Blog:
public int BlogId { get; set; }
public virtual Blog Blog { get; set; }
public string Title { get; set; }
public string Text { get; set; }
}
public class BlogContext : DbContext
{
public DbSet<Blog> Blogs {get; set;}
public DbSet<Post> Posts {get; set;}
}
A Blog has many Posts. A Blog has an ICollection of Posts. There is a straightforward one-to-many relation between Blogs and Posts.
Suppose I want to remove all Posts from a Blog
Of course I could do the following:
Blog myBlog = ...
var postsToRemove = dbContext.Posts.Where(post => post.BlogId == myBlog.Id);
dbContext.RemoveRange(postsToRemove);
dbContext.SaveChanges();
However, the following seems easier:
Blog myBlog = ...
myBlog.Posts.Clear();
dbContext.SaveChanges();
However this leads to an InvalidOperationException:
The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
What is the proper way to clear the collection? Is there a fluent API statement for this?
A:
There is a difference between your two code samples.
Your first code sample dbContext.RemoveRange(postsToRemove) removes the Post records. Therefor, any relationship involving these records are also removed.
In your second code sample myBlog.Posts.Clear() you are removing the relationship between myBlog and its corresponding Post records. The 'real' underlying action is to set the value of BlogId of the Post records to null. Unfortunately this is not possible, since BlogId is set to not-nullable. So, in short, the relationship is removed, and no records are actually deleted.
A:
Clear works on the relationship and not on deleting the entity.
There is a working (I think more readable) half way solution between the two solutions you wrote.
dbContext.Posts.RemoveRange(myBlog.Posts);
// Now (also before SaveChanges) the myBlog.Posts is empty
dbContext.SaveChanges();
EDIT
RemoveRange also removes Posts from the Blog.Posts collection
| {
"pile_set_name": "StackExchange"
} |
Q:
.NET Code First is adding user login as default table schema
I am having a strange behavior when I apply a migration to my online db with Entity Framework Core. All of the tables take by default the UserId defined in my connectionstring as the default schema. I know how to change it but I'd like to understand the reason why this is happening. Notice that it does not happen with a local database, the schema remains as "dbo".
A:
You can set the default schema for the User using:
ALTER USER myUser WITH DEFAULT_SCHEMA [myschema]
So you can set your user to have the default schema of dbo, if you wish.
I'm guessing dbo is already set as the default schema for the user that you connect with locally.
You can also specify the default schema in Entity Framework Core. See this question: Where is HasDefaultSchema in Entity Framework Core?
Note that it is a good practice to use a different user for applying your migrations than what you use for querying etc.
| {
"pile_set_name": "StackExchange"
} |
Q:
Performance of Java API versus Python with Cypher for Neo4J
I am working with an application that uses a Neo4J graph containing about 10 million nodes. One of the main tasks that I run daily is the batch import of new/updated nodes into the graph, on the order of about 1-2 million. After experimenting with Python scripts in combination with the Cypher query language, I decided to give the embedded graph with Java API a try in order to get better performance results.
What I found is about a 5x improvement using the native Java API. I am using Neo4j 2.1.4, which I believe is the latest. I have read in other posts that the embedded graph is a bit faster, but that this should/could be changing in the near future. I would like to validate my findings with anyone who has observed similar results?
I have included snippets below just to give a general sense of methods used - code has been greatly simplified.
sample from cypher/python:
cnode = self.graph_db.create(node(hash = obj.hash,
name = obj.title,
date_created = str(datetime.datetime.now()),
date_updated = str(datetime.datetime.now())
))
sample from embedded graph using java:
final Node n = Graph.graphDb.createNode();
for (final Label label : labels){
n.addLabel(label);
}
for (Map.Entry<String, Object> entry : properties.entrySet()) {
n.setProperty(entry.getKey(), entry.getValue());
}
Thank you for your insight!
A:
What you're actually doing here is comparing the speeds of two different APIs and merely using two different languages to do that. Therefore, you're not comparing like for like. The Java core API and the REST API used by Python (and other languages) have different idioms, such as explicit vs implicit transactions. Additionally, network latency associated with the REST API will make a great difference, especially if you are using one HTTP call per node created.
So to get a more meaningful performance comparison, make sure you are comparing like for like: use Java via the REST API perhaps or use Cypher for both tests.
Hint 1: you will get better performance in general over REST by batching up a number of requests into a single API call.
Hint 2: the REST API will never be as fast as the core API as the latter is native and the former has many more layers to go through.
| {
"pile_set_name": "StackExchange"
} |
Q:
Assign css to value of *ngFor item
I have ion-item that will display one of the following Alert, Level 1, Level 2, or Level 3 Emergency.
<ion-item text-wrap *ngFor="let item of levelofEmergency">
{{item.level}}
</ion-item>
What I am trying to do is assign css according to the text of the level. i.e Alert is grey, Level 1 is green etc..
<ion-item text-wrap *ngFor="let item of statuslevelEmergency">
<span style="color:red" *ngIf="item.level === 'Alert'">{{item.level}}</span>
</ion-item>
Thanks in advance for any info pointing me in the right direction.
A:
You can define the level colors in an object having an index signature:
levelColors: { [level: string]: string } = {
Alert: "grey",
Level1: "green",
Level2: "blue",
Level3: "orange",
Emergency: "red",
};
and use it like an associative array to set the color attribute with style binding:
<ion-item text-wrap *ngFor="let item of items" [style.color]="levelColors[item.level]">
<span>{{item.level}}</span>
</ion-item>
See this stackblitz for a demo.
The same result can be obtained with a Map object:
levelColors = new Map<string, string>([
["Alert", "grey"],
["Level1", "green"],
["Level2", "blue"],
["Level3", "orange"],
["Emergency", "red"],
]);
using a slightly different syntax in the template:
<ion-item text-wrap *ngFor="let item of items" [style.color]="levelColors.get(item.level)">
<span>{{item.level}}</span>
</ion-item>
See this stackblitz for a demo.
| {
"pile_set_name": "StackExchange"
} |
Q:
activity aggregate relationships only allow security evaluation for non-admin users when a single parent record is evaluated
I am getting the following error when I run a Salesforce SOQL query with a standard account.
Query:
SELECT ( SELECT Id, Subject FROM OpenActivities ORDER BY ActivityDate
ASC , LastModifiedDate DESC LIMIT 500) FROM Account WHERE Id in (
'001b0000009owSN', '001b0000009owNo' )
Results:
MALFORMED_QUERY: Implementation restriction: activity aggregate relationships only allow security evaluation for non-admin users when a single parent record is evaluated
Same query under Admin account works well.
Similar query works well under Standard account:
SELECT ( SELECT Id, Name FROM Contacts ORDER BY Email ASC LIMIT 500)
FROM Account WHERE Id in ( '001b0000009owSN', '001b0000009owNo' )
How can the problematic query be re-written?
Why does that limitation exists?
Thanks,
A:
Do you know if you are using with sharing on the apex classes?
The implication from SOQL Query ActivityHistory Problem is that switching to the System context will bypass the non-admin user restriction.
As a guess, I'd say it is too expensive for Salesforce to evaluate if a non-admin user has access to the referenced ActivityHistory records. Where is an admin doesn't require the same level of access checking.
Failing that, can you split the query into two parts or query ActivityHistory rather than OpenActivities?
Set accountIds = new Set();
accountIds.add('001b0000009owSN');
accountIds.add('001b0000009owNo');
// What fields do you actually want from Account?
List accounts = [Select Id, Name from Account where ID in :accountIds];
List activities = [Select Id, AccountId, Subject
FROM OpenActivities
ORDER BY ActivityDate ASC, LastModifiedDate DESC
WHERE AccountId in :accountIds
LIMIT 500];
See also OpenActivity - Usage:
The following restrictions on users who don’t have “View All Data” permission help prevent performance issues:
In the main clause of the relationship query, you can reference only one record. For example, you can’t filter on all records where the account name starts with ‘A’; instead, you must reference a single account record.
You can’t use WHERE clauses.
You must specify a limit of 499 or fewer on the number of rows returned in the list.
You must sort on ActivityDate in ascending order and LastModifiedDate in descending order; you can display nulls last. For example: ORDER BY ActivityDate ASC NULLS LAST, LastModifiedDate DESC.
| {
"pile_set_name": "StackExchange"
} |
Q:
Regex for allowing no space and no value, A, AR, or Ar in the start
^([A-Z]{0,1}|[A-Za-z]{0,2})(\s{0,5})([A-Za-z]{1,5}|[\d]{1,5})([']{0,1})(\s{1})([A-Z]{1,2})([a-z]{0,2})(\s{1,2})([A-Za-z]{1,5}|[\d]{1,5})
valid case
Mz A Lt 1
Mz B' Lt 4
I was trying the following regular expression where the valid inclusion would be: no value, A, AR, or Ar and no space if nothing present in first
and Apostrophe (') optional, then SPACE required based on if there is any letter present after Apostrophe.(A, AR, or Ar are examples for ref valid for All chars)
Invalid case will be like ARrd A Lt 1 or aa B Lt' 2
Rules
a)1-2 letter; second letter optional Lower Case: Min 0, Max 2
b) SPACE as a conditional requirement based on letter(s) presence before
c) 1-5 number or 1-5 letter any combination: Min 1, Max 5
d) Apostrophe (') optional
e) SPACE required
f) 1-2 letter; second letter optional Lower Case: Min 0, Max 2
g) SPACE as a conditional requirement based on letter(s) presence before
h) 1-5 number; Min 1, Max 5
but my regex allows all lower cases too which i was trying to avoid can anyone help me out
A:
https://regex101.com/r/vho6Tn/24
This works for all the scenarios
| {
"pile_set_name": "StackExchange"
} |
Q:
logical or condition
In grails gsp, instead of
<g:if env="development">
<H1> xyz </H2>
</g:if>
<g:if env="production">
<H1> xyz </H2>
</g:if>
is it possible to write logical or condition in to combine the two conditions
for example
<g:if test="env='production'"||"env='devlopment'">
<H1> xyz </H2>
</g:if>
What's the right way of doing that? Right now I am having errors.
Thanks,
A:
Just for the sake of DRYness:
<%@ page import="grails.util.Environment" %>
<g:if test="${Environment.current in
[Environment.PRODUCTION, Environment.DEVELOPMENT]}">
<h1>xyz</h1>
</g:if>
| {
"pile_set_name": "StackExchange"
} |
Q:
COM IContextMenu::InvokeCommand - matching LPCMINVOKECOMMANDINFO::lpVerb to item
I have created a shell extension for windows with COM, however I seem to fail to properly match the ids of items I add in the overload of IContextMenu::QueryContextMenu with what I receive in the overload of IContextMenu::InvokeCommand. In my code I use InsertMenu and InsertMenuItem (as far as I understood they do the same, but the latter has some more features?). However I'm not sure which arguments passed to InsertMenu/InsertMenuItem correspond to what I must be looking for in LPCMINVOKECOMMANDINFO::lpVerb. I need some way to easily know that when I add items x, y, z to a context menu, I can then know exactly which one of x, y or z has been clicked.
EDIT: It seems that the verb equals the number from top to bottom of the item in the current menu/submenu. However I have two sub-menus each with x amount of items, so they have the same IDs of 1,2,3. How do I set custom IDs or something?
A:
Firstly you should define an enum that holds the command IDs for your menu items, e.g.
enum {
CMDID_FIRST = 0,
CMDID_DOSOMETHING = CMDID_FIRST,
CMDID_DOSOMETHINGELSE,
CMDID_LAST,
};
These ID values need to start from 0.
In your IContextMenu::QueryContextMenu implementation:
when you add your menu items you need to give each of them an ID by setting the MIIM_ID flag in the MENUITEMINFO.fMask field, and setting the MENUITEMINFO.wID value.
give each of your menu items an ID derived from its command ID as defined above, plus the value of idCmdFirst which is passed into QueryContextMenu. E.g. the "Do Something" menu item would have MENUITEMINFO.wID set to idCmdFirst + CMDID_DOSOMETHING, and "Do Something Else" would have MENUITEMINFO.wID set to idCmdFirst + CMDID_DOSOMETHINGELSE.
the return value from QueryContextMenu needs to be MAKE_HRESULT(SEVERITY_SUCCESS, FACILITY_NULL, x) where x is the ID of the highest-numbered item you added plus 1 (alternatively, if all items were sequentially numbered, the total number of items). Basically, you're telling the host which menu item ID values are now in use so that no other context menu extensions add items that clash with yours. In the above example, you'd return MAKE_HRESULT(SEVERITY_SUCCESS, FACILITY_NULL, CMDID_LAST).
In IContextMenu::InvokeCommand:
test if lpVerb (or lpVerbW) is an integer value using the IS_INTRESOURCE macro.
if so, the command ID can be found in the low word. E.g, if the user selected "Do Something Else", you would find that LOWORD(lpVerb) == CMDID_DOSOMETHINGELSE.
| {
"pile_set_name": "StackExchange"
} |
Q:
Stored Procedures error unknown column mySQL
I'm getting this error when I try to run a stored procedure.
mysql> call get_nearby;
ERROR 1054 (42S22): Unknown column 'longRadius' in 'where clause'
Here is the sql to create the stored procedure:
CREATE PROCEDURE get_nearby() BEGIN SET @lat = 10; set @long = 12;
SELECT id,
@long - radius / abs(cos(radians(@lat)) * 69) as longRadius,
(radius/69) as latRadius
FROM area
WHERE longitude between @long + longRadius and @long - longRadius
AND latitude between @lat + latRadius and @long - latRadius;
END
I have no idea why it's not recognising the stated column name. For the moment, I have set @lat, and @long at the start to simplify testing.
Any help would be greatly appreciated.
A:
You cannot use column aliases in the where clause. You could convert that where clause to a "having" clause and then that will let you use the aliases. You can get more info here and here.
From the Mysql docs:
Standard SQL disallows references to column aliases in a WHERE clause.
This restriction is imposed because when the WHERE clause is
evaluated, the column value may not yet have been determined.
You can also either restate the computation in the where clause, or use a subquery.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cant "get" streams from server
I am trying to make a simple Client-Server application but when I execute the code I get an exception that the client cannot get the socket's input stream.Please, take a look to my code and try to help.Thanks:)
P.S:Sorry for the messy code.Execute it as two different applications.
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class SimpleClient //implements Runnable
{
private ObjectOutputStream output; // output stream to server
private ObjectInputStream input; // input stream from server
private String message = ""; // message from server
private String chatServer="localhost"; // host server for this application
private Socket client; // socket to communicate with server
public void runClient()
{
try // connect to server, get streams, process connection
{
connectToServer(); // create a Socket to make connection
getStreams(); // get the input and output streams
processConnection(); // process connection
} // end try
catch(IOException ioe)
{
ioe.printStackTrace();
}
finally
{
// closeConnection(); // close connection
} // end finally
}
private void closeConnection()
{
try
{
output.close(); // close output stream
input.close(); // close input stream
client.close(); // close socket
} // end try
catch ( IOException ioException )
{
ioException.printStackTrace();
} // end catch
} // end method closeConnection
private void connectToServer() throws IOException
{
System.out.println( "Attempting connection\n" );
// create Socket to make connection to server
client = new Socket( InetAddress.getByName( chatServer ), 12345 );
// display connection information
System.out.println( "Connected to: " +
client.getInetAddress().getHostName() );
} // end method connectToServer
private void getStreams() throws IOException
{
// set up output stream for objects
output = new ObjectOutputStream( client.getOutputStream() );
output.flush(); // flush output buffer to send header information
// set up input stream for objects
input = new ObjectInputStream( client.getInputStream() );
System.out.println( "\nGot I/O streams\n" );
} // end method getStreams
private void processConnection() throws IOException
{
do {
try // read message and display it
{
message = ( String ) input.readObject(); // read new message
System.out.println( "\n" + message ); // display message
} // end try
catch ( ClassNotFoundException classNotFoundException )
{
System.out.println( "\nUnknown object type received" );
} // end catch
} while ( !message.equals( "SERVER>>> TERMINATE" ) );
} // end method processConnection
public String toString()
{
return "client connected to "+chatServer;
}
public static void main(String []args)
{
SimpleClient c= new SimpleClient();
c.runClient();
}
}
//-------------servers starts here
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class SimpleServer //implements Runnable
{
private ObjectOutputStream output; // output stream to client
private ObjectInputStream input; // input stream from client
private ServerSocket server; // server socket
private Socket connection; // connection to client
private int counter=1; //counts connections
ArrayList<SimpleClient> list;
/***
* Runs forever and takes care of alla
*/
public void runServer()
{
try // set up server to receive connections; process connections
{
server = new ServerSocket( 12345, 100 ); // create ServerSocket
while ( true )
{
try
{
waitForConnection(); // wait for a connection
getStreams(); // get input & output streams
processConnection(); // process connection
} // end try
catch ( Exception Exception )
{
System.out.println( "\nSomething bad happened" );
} // end catch
finally
{
closeConnection();
counter++; // close connection
} // end finally
}
}
catch ( IOException ioException )
{
System.out.println("An io error occured while creating a server-socket");
ioException.printStackTrace();
} // end catch
} // end method runServer
/***
* Waits for a client's request for connection
*/
public void waitForConnection()
{
try
{
connection = server.accept();
System.out.println("Client with IP and hostname "+connection.getInetAddress().getHostName());
} catch (IOException ex)
{
System.out.println("An error makes connection impossible");
ex.printStackTrace();
}
}
/***
* Makes the interconnection of client's and server's stream's
*/
public void getStreams()
{
try
{
output=(ObjectOutputStream) connection.getOutputStream();
input=(ObjectInputStream) connection.getInputStream();
output.flush();
System.out.println("Got IO Streams, hell yeah ");
}
catch(IOException ioe)
{
System.out.println("Cannot get streams");
ioe.printStackTrace();
}
}
/***
* Terminates connection
*/
public void closeConnection()
{
try
{
output.flush();
output.close();
input.close();
} catch (IOException ex)
{
ex.printStackTrace();
}
}
/***
* Receives messages from client
*/
public void processConnection()
{
String message="Connection successful";
do // process messages sent from client
{
try // read message and display it
{
message = ( String ) input.readObject(); // read new message
System.out.println("CLIENT>>> "+message);
} // end try
catch ( ClassNotFoundException classNotFoundException )
{
System.out.println( "\nUnknown object type received" );
}
catch(IOException ioe)
{
System.out.println("Cannot receive message from clint");
ioe.printStackTrace();
}
} while ( !message.equals( "CLIENT>>> TERMINATE" ) );
}
/***
* Sends data to client
* @param message
*/
public void sendData(String message)
{
try // send object to client
{
output.writeObject( "SERVER>>> " + message );
output.flush(); // flush output to client
System.out.println("SERVER>>> " + message);
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
public String toString()
{
return "this is a simple server with a total of "+counter+" connections";
}
public static void main(String []args)
{
SimpleServer c= new SimpleServer();
c.runServer();
}
}
A:
Your server is just casting the objects returned by Socket.getOutputStream() and Socket.getInputStream() to object streams. Instead, it must construct the object streams in the same way that your client does by using "new ObjectInputStream()" and "new ObjectOutputStream()". Remember to flush the server's ObjectOutputStream.
| {
"pile_set_name": "StackExchange"
} |
Q:
Fetching relation to PFObject cloud code
I have a PFUser that has a days relation to a Day PFObject.
In my database it looks like this:
{
"_id": "WjLAnMuRmp",
"name": "c",
"_created_at": {
"$date": "2016-08-04T15:28:51.759Z"
},
"_updated_at": {
"$date": "2016-08-24T19:44:44.774Z"
},
"days": [
{
"__type": "Pointer",
"className": "Day",
"objectId": "BrQwmKAbJC"
},
{
"__type": "Pointer",
"className": "Day",
"objectId": "6wuDMl4kKI"
}
]
}
Pretty straight forward. In my cloud code, I'm trying to send up a PFUser objectId, then fetch all the days they have and iterate over them. For some strange reason I keep getting 0 returned when I do a relation query.
Here is what I'm working with:
Parse.Cloud.define("getDayAveragesForUser", function(request, response) {
console.log("-getDayAveragesForUser");
// Create the query on the User class
var fetchedUser = new Parse.User({id:request.params.userObjectId});
console.log("the fetched user: " + fetchedUser.id);
var relation = fetchedUser.relation("days");
var query = relation.query();
query.limit(365);
query.ascending("createdAt");
query.find({
success: function(results) {
console.log("Successfully retrieved " + results.length + " Days.");
},
error: function(error) {
console.log("Error: " + error.code + " " + error.message);
}
});
});
When I print the fetchedUser.id it's correct so I know I'm on the right user. This seems based on the documentation example:
var relation = user.relation("likes");
relation.query().find({
success: function(list) {
// list contains the posts that the current user likes.
}
});
This should be working fine.
===
I just add this to my Cloud Code to test:
var days = fetchedUser.get("days");
console.log("type of: " + typeof days);
which from this I get:
type of: undefined
A:
The reason is that your days are not saved as relations but as a pointers. And in parse relations and pointers are handled in different ways.
In order to fetch the days pointer you need to change your query to look like the following:
var userQuery = new Parse.Query(Parse.User);
userQuery.include("days"); // include the days pointer in the results
userQuery.get(request.params.userObjectId, {
success: function(user) {
// This function will *not* be called.
console.log(user.get("days")); // print the days to console
},
error: function(error) {
}
});
| {
"pile_set_name": "StackExchange"
} |
Q:
YouTube - Link Asset ID to Video ID
Is it possible to get an asset's video ID from the asset ID in YouTube?
I am writing a Javascript application that will allow a user to input the asset ID (Content ID API) and retrieve that asset's views, gross revenue, monetized views (YT Analytics API).
Is there any way to link the two? If I could return the video ID from the Asset ID then I would be set but I can't see where I can get that in the documentation.
A:
Claim is where videoId, assetId, and contentManagerId all linked.
You can do a claimSearch->list with assetId and get videoId in response.
Note that this will only list "your own or your managed channel's" claims. You can not search other people's claims.
| {
"pile_set_name": "StackExchange"
} |
Q:
oledb import csv file - weird characters:˥«¿ added
when I import csv file using Oledb , weird characters:˥«¿
are added to the first column
code:
string strConnectionString = string.Format("Provider=Microsoft.jet.OLEDB.4.0;Data
OleDbConnection SQLConn = new OleDbConnection(strConnectionString);
Source={0};Extended Properties='text;HDR=Yes;FMT=Delimited(,)';", strFile);
OleDbCommand selectCMD = new OleDbCommand("select * FROM ["+strFileName+"]")
selectCMD.Connection = SQLConn;
SQLAdapter.SelectCommand = selectCMD;
SQLAdapter.Fill(dtXLS);
my file start with the word shape without any char before it.
I get in the datatable first column name ˥«¿Shape
why?
Thanks.
A:
This is an encoding issue - what you are seeing is called the byte order mark (good luck Googling for such a character string!)
Find a way of changing the encoding to UTF-8 and I suspect it'll go away.
| {
"pile_set_name": "StackExchange"
} |
Q:
Angular Js - Avoid repetition in ng-repeat
I am developing the system for Hotel POS solution. I want to fetch all the current orders and show the table number of orders only once.
But the table number is repeating for all the orders
I have written following code :
<span ng-repeat='orders in allCurrentOrder' ng-if='orders.custId==ctrl.person" + scope.divId + ".selected.cust_id && orders.orderType=="+scope.orderType+"'>Table No. : {{orders.tableNumber}}</span>
and I want output as :
Table No. : 9
but I am getting
Table No. : 9Table No. : 9Table No. : 9Table No. : 9Table No. : 9Table No. : 9Table No. : 9
how can I solve this problem?
A:
Use track by:
ng-repeat='orders in allCurrentOrder track by orders.tableNumber'
| {
"pile_set_name": "StackExchange"
} |
Q:
Proof that the $d$-th powers generate the $d$-th symmetric power of a vector space
Let $V$ be a $\mathbb{C}$-vector space of finite dimension. Denote its $d$-th symmetric power by $V^{\odot d}$. I am looking for a proof that $V^{\odot d}$ is generated by the elements $v^{\odot d}$ for $v\in V$.
A different way to look at it is the following: Consider the polynomial ring $R=\mathbb{C}[x_1,\ldots,x_n]$ and $f$ a homogeneous polynomial of degree $d$: Then, I want to show that there are linear polynomials $h_1,\ldots,h_k$ such that $f$ is a linear combination of the $d$-th powers $h_i^d$.
In the case $d=2$, this follows from $2xy = (x+y)^2 - x^2 - y^2$. For higher $d$, I recall seeing a proof involving multinomial coefficients once, but I do not remember the details. I have tried to work it out again, but it seems a bit cumbersome, so I am asking whether you know any textbook where this result is proved. If you know an easy proof, I'd be very happy if you could outline it, though.
A:
In my answer here I note that symmetric tensors, as multilinear functionals, descend to linear maps on the symmetric power of the underlying vector space. I then reason that if we could show that $\mathrm{Sym}^n V$ is generated by $n$th powers of elements from $V$ the question on tensors would then be answered in its general form decisively. I remark that this is formally equivalent to the elementary symmetric polynomials $e_n$ being expressible as sums of $n$th powers of homogeneous polynomials.
This was the subject of my question here, which received a correct answer (containing a proof of the claim) from user m_l. It was very combinatorial and indeed involved multinomial coefficients, though I'm not sure how related it is to what you've seen before. (Unfortunately, at this point in time I am the only person to have upvoted poor m_l.) It requires the characteristic of the base field be greater than the power $n$ in question (or zero, of course).
| {
"pile_set_name": "StackExchange"
} |
Q:
When plotting a 3D Graphic, how to define the angle it will show?
I know I can after the plot is done, to rotate it with my mouse to the desired angle. Now, I'd like to know how to do the same through code.
A:
On second look your title involves 3d rotation. For that you can use ViewPoint. The example under the applications tab seems to be what you are looking for.
You can use the ImageRotate function.
ImageRotate@Plot[x, {x, 0, 10}] (*rotate 90 degrees counterclockwise*)
ImageRotate[Plot[x, {x, 0, 10}], phi] (*rotate phi degrees counterclockwise*)
| {
"pile_set_name": "StackExchange"
} |
Q:
Is WordPress appropriate for building customized Web Apps
Our company is aiming to build an eLearning Website, we are a team of developers and our boss is suggesting using WordPress for it. We are experienced in building web apps using Codeigniter and Laravel.
I already know that we can build any type of web app using WordPress, but my questions is that is it appropriate using WordPress for building it, in terms of ease in teamwork, time, customization, easiness or anything else which you may suggest compared to usign Codeigniter or Laravel?
A:
Yes definitely Wordpress would be a great platform to work in. Since it has extended its wings from a normal CMS to ecommerce, social networking and much more to come.
And about developing the eLearning site yes it would be definitely magnificent to develop it in wordpress as there could be some plugins for it or else you can develop one with ease.
Benefits of Working in Wordpress:
Large number of community members around to help you.
Your website will be most search engine friendly with it.
Really takes less time to develop any application because most of things are in built and you can also modify them to match your requirements.
Installation and migration is effortless.
| {
"pile_set_name": "StackExchange"
} |
Q:
Store and display HTML string while avoiding JS, in ASP.Net Core 2
I wish to store a formatted text using a Rich-Text editor (QuillJS) and while displaying back it should be rendered as HTML. By default the views encode the HTML to avoid JS Injection, and so the data is being treated as a plain string.
How do i manage to store and display / render the data as HTML, while at the same time filtering any JS in the string ?
I tried searching for api's but couldn't find any help. Secondly, these days it's getting increasing difficult getting to the documentation with just class name, hence full class name is highly appreciated in the answers.
A:
Assuming your model contains a public string MyHtml { get; set; } property, then to display the results in a view, use
@Html.Raw(Model.MyHtml)
To identify if the posted value contains any <script> tags and/or to remove them from the value, use a html parser such as Html Agility Pack. For example in your POST method, you could add a ModelStateError and return the view
public ActionResult Save(MyModel model)
{
if (HasScripts(model.MyHtml)
{
ModelState.AddModelError("MyHtml", "The html cannot contain script tags");
}
if (!ModelState.IsValid)
{
return View(model);
}
// save and redirect
}
Where HasScripts() is
public bool HasScripts(string html)
{
HtmlDocument document = new HtmlDocument();
document.LoadHtml(html);
HtmlNode root = document.DocumentNode;
return root.Descendants("script").Any();
}
Alternatively, if you want to just remove them before saving, you could use the following method
public string RemoveScripts(string html)
{
HtmlDocument document = new HtmlDocument();
document.LoadHtml(html);
HtmlNode root = document.DocumentNode;
IEnumerable<HtmlNode> scripts = root.Descendants("script");
for(int i = 0; i < scripts.Count(); i++)
{
HtmlNode script = scripts[i];
script.Remove();
}
return scripts.Any() ? document.ToString() : html;
}
and use it as
model.MyHtml = RemoveScripts(model.MyHtml);
Note: If you are tempted to use a regex for this, I recommend reading Regular Expression for Extracting Script Tags.
You might also want to consider checking for other potentially malicious elements such as <embed>, <iframe>, <form> etc
| {
"pile_set_name": "StackExchange"
} |
Q:
vagrant reload --provision is wrong says running composer as "root",how can I do?
I used vagrant reload --provision, it says:
==> homestead-7: Attempting graceful shutdown of VM...
==> homestead-7: Checking if box 'laravel/homestead' is up to date...
==> homestead-7: Clearing any previously set forwarded ports...
==> homestead-7: Fixed port collision for 80 => 8000. Now on port 2200.
==> homestead-7: Clearing any previously set network interfaces...
==> homestead-7: Preparing network interfaces based on configuration...
homestead-7: Adapter 1: nat
homestead-7: Adapter 2: hostonly
==> homestead-7: Forwarding ports...
homestead-7: 80 (guest) => 2200 (host) (adapter 1)
homestead-7: 443 (guest) => 44300 (host) (adapter 1)
homestead-7: 3306 (guest) => 33060 (host) (adapter 1)
homestead-7: 4040 (guest) => 4040 (host) (adapter 1)
homestead-7: 5432 (guest) => 54320 (host) (adapter 1)
homestead-7: 8025 (guest) => 8025 (host) (adapter 1)
homestead-7: 27017 (guest) => 27017 (host) (adapter 1)
homestead-7: 22 (guest) => 2222 (host) (adapter 1)
==> homestead-7: Running 'pre-boot' VM customizations...
==> homestead-7: Booting VM...
==> homestead-7: Waiting for machine to boot. This may take a few minutes...
homestead-7: SSH address: 127.0.0.1:2222
homestead-7: SSH username: vagrant
homestead-7: SSH auth method: private key
homestead-7: Warning: Connection reset. Retrying...
homestead-7: Warning: Remote connection disconnect. Retrying...
homestead-7: Warning: Connection reset. Retrying...
homestead-7: Warning: Remote connection disconnect. Retrying...
homestead-7: Warning: Connection reset. Retrying...
homestead-7: Warning: Remote connection disconnect. Retrying...
==> homestead-7: Machine booted and ready!
==> homestead-7: Checking for guest additions in VM...
homestead-7: The guest additions on this VM do not match the installed version of
homestead-7: VirtualBox! In most cases this is fine, but in rare cases it can
homestead-7: prevent things such as shared folders from working properly. If you see
homestead-7: shared folder errors, please make sure the guest additions within the
homestead-7: virtual machine match the version of VirtualBox you have installed on
homestead-7: your host and reload your VM.
homestead-7:
homestead-7: Guest Additions Version: 5.0.18_Ubuntu r106667
homestead-7: VirtualBox Version: 5.2
==> homestead-7: Setting hostname...
==> homestead-7: Configuring and enabling network interfaces...
==> homestead-7: Mounting shared folders...
homestead-7: /vagrant => /Users/imchess/Homestead
homestead-7: /home/vagrant/code => /www/Code/php
==> homestead-7: Running provisioner: file...
==> homestead-7: Running provisioner: shell...
homestead-7: Running: inline script
==> homestead-7: Running provisioner: shell...
homestead-7: Running: inline script
==> homestead-7: Running provisioner: shell...
homestead-7: Running: inline script
==> homestead-7: Running provisioner: shell...
homestead-7: Running: /var/folders/hq/czdzwx2n1c3_mzsf4vfwm8gm0000gn/T/vagrant-shell20180202-16576-1j9ra42.sh
==> homestead-7: Running provisioner: shell...
homestead-7: Running: script: Creating Certificate: mwboom.local
==> homestead-7: Running provisioner: shell...
homestead-7: Running: script: Creating Site: mwboom.local
==> homestead-7: Running provisioner: shell...
homestead-7: Running: inline script
==> homestead-7: Running provisioner: shell...
homestead-7: Running: script: Checking for old Schedule
==> homestead-7: Running provisioner: shell...
homestead-7: Running: script: Creating Certificate: slboom.local
==> homestead-7: Running provisioner: shell...
homestead-7: Running: script: Creating Site: slboom.local
==> homestead-7: Running provisioner: shell...
homestead-7: Running: inline script
==> homestead-7: Running provisioner: shell...
homestead-7: Running: script: Checking for old Schedule
==> homestead-7: Running provisioner: shell...
homestead-7: Running: script: Clear Variables
==> homestead-7: Running provisioner: shell...
homestead-7: Running: script: Restarting Cron
==> homestead-7: Running provisioner: shell...
homestead-7: Running: script: Restarting Nginx
==> homestead-7: Running provisioner: shell...
homestead-7: Running: script: Creating MySQL Database: homestead
==> homestead-7: Running provisioner: shell...
homestead-7: Running: script: Creating Postgres Database: homestead
==> homestead-7: Running provisioner: shell...
homestead-7: Running: script: Update Composer
homestead-7: You are running composer as "root", while "/home/vagrant/.composer" is owned by "vagrant"
homestead-7: You are already using composer version 1.6.3 (stable channel).
==> homestead-7: Running provisioner: shell...
homestead-7: Running: /var/folders/hq/czdzwx2n1c3_mzsf4vfwm8gm0000gn/T/vagrant-shell20180202-16576-17qinoh.sh
==> homestead-7: Running provisioner: shell...
homestead-7: Running: /var/folders/hq/czdzwx2n1c3_mzsf4vfwm8gm0000gn/T/vagrant-shell20180202-16576-i3q6nl.sh
In this report,
homestead-7: You are running composer as "root", while "/home/vagrant/.composer" is owned by "vagrant"
homestead-7: You are already using composer version 1.6.3 (stable channel).
is red, like an error message.
This is the picture:
So how can I fix this error message?
A:
I'm a real newbie at this, but here is what I found.
First, this article explains the root issue (forgive the pun):
https://snipe.net/2017/11/15/so-you-ran-composer-as-root/
To fix the issue, I went to Terminal, to my user's top-level folder and ran "rm .composer" to remove the .composer folder that I had previously installed.
After that, I ran "vagrant halt" and "vagrant up" and the error message was gone, and my site ran properly.
| {
"pile_set_name": "StackExchange"
} |
Q:
data appear and disapear when jquery loads
i have this code bellow and i have select options with $menucompare values .
<script>
function displayVals() {
var singleValues = $("#menucompare").val();
$("#hiddenselect").attr("value", singleValues );
$("p").html("Procent of: " + singleValues);
}
$("select").change(displayVals);
displayVals();
</script>
<table width='100%' border='1' cellspacing='0' cellpadding='0'>
<th>weeks</th>
<th style="text-align: left; padding-left:5%;"><?php echo "<p></p>"; ?></th>
which i can get this value (Procent of: $menucompare) . but the problem is when i select one option , the value appears right when jquery is loading , and when jquery is finished loading it disapears this (Procent of: $menucompare) , of course the variable $menucompare commes with the right value.
so i want even when jquery finished loading this value stays in the table . hope can get some fix for this .
A:
Try the following script instead:
<script type="text/javascript">
$(document).ready(function(){
$("select").change(function() {
displayVals();
});
displayVals();
});
function displayVals() {
var singleValues = $("#menucompare").val();
$("#hiddenselect").val(singleValues);
$("p").html("Procent of: " + singleValues);
}
</script>
| {
"pile_set_name": "StackExchange"
} |
Q:
Как посчитать частоту появления триграммы в тексте?
Добрый день. Правильно ли я понимаю, что для подсчёта частоты появления триграммы в тексте, нужно, во-первых, знать, сколько раз данная триграмма встречалась в тексте, во-вторых, сколько всего различных триграмм в тексте, но я не понял, как именно нужно считать триграммы, как повторяющиеся, так и их общее количество. На картинке представлено два способа, и какой из них правильный?
A:
Второй способ (с наложением) "более верный". Вот, например, цитата из английской Wiki:
"the quick red" has the following character-level trigrams
(where an underscore "_" marks a space):
the
he_
e_q
_qu
qui
uic
ick
ck_
k_r
_re
red
Вот выдержка из Postgres доков:
При выделении триграмм, содержащихся в строке, считается, что перед каждым
словом находятся два пробела, а после — один пробел. Например, из строки
"cat" выделяется набор триграмм: " c", " ca", "cat" и "at ". Из строки
"foo|bar" выделяются триграммы: " f", " fo", "foo", "oo ", " b", " ba",
"bar" и "ar ".
Правда, иногда используют и первый вариант, если имплементатору кажется, что это проще, и не приводит к существенному искажению частот n-грамм. Пруф
| {
"pile_set_name": "StackExchange"
} |
Q:
Move Form if second monitor screen exists
Looking for a way to load a from if a second screen exists.
I have tried this code with a load event:
Dim numofMon As Integer = Screen.AllScreens.Length
If numofMon > 1 Then
Me.Bounds = Screen.AllScreens(1).Bounds
End If
Side note: If someone could point me to how to detect when the cursor is no longer on the form, I would appreciate it.
A:
This ended up working for me.
Dim obj as New Form2
obj.Location = Screen.AllScreens(UBound(Screen.Allscreens)).Bounds.Location
obj.show()
| {
"pile_set_name": "StackExchange"
} |
Q:
requesting cloudinary resource gives CORS errors
I have a laravel/lumen server managing uploads of my cloudinary resources. I'm also using the server as an API endpoint for my front end app. One of the endpoints returns a file from Cloudinary. I'm doing this by redirecting the request to the Cloudinary resource. However my app is failing because there are no CORS headers on the redirected resource.
return redirect()->to("https://res.cloudinary.com/gates/raw/upload/" . $upload->id);
the error i get is:
Redirect from 'https://{my-server.com}/api/v1/export' to
'https://res.cloudinary.com/gates/raw/upload/{upload-id}' has been
blocked by CORS policy: No 'Access-Control-Allow-Origin' header is
present on the requested resource. Origin 'https://{my-frontend.com}'
is therefore not allowed access.
A:
You can use this library on your server: https://github.com/barryvdh/laravel-cors
return [
/*
|--------------------------------------------------------------------------
| Laravel CORS
|--------------------------------------------------------------------------
|
| allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
| to accept any value.
|
*/
'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedHeaders' => ['Content-Type', 'X-Requested-With'],
'allowedMethods' => ['*'], // ex: ['GET', 'POST', 'PUT', 'DELETE']
'exposedHeaders' => [],
'maxAge' => 0,
]
allowedOrigins => [*] mean that you give access to your server, you can add ip's or dns for restrict access to your server
| {
"pile_set_name": "StackExchange"
} |
Q:
How to declare doubles inside a matrix (2d arrays) in C?
I am learning by myself (started few days ago) and could not find reliable information in portuguese (my home language).
After just too much headache, I gave up and came here for help.
I do not know how to make am array/2d array of doubles, only intergers.
The following code works as expected:
int main(void){
int matriz[5][2] = {{1,2}, // DECLARATION OF MATRIX COMPOSED OF INTERGERS
{3,4},
{5,6},
{7,8},
{9,10}};
int maior = matriz[0][0]; // BIGGEST NUMBER INSIDE MATRIX, STARTED AS FIRST POSITION
int soma = 0; // SUM OF NUMBERS START WITH ZERO
int lin = 0; // INDICATION OF LINE
int col = 0; // INDICATION OF COLUMN
for (lin = 0; lin < 5; lin++){
for (col = 0; col < 2; col++){
if (maior < matriz[lin][col]) {maior = matriz[lin][col];}
soma += matriz[lin][col];
}
}
printf("A soma dos numeros eh %d e o maior numero eh %d\n", soma, maior);
// THE SUM OF NUMBERS IS %D AND THE BIGGEST NUMBER IS %D
// I COPIED THE FOLLOWING CODE FROM ELSEWHERE TO SEE WHAT WAS GOING ON
int i, j;
for ( i = 0; i < 5; i++ ) {
for ( j = 0; j < 2; j++ ) {
printf("a[%d][%d] = %d\n", i,j, matriz[i][j] );
}
}
return 0;}
The output is just as expected:
A soma dos numeros eh 55 e o maior numero eh 10
a[0][0] = 1
a[0][1] = 2
a[1][0] = 3
a[1][1] = 4
a[2][0] = 5
a[2][1] = 6
a[3][0] = 7
a[3][1] = 8
a[4][0] = 9
a[4][1] = 10
**
However any change as the folowing code is always wrong:
**
int main(void){
double matriz2[5][2] = {{10000,1000},
{100,10},
{1,0.1},
{0.01,0.001},
{0.0001,0.00001}};
double maior2 = matriz2[0][0];
double soma2 = 0;
int lin2 = 0;
int col2 = 0;
for (lin2 = 0; lin2 < 5; lin2++){
for (col2 = 0; col2 < 2; col2++){
if (maior2 < matriz2[lin2][col2]) {maior2 = matriz2[lin2][col2];}
soma2 += matriz2[lin2][col2];
}
}
printf("A soma dos numeros eh %d e o maior numero eh %d\n", soma2, maior2);
for ( i = 0; i < 5; i++ ) {
for ( j = 0; j < 2; j++ ) {
printf("a[%d][%d] = %d\n", i,j, matriz2[i][j] );
}
}
return 0;}
The output is always wrong as I keep changing it.
I declared long doubles, doubles, interger and doubles etc. And each time the code outputs wrong answers.
Some combinations output negative numbers. Others just output ZERO everywhere. Two examples:
A soma dos numeros eh 0 e o maior numero eh 0
a[0][0] = 10000
a[0][1] = 1000
a[1][0] = 100
a[1][1] = 10
a[2][0] = 1
a[2][1] = 0
a[3][0] = 0
a[3][1] = 0
a[4][0] = 0
a[4][1] = 0
or
A soma dos numeros eh 953826337 e o maior numero eh 0
a[0][0] = 0
a[0][1] = 0
a[1][0] = 0
a[1][1] = 0
a[2][0] = 0
a[2][1] = -1717986918
a[3][0] = 1202590843
a[3][1] = -755914244
a[4][0] = -350469331
a[4][1] = -1998362383
I simply could not find a way to declare or put double number in a matrix.
How can I do it?
A:
%d format specifier of printf expects an int argument, but you are passing a double. Your program then exhibits undefined behavior. Consult your favorite C or C++ textbook on how to output a value of type double.
A:
You have tagged both C & C++ you should pick one or the other. I'll give answers for both languages.
If using C with printf() when you change your 2D array from int to double the calculations appear to be fine, what is wrong here is your output with printf(). You are using %d which expects an int but you are passing it a double and this leads to undefined behavior. When using float or double change this to %f or %g.
If using C++ try not to use printf(). Instead you should include iostream. Then your output would look something like:
// printf("A soma dos numeros eh %d e o maior numero eh %d\n", soma2, maior2);
std::cout << "A soma dos numerous eh " << soma2 << " e o maior numero eh << maior2 << '\n';
for ( i = 0; i < 5; i++ ) {
for ( j = 0; j < 2; j++ ) {
// printf("a[%d][%d] = %d\n", i,j, matriz2[i][j] );
std::cout << "a[" << i << "][" << j "] = " << matriz2[i][j] << '\n';
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Referer = Category?
I've sucesfully tracked where clicks are from and then made my site show elements based off where that click is from. A code example is this:
$referer = $_SERVER['HTTP_REFERER'];
if ( $referer == "http://www.testdomain.com/testpage" ) {
echo '<div id="bgphotos"></div>';
} else {
echo '<div id="bgvideos"></div>';
}
So this is telling my site to display the bgphotos div if it is clicked from http://www.testdomain.com/testpage. This works awesome. I've even done even more coding to track where certain divs are clicked on within a webpage. But, I would like to show an element if it was clicked on from a category.
Now, I thought the solution would just be to change the $referer to the category webpage. But the problem is, when there are more than one pages of posts for this category, you would have to manually track each category page number... which would take forever.. An example would be:
if ( $referer == "http://www.testdomain.com/category/test/" ) {
//do this }
if ( $referer == "http://www.testdomain.com/category/test/page/2/" ) {
//do this }
if ( $referer == "http://www.testdomain.com/category/test/page/3/" ) {
//do this }
if ( $referer == "http://www.testdomain.com/category/test/page/4/" ) {
//do this }
As you can see this would just get out of hand, I would have to track every single category page possible. So is there any way to say, just track if something is clicked from a category?? Or is there any other solution to this problem?
Any help would be appreciated soo soo soo soo much! :) loll. It really would.
A:
A regex would work.
if( preg_match("(^http://www\.testdomain\.com/category/test/(?:page/\d+/)?$)",$referer)) {
// do this
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How do You Control Column Name Position When Creating CSV Exportable Object Arrays?
REFERENCE SCRIPTS:
Script 1:
$csvList = @()
$csvList += New-Object PSObject -Property @{name="test1";accountname="testuser1";mail="[email protected]"}
$csvList += New-Object PSObject -Property @{name="test2";accountname="testuser2";mail="[email protected]"}
$csvList += New-Object PSObject -Property @{name="test3";accountname="testuser3";mail="[email protected]"}
$csvList += New-Object PSObject -Property @{name="test4";accountname="testuser4";mail="[email protected]"}
$csvList | Export-Csv c:\temp\testcsv.csv -NoTypeInformation
Script 2 (added in edit to reflect extended usage):
$aTest = @()
for($x=0;$x -le 5;$x++)
{
$aTest += New-Object PSObject -Property @{Name="test$($x)"; `
AccountName="testuser$($x)"; `
Mail="user$($x)@somewhere.com"}
}
$aTest | Export-Csv c:\temp\testcsv.csv -NoTypeInformation
QUESTION:
While that script creates my CSV and includes all the data I need in the correct rows, I cannot figure out how to control column position. Even though I'm ordering and adding the data by name,accountname,mail Powershell orders it by mail,name,accountname. How can I control the column order?
Note: If I do a screen dump of the contents of $csvList before the export the order has already been changed.
A:
Each PSObject is essentially a hashtable. There is no ordering of values in a hashtable. Select-Object can reformat the order for you.
Make your last line:
$csvList | Select-Object name,accountname,mail | Export-Csv c:\temp\testcsv2.csv -NoTypeInformation
Got the idea from this forum question: Source
A:
If you're running V4, they added a type accelerator ([PSCustomObject]) for creating PS Objects that uses an ordered hash table so the properties stay in the order they were declared in the hash literal.
$(
[PSCustomObject]@{name="test1";accountname="testuser1";mail="[email protected]"}
[PSCustomObject]@{name="test2";accountname="testuser2";mail="[email protected]"}
[PSCustomObject]@{name="test3";accountname="testuser3";mail="[email protected]"}
[PSCustomObject]@{name="test4";accountname="testuser4";mail="[email protected]"}
) | Export-Csv c:\temp\testcsv.csv -NoTypeInformation
Edit: Example using a loop to build up an ordered hash table:
foreach ($i in 1..4)
{
$ht = [ordered]@{}
$ht.name = "test$i"
$ht.accountname = "testuser$i"
$ht.mail = "[email protected]"
[PSCustomObject] $ht
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Custom module's output is not wrapped in the site theme
I've put together my first Drupal 7 custom module. I've implemented hook_menu() to get it to path correctly, but I cannot seem to get the output wrapped in the page tpl.
I can visit domain.com/mycustommodule to see the output, but it's just the photos and links that the custom module built, not the site wrapper. How do I get this output into the node area of the page?
Here's my hook_menu if that helps.
function mymodule_menu() {
$items = array();
$items['mymodule/view'] = array(
'title' => 'Mymodule',
'page callback' => 'mymodule_display',
'access callback' => 'user_access',
'access arguments' => array('Access administration menu'),
'weight' => 1,
'type' => MENU_CALLBACK,
);
return $items;
}
A:
What would help is the code for the mymodule_display() function. However, it sounds like you are printing the output in the function instead of returning it.
Blank page:
/**
* Creates a blank page with only the module output.
*/
function mymodule_display() {
print 'Module content';
}
Themed page:
/**
* Output the content in the main content area of active theme.
*/
function mymodule_display() {
return 'Module content';
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Python - Executing code as long as a subprocess is running
I would like to run a section of code as long as a forked subprocess (rsync) is running. This is how I did it in my code:
rsync_proc = subprocess.Popen(proc_args, stdout=subprocess.PIPE)
while rsync_proc.poll() == None:
sys.stdout.write('\r'+
rsync_progress_report(source_size_kb, dest, start)),
sys.stdout.flush()
time.sleep(1)
For some reason, this causes the rsync subprocess to get stuck when it's almost finished. The while loop just continues looping with the rsync_proc.poll() returning None.
When I do run this same rsync call without the while loop code, it finishes without a problem.
Thanks in advance.
A:
If you attach strace to your stuck rsync child process, you'll probably see it's blocked writing to stdout.
If it's blocked writing to stdout, it's probably because the pipe is full because you never read from it.
Try reading from the pipe and just discarding the output - or, if you really don't want the output, don't connect it to a pipe in the first place.
| {
"pile_set_name": "StackExchange"
} |
Q:
JQuery hide specific parent
I have this table
<table>
<tr>
<td>One</td>
<td>*Two</td>
</tr>
<tr>
<td>One</td>
</tr>
</table>
and this JQuery
$("#show").click(function () {
$("td:contains('*Two')").show();
})
$("#hide").click(function () {
$("td:contains('*Two')").hide();
})
$("#hideRow").click(function (){
$("tr:contains('*Two')").parent().hide();
})
I'm trying to only hide the row that has "*Two" but it hides all parent trs
Edit: I'm working on it in jfiddle
http://jsfiddle.net/tvsfbj8j/
A:
Change this lines:
$("#hideRow").click(function (){
$("tr:contains('*Two')").parent().hide();
})
To:
$("#hideRow").click(function (){
$("td:contains('*Two')").parent().hide();
})
Notice the change from tr:contains to td:contains.
| {
"pile_set_name": "StackExchange"
} |
Q:
Jenkins: update SCM without triggering a build?
We have an SCM-controlled project that polls a repo every several minutes. Overall the workflow is great but occasionally I need to push the new changes to the server's repository without triggering a build in Jenkins (for various reasons: long builds, minor changes, concurrent commits etc).
I have already set up a quiet period, and sometimes I just start and stop the build (which is awkward), so the Jenkins pulls the changes and does not trigger the build later.
So, is there a plugin of any sort that allows either:
Manually cancel the future build (before it's triggered by SCM poller)
Manually update the project's SCM repo without triggering a build?
A:
You have many solutions to do this :
Instead of polling your SCM and trigger a build on change, you can do it another way. You can make your SCM decide if the commit should trigger a job or not. Have a look there for an example
You could try to use the "Excluded Commit comments" property in Subversion extended properties of your job, this way, you could avoid to trigger builds on "useless commits".
| {
"pile_set_name": "StackExchange"
} |
Q:
Google Product Sans font in Android Application, okay to use?
I've seen the Google Product Sans font in quite a few popular apps on the Play Store, and available to download from a few places. (https://9to5google.com/2018/05/09/google-sans-vs-product-sans/)
However, upon visiting the Google Fonts page for Product Sans it displays this message: https://fonts.google.com/license/productsans
Google offers many fonts under open source licenses. This is not one of them. Please see fonts.google.com for options you can use.
Does not open source mean that we simply can't modify it, but we can use it? Would I be allowed to use this font in my Android application if I don't modify the font at all?
A:
It means you cannot use it. It has nothing to do with whether you modify it or not.
If something is open source, you may be able to use it, depending on the license and how you intend to use it. But in this case the fonts are not open source at all.
| {
"pile_set_name": "StackExchange"
} |
Q:
Create a form for accessing relationships in RoR 3
This is kind of evolution of my previous question (although I changed a lot, including model names so figured I should better create another thread).. and the nature of question changed as well..
Currently I am struggling to create a form for the function
@dot2.link!(@dot)
The function works fine in console.
Here is the info from models / controllers (I tried to keep it minimal):
class User < ActiveRecord::Base
has_many :dots, :dependent => :destroy
....
end
Dot
class Dot < ActiveRecord::Base
belongs_to :user
has_many :linkages
...
def link!(new_dot)
linkages.create!(:end_id => new_dot.id)
end
...
end
Linkages:
class LinkagesController < ApplicationController
...
def create
@dot = current_user.dots.find(params[:linkages][:end_id])
@dot2 = Dot.find(params[:id])
@dot2.link!(@dot)
end
Linkages migration:
class CreateLinkages < ActiveRecord::Migration
def self.up
create_table :linkages do |t|
t.integer :start_id
t.integer :end_id
t.timestamps
end
add_index :linkages, :start_id
add_index :linkages, :end_id
add_index :linkages, [:start_id, :end_id], :unique => true
end
...
end
Now in console if I do
User.first.dots.first.link!(User.second.dots.second)
everything works fine.
How would I create a form for it (using just dot_id) as input??
Thanks!
A:
Look up the collection_select form helper. It renders an association however you like, defaults to a Selectbox.
| {
"pile_set_name": "StackExchange"
} |
Q:
Yii2 Call api method from backend controllers
I have implemented API based on advanced template following Yii Rest API documentation. And I want to call API methods from backend controllers. Is it possible to do?
Thanks
A:
So, I finally found a solution.
My Yii2 application has advanced template. I've created api module.
So app has 3 endpoints
api
backend
frontend
And I wanted to call api methods from backend or frontend, It's not important.
So the main goal here that api is the module. You can read about this here
In backend/config/main.php
'modules' => [
'api' => [
'basePath' => '@api/modules/v1',
'class' => 'api\modules\v1\Module'
]
],
And then for example
in backend/UserController/indexAction
$res = Yii::$app->runAction('api/user/index');
That how it works. Hope it will help to someone.
| {
"pile_set_name": "StackExchange"
} |
Q:
Count Function - Codeigniter and MySQL
I have a table as below:
table name: brand
id | brand
1 | UNIQLO
2 | PDI
3 | PDI
4 | H&M
5 | UNIQLO
The result that I need is:
PDI x 2
UNIQLO x 2
H&M x 1
I have tried this :
$this->db->select('brand, count(*) as TOTAL');
$this->db->from('brand');
$this->db->group_by('id');
$query = $this->db->get();
return $query->result();
But my output is uniqlopdiuniqlopdiH&Muniqlo.
Anyone can solve my problem?
A:
Michael Berkowski is right
It should be group by brand.
Your query will be like this
$this->db->select('brand, count(*) as TOTAL');
$this->db->from('brand');
$this->db->group_by('brand');
$query = $this->db->get();
return $query->result();
| {
"pile_set_name": "StackExchange"
} |
Q:
App crashing when open map in dialog
i have custom dialog, i want to show map in the dialog it's working fine but when i show the second time at that time my app is crashing, i stuck in it from many days please guys help to solve it!!!
My code is below
<fragment
android:id="@+id/mGoogleMap"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
MainActivity.java
private void showMapDialog() {
mDialog = new Dialog(MainActivity.this);
mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
mDialog.setContentView(R.layout.dialog_map_view);
mDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
mIsDialogueClick = false;
}
});
mDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
mIsDialogueClick = false;
}
});
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mGoogleMap);
if (mMap == null) {
mapFragment.getMapAsync(this);
}
if (mDialog != null && !mDialog.isShowing()) {
mDialog.show();
mIsDialogueClick = true;
}
// mDialog.show();
}
and in onMapReady method i'm showing marker of current location
My error log is below
02-20 15:35:41.356 23874-23874/com.example E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example, PID: 23874
android.view.InflateException: Binary XML file line #43: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:809)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:809)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:407)
at android.app.Dialog.setContentView(Dialog.java:490)
at com.example.forms.MainActivity.showMapDialog(MainActivity.java:614)
at com.example.forms.MainActivity.access$600(MainActivity.java:49)
at com.example.forms.MainActivity$3.onClick(MainActivity.java:274)
at android.view.View.performClick(View.java:4788)
at android.view.View$PerformClick.run(View.java:19923)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5382)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:928)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:723)
A:
I had the same error with the map in viewpager. Because you use dialog to inflate your map, and you open it again, dialog will inflate your map again (fragment manager will add the same id/tag). YOu don't need to create new dialog multiple time
mDialog = new Dialog(MainActivity.this);
mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
mDialog.setContentView(R.layout.dialog_map_view);
You can move codes above to outside method showMapDialog() when you want to show your dialog, just create it 1 time.
| {
"pile_set_name": "StackExchange"
} |
Q:
debug in localhost using deployed database
I use Google Eclipse Plugin, develop a web page using GWT + GAE/Java.
I would like to debug in localhost with the local GWT code but want to use the database in my actual deployed web page.
Is it possible?
A:
Filter doesn't work well with RemoteServiceServlets so add these to your RemoteServiceServlet:
RemoteApiOptions options;
RemoteApiInstaller installer;
@Override
protected void onBeforeRequestDeserialized(String serializedRequest) {
if (getThreadLocalRequest().getRequestURL().indexOf("127.0.0.1") != -1) {
if (options == null) {
options = new RemoteApiOptions().server("example.appspot.com", 443).credentials("username",
"password");
installer = new RemoteApiInstaller();
try {
installer.install(options);
options.reuseCredentials("username", installer.serializeCredentials());
}
catch (IOException e) {
e.printStackTrace();
}
}
else {
installer = new RemoteApiInstaller();
try {
installer.install(options);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Override
protected void onAfterResponseSerialized(String serializedResponse) {
if (getThreadLocalRequest().getRequestURL().indexOf("127.0.0.1") != -1)
installer.uninstall();
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I split a text file based on the content into multiple text files?
I have a text file called CAMS.txt that contains the following:
4153999999999991
4153999999999992
4153999999999993
4153999999999994
4801999999999991
4801999999999992
4801999999999993
I would like to split the CAMS.txt file into 2 files - CAMS1.txt and CAMS2.txt. Their contents are as follows
CAMS1.txt
4153999999999991
4153999999999992
4153999999999993
4153999999999994
CAMS2.txt
4801999999999991
4801999999999992
4801999999999993
It's really splitting the file based on the first 4 digits of the original CAMS.txt file. It will always be 4153 and 4801. I'm new to the unix world =)
A:
awk '/^4153/ {print >"CAMS1.TXT"; next} {print >"CAMS2.TXT"}' CAMS.TXT
There are other ways to do that, another would be using two grep commands
grep "^4153" CAMS.TXT > CAMS1.TXT
grep -v "^4153" CAMS.TXT > CAMS2.TXT
That's less efficient but easier to type, after the first grep is done, you recall it from your shell history (using the "up" arrow key) and makes a few changes. Of course the file is read two times, so don't do that if it is huge.
A:
For this particular case where you know the text already, you can do something like
while read line; do
[[ $line =~ ^4153 ]] &&
printf "%s\n" "$line" >> CAMS1.TXT ||
printf "%s\n" "$line" >> CAMS2.TXT
done < CAMS.TXT
This reads each line of CAMS.TXT into the variable $line and then, if $line starts with 4153, it prints to CAMS1 and if not, it prints to CAMS2.
Alternatively, you could print each line to standard error or standard output depending on what the first numbers are and redirect the command's output accordingly. For example:
perl -ne '/^4153/ ? print STDOUT : print STDERR' CAMS.TXT >CAMS1.TXT 2>CAMS2.TXT
If you don't know what the text will be, you could just write each line to a file whose name is the first 4 characters of the line:
awk '{print >> substr($1,1,4)}' CAMS.TXT
The above will create two files, 4153 and 4801 each containing the lines you expect. This has the advantage of working with any number of different patterns.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to remove some extra space at bottom in QMChatViewController?
I am using QuickBlox Q-municate for my chat application and after set up Q-municate in my application in swift, i am getting some extra space at bottom. I tried with different solution provided in code but not able to remove that space.
Please help me on this how can i remove that space.
A:
You should override "inputToolBarStartPos" method which is used in the QMChatViewController.
For Swift
-(NSUInteger)inputToolBarStartPos {
return 0;
}
For Objective C
@objc func inputToolBarStartPos() -> Int{
return 0;
}
Original answer
| {
"pile_set_name": "StackExchange"
} |
Q:
Odd bug converting char to int (Objective C)
I have an app set up where I convert an NSString into an array of char variables, and I'm trying to convert some of the chars to integers (basically to parse the numbers out of the string). But when I try to convert them to int variables, they suddenly change value.
For example:
char thechar = array[7]; //to make sure the issue isn't related to the array
NSLog(@"%c %i %i",thechar,(int) thechar, [[NSNumber numberWithUnsignedChar:thechar] intValue]);
returns this:
3 51 51
Both methods (that I've found) of converting it seem to change the value to 51. Does anyone know what might be happening?
A:
I figured it out: just convert it to NSString and then get the intValue.
[[NSString stringWithFormat:@"%c", thechar] intValue];
A:
51 is the numeric value for the literal character '3'. It dates back to the ASCII standard, though many common Unicode encodings maintain the value as well.
You can pretty reliably just subtract 48 (or '0') to get the number:
int num = (int)(numAsChar - '0');
Alternatively, if you want to convert an entire string, you can use atoi:
int num = atoi(myNumberString);
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.