source
sequence | text
stringlengths 99
98.5k
|
---|---|
[
"stackoverflow",
"0058959275.txt"
] | Q:
What is the name of such collection / algorithm that looksup elements via "buckets"
This collection works logically as map but allows to lookup elements by its prefix. It consists of nested Maps in which every nested map corresponds to elements that matches next token of the key.
For example:
Lets have bar as a map key.
Lets tokenize that bar int "subkeys": b,a,r. Then we would put value using following method (pseudocode)
From root map Map<String,Value or Map> get bor put new Map<String,Value or Map if absent
From map from previous step get aor put new Map<String,Value or Map> if absent
In map from previous step, set or replace value under key r
Retrieval is similar (pseudocode)
Take b bucket from root map
Take a bucket from previous bucket
Take r take value under r from previous bucket
How is such collection called? I would call it a GraphMap or BucketGraph. But what is the proper name?
A:
What you describe sounds very much like a Trie, or Prefix Tree. It can be used to sort strings or other objects into buckets based on the individual characters of a word, or words in a sentence, or other types of "sequentian decomposition" (not sure if that is the right term...).
|
[
"stackoverflow",
"0043556592.txt"
] | Q:
python nested lists not splitting
So I have the following nested list in python:
a=[['1475367347', '72', 'c82e4f74ab2856bf', '14e87da06de28007', '1faf45a4', '83f8e8c8', '6', 'c7bd96e2', 'c7bd96e2', 'a799a5bf', '4b664dcf', '5d955804', '3d2831f2', '1', '1'],['1475367347', '72', 'c82e4f74ab2856bf', '14e87da06de28007', '1faf45a4', '83f8e8c8', '6', 'c7bd96e2', 'c7bd96e2', 'a799a5bf', '4b664dcf', '5d955804', '3d2831f2', '1', '1']]
Here's what I'm doing:
for b in a:
for item in b:
print(item)
But the result of the above print statement is as follows:
[
[
'
1
4
7
5
3
6
7
3
4
7
'
,
'
7
2
'
,
'
c
8
2
e
4
f
7
4
a
b
2
8
5
6
b
f
'
,
'
1
4
e
8
7
d
a
0
6
d
e
2
8
0
0
7
'
,
'
1
f
a
f
4
5
a
4
'
,
'
8
3
f
8
e
8
c
8
'
,
'
6
'
,
'
c
7
b
d
9
6
e
2
'
,
'
c
7
b
d
9
6
e
2
'
,
'
a
7
9
9
a
5
b
f
'
,
'
4
b
6
6
4
d
c
f
'
,
'
5
d
9
5
5
8
0
4
'
,
'
3
d
2
8
3
1
f
2
'
,
'
1
'
,
'
1
'
]
,
[
'
1
4
7
5
3
6
7
3
4
7
'
,
'
7
2
'
,
'
c
8
2
e
4
f
7
4
a
b
2
8
5
6
b
f
'
,
'
1
4
e
8
7
d
a
0
6
d
e
2
8
0
0
7
'
,
'
1
f
a
f
4
5
a
4
'
,
'
8
3
f
8
e
8
c
8
'
,
'
6
'
,
'
c
7
b
d
9
6
e
2
'
,
'
c
7
b
d
9
6
e
2
'
,
'
a
7
9
9
a
5
b
f
'
,
'
4
b
6
6
4
d
c
f
'
,
'
5
d
9
5
5
8
0
4
'
,
'
3
d
2
8
3
1
f
2
'
,
'
1
'
,
'
1
'
]
]
What am I missing here?
A:
use ast.literal_eval:
>>> a="""[['1475367347', '72', 'c82e4f74ab2856bf', '14e87da06de28007', '1faf45a4', '83f8e8c8', '6', 'c7bd96e2', 'c7bd96e2', 'a799a5bf', '4b664dcf', '5d955804', '3d2831f2', '1', '1'],['1475367347', '72', 'c82e4f74ab2856bf', '14e87da06de28007', '1faf45a4', '83f8e8c8', '6', 'c7bd96e2', 'c7bd96e2', 'a799a5bf', '4b664dcf', '5d955804', '3d2831f2', '1', '1']]"""
>>> a = ast.literal_eval(a)
>>> a
[['1475367347', '72', 'c82e4f74ab2856bf', '14e87da06de28007', '1faf45a4', '83f8e8c8', '6', 'c7bd96e2', 'c7bd96e2', 'a799a5bf', '4b664dcf', '5d955804', '3d2831f2', '1', '1'], ['1475367347', '72', 'c82e4f74ab2856bf', '14e87da06de28007', '1faf45a4', '83f8e8c8', '6', 'c7bd96e2', 'c7bd96e2', 'a799a5bf', '4b664dcf', '5d955804', '3d2831f2', '1', '1']]
>>> for x in a:
... for y in x:
... print y
...
1475367347
72
c82e4f74ab2856bf
14e87da06de28007
1faf45a4
83f8e8c8
6
c7bd96e2
c7bd96e2
a799a5bf
4b664dcf
5d955804
3d2831f2
1
1
1475367347
72
c82e4f74ab2856bf
14e87da06de28007
1faf45a4
83f8e8c8
6
c7bd96e2
c7bd96e2
a799a5bf
4b664dcf
5d955804
3d2831f2
1
1
|
[
"stackoverflow",
"0035887896.txt"
] | Q:
Can't post all three text fields to text document?
I'm trying to create a website for a college assignment and i'm having issues getting my three text fields to submit to my text document. I managed to get it to send the first one over by simply putting $_POST['des1'] and sure enough it worked perfectly. However, when I attempt to make it send over all three it doesn't work. What am I missing?
<?php
$myFile=fopen("Observation.txt","w") or exit("Can’t open file!");
fwrite($myFile, $_POST['des1'], $_POST['act1'], $_POST['date1']."\r\n");
fclose($myFile);
?>
A:
It's because fwrite() only takes a max of 3 arguments, but only 2 are necessary.
If you want to write it to the file, the second argument has to be the only text being written to that file.
You currently have a few , separating the current fields, which fwrite will treat like more arguments and get confused.
It needs to be something like this:
$string = $_POST['des1'].$_POST['act1'].$_POST['date1']."\r\n";
fwrite($myFile, $string);
|
[
"stackoverflow",
"0036648234.txt"
] | Q:
Oracle query on time (and not date)
How can you query on just the time portion of an Orace date field. Ie:
select * from mytable
where
date_column < '05:30:00'
Want the query to return any rows where the time represented by date_column is less than 5:30 regardless of the date.
A:
You can try like this:
select * from mytable
where
to_char( date_column, 'HH24:MI:SS' ) < '05:30:00'
|
[
"stackoverflow",
"0041012791.txt"
] | Q:
Hide group in odoo 9
How with xpath expr replace (hide) group Configuration in project managment module in tabs settings?
<group string="Configuration" groups="base.group_no_one">
<field name="sequence" groups="base.group_no_one"/>
</group>
I'm try with below code but get error:
<xpath expr="//group[@string='Configuration']" position="replace">
</xpath>
A:
I guess the error you are getting is a ParseError, because you are using the string attribute as a selector inside your XPath expression, which is not allowed since Odoo v9.0.
Instead, you might try to find the sequence field and the select the parent:
<xpath expr="//field[@name='sequence']/.." position="replace">
</xpath>
However, replacing the whole element might not be the best solution, because other modules might use the group or the sequence field inside an inherited view, which would cause an error. A better solution would be to hide the group using the invisible attribute. The full record could look something like this:
<record id="edit_project_inherit" model="ir.ui.view">
<field name="model">project.project</field>
<field name="inherit_id" ref="project.edit_project"/>
<field name="arch" type="xml">
<xpath expr="//field[@name='sequence']/.." position="attributes">
<attribute name="invisible">1</attribute>
</xpath>
</field>
</record>
|
[
"stackoverflow",
"0040565583.txt"
] | Q:
How do I export this MongoDB data into a CSV file (a "join" of two collections)?
I have a database with two collections.
Collection cars has documents that look like this:
{ license_number: "123456", name: "tesla" }
{ license_number: "654321", name: "ford" }
{ license_number: "987654", name: "volvo" }
Collection greatCars has documents that look like this:
{ license_number: "123456" }
I want to export a "join" of these two collections into a CSV file that looks like this:
license_number, name, isGreat
123456, tesla, TRUE
654321, ford, FALSE
987654, volvo, FALSE
(Please don't take offense. It's just an example and I know nothing about cars.)
A:
You can create a short javascript program that will transfer the data you want to export into a new temporary collection, that can be exported.
create a file export.js:
//initialise the export results collection
db.export.results.drop()`;
//create a cursor containing the contents of the list1 collection
cursor = db.list1.find();
while (cursor.hasNext()) {
doc = cursor.next();
//Check if the document exists in the list2 collection
list2 = db.list2.find({"<id_fieldname>": doc.<id_fieldname>});
if (list2.hasNext()) {
//if it does exist, add the document from list1 to the new export collection
db.export.results.insert(doc);
}
}
print(db.export.results.count() + " matching documents found");
Run this from the cmd line:
# mongo "localhost:27017/<dbname>" export.js
It will create a collection called export.results containing the document from the list1 collection with documents in the list2 (in your case cars and greatCars)collection with a matching id field. You can then export or dump this collection:
# mongoexport --db <dbname> -c export.results -type csv -o <file_name>
|
[
"scicomp.stackexchange",
"0000035802.txt"
] | Q:
Algorithm to determine if a polynomial has any complex roots
Is there a simple algorithm to determine if a given polynomial (with all real coefficients) has all real roots? I do not need to know what the roots are; I just what to know if a given polynomial has any complex roots.
Background: I am aware that there are algorithms (for example see here) to compute all of the real roots of an arbitrary degree polynomial
\begin{equation}
\label{polynomial}
a_0 + a_1x + a_2x^2 + \cdots + a_n x^n ,
\end{equation}
where $a_0,...,a_n$ are all real constants.
A:
You can use the companion matrix to find the roots via eigenvalue calculation:
Companion matrix
Note that you have to consider Sturm's theorem in order to find the number of complex/real roots without explicitly calculating them (that's the only way):
Sturm's theorem
|
[
"stackoverflow",
"0040677433.txt"
] | Q:
Entering integers doesn't stop for non-integers
I have a program in which I enter integers until something that is not an integer is entered. The code needs to print the integers that meet the following condition:
integer "abcde": "a > b, b < c, c > d, d < e" or "a < b, b > c, c < d, d > e"
example: 343, 4624, 6231209
I have written this, and it works for most of the integers, but somehow it doesnt work for some.
#include <stdio.h>
int main()
{
int a;
while (scanf("%d", &a))
{
int a1 = a;
int cifra = 0, cifra1 = 0, cifra2 = 0;
while (a1 > 0)
{
cifra = a1 % 10;
cifra1 = (a1 / 10) % 10;
cifra2 = (a1 / 100) % 10;
a1 = a1 / 10;
if (cifra == cifra1 || cifra1 == cifra2)
{
break;
}
if ((cifra < cifra1 && cifra1 > cifra2) || (cifra > cifra1 && cifra1 < cifra2)) {
printf("%d\n", a);
break;
}
else
{
break;
}
}
}
return 0;
}
A:
Solved it myself
#include <stdio.h>
int main()
{
int a;
int cifra = 0, cifra1 = 0, cifra2 = 0;
int a1;
while(scanf("%d", &a))
{
int a1 = a;
while(a1 > 0){
if(a1 <= 9)
{
break;
}
cifra = a1 % 10;
cifra1 = (a1 / 10) % 10;
cifra2 = (a1 / 100) % 10;
if((cifra > cifra1 || cifra1 > cifra)&&cifra2 == 0)
{
printf("%d\n", a);
break;
}
if((cifra < cifra1&&cifra1 > cifra2) || (cifra > cifra1&&cifra1 < cifra2))
{
a1 = a1 / 10;;
}
else
{
break;
}
}
}
return 0;
}
|
[
"pt.stackoverflow",
"0000148157.txt"
] | Q:
A localização obtida por getLastLocation() retorna sempre nula
Estou realizando varias tentativas, mas não consigo obter a localização atual de um usuário utilizando da Location API.
Estou executando o exemplo a seguir:
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
Location localizacao;
GoogleApiClient mapGoogleApiClient;
EditText edtLat;
EditText edtLog;
Button btLocalizacao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtLat = (EditText) findViewById(R.id.edtLatitude);
edtLog = (EditText) findViewById(R.id.edtLongitude);
btLocalizacao = (Button) findViewById(R.id.btLocalizacao);
if (mapGoogleApiClient == null) {
mapGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
btLocalizacao.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
GPS();
}
});
}
@TargetApi(Build.VERSION_CODES.M)
public void GPS() {
if(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// public void requestPermissions(@NonNull String[] permissions, int requestCode)
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for Activity#requestPermissions for more details.
return;
}
localizacao = LocationServices.FusedLocationApi.getLastLocation(mapGoogleApiClient);
if (localizacao != null) {
edtLat.setText(String.valueOf(localizacao.getLatitude()));
edtLog.setText(String.valueOf(localizacao.getLongitude()));
} else {
AlertDialog erroLocation = new AlertDialog.Builder(this).create();
erroLocation.setIcon(R.drawable.alert);
erroLocation.setTitle("Localização não encontrada");
erroLocation.setMessage("Sua Localização não foi encontrada!! Tente novamente!");
erroLocation.show();
}
}
@Override
public void onConnected(Bundle bundle) {
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}}
O sistema roda perfeitamente, porem ele acaba todo momento caindo no else(código abaixo) do método GPS, pois não está passando a localização:
else {
AlertDialog erroLocation = new AlertDialog.Builder(this).create();
erroLocation.setIcon(R.drawable.alert);
erroLocation.setTitle("Localização não encontrada");
erroLocation.setMessage("Sua Localização não foi encontrada!! Tente novamente!");
erroLocation.show();
}
Está pergunta não é duplicada, pois é um caso diferente e estava utilizando outros métodos para fazer funcionar. Resposta abaixo resolveu com sucesso essa pergunta.
A:
Como alertou o nosso amigo nos comentários, resolvi melhorar a resposta postando duas formas de capturar GPS, usando GoogleApiClient e usando LocationManager. Nas condições do Android 6.0(Api level 23) existe o Requesting Permissions at Run Time que trata-se da questão das permissões, que é bem interessante você dar lida e aprender mais.
1. Google Location API
As APIs de localização facilitam a criação de aplicativos com ciência
da localização e baixo consumo de energia. Como a Google Maps Android
API, a Location API é distribuída como parte do SDK do Google Play
Services.
Classe Main
public class Main extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
GoogleApiClient mapGoogleApiClient;
EditText edtLat;
EditText edtLog;
Button btLocalizacao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_get_localization);
edtLat = (EditText) findViewById(R.id.et1);
edtLog = (EditText) findViewById(R.id.et2);
btLocalizacao = (Button) findViewById(R.id.btLocalizacao);
if (mapGoogleApiClient == null) {
mapGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
btLocalizacao.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (GetLocalization(Main.this)) {
if (ActivityCompat.checkSelfPermission(Main.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(Main.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
return;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(mapGoogleApiClient);
if (location != null) {
edtLat.setText(String.valueOf(location.getLatitude()));
edtLog.setText(String.valueOf(location.getLongitude()));
} else {
showSettingsAlert();
}
}
}
});
}
@Override
protected void onResume() {
super.onResume();
mapGoogleApiClient.connect();
}
@Override
protected void onPause() {
super.onPause();
if (mapGoogleApiClient.isConnected()) {
mapGoogleApiClient.disconnect();
}
}
@Override
public void onConnected(Bundle bundle) {
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public boolean GetLocalization(Context context){
int REQUEST_PERMISSION_LOCALIZATION = 221;
boolean res=true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
res = false;
ActivityCompat.requestPermissions((Activity) context, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_PERMISSION_LOCALIZATION);
}
}
return res;
}
/**
* Este metodo exite uma alerta para configuração do GPS
*/
public void showSettingsAlert(){
android.app.AlertDialog.Builder alertDialog = new android.app.AlertDialog.Builder(Main.this);
// Titulo do dialogo
alertDialog.setTitle("GPS");
// Mensagem do dialogo
alertDialog.setMessage("GPS não está habilitado. Deseja configurar?");
// On pressing Settings button
alertDialog.setPositiveButton("Configurar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
Main.this.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// visualizacao do dialogo
alertDialog.show();
}
}
2. LocationManager
Fiz alguns testes e criei uma classe chamada ObtainGPS para resolver o seu problema, que seria capturar sua atual localização (latitude/longitude). Nele também possui um método showSettingsAlert() que verifica se o GPS do dispositivo está habilitado, caso não esteja habilitado, o app te direciona para que você possa configurar/habilitar.
Bom, na Main você apenas precisa declara o ObtainGPS além de criar um método GetLocalization. Então ficaria assim:
Classe Main
public class Main extends AppCompatActivity {
ObtainGPS gps;
Button btLocalizacao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_get_localization);
btLocalizacao = (Button) findViewById(R.id.button3);
btLocalizacao.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getLocalization();
}
});
}
public void getLocalization() {
gps = new ObtainGPS(Main.this);
if (GetLocalization(Main.this)) {
// check if GPS enabled
if (gps.canGetLocation()) {
AlertDialog erroLocation = new AlertDialog.Builder(this).create();
erroLocation.setTitle("Localização");
erroLocation.setMessage("Lat:" + gps.getLatitude() + " Lng:" + gps.getLongitude());
erroLocation.show();
} else {
AlertDialog erroLocation = new AlertDialog.Builder(this).create();
erroLocation.setTitle("Localização não encontrada");
erroLocation.setMessage("Sua Localização não foi encontrada!! Tente novamente!");
erroLocation.show();
gps.showSettingsAlert();
}
}
}
public boolean GetLocalization(Context context) {
int REQUEST_PERMISSION_LOCALIZATION = 221;
boolean res = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// public void requestPermissions(@NonNull String[] permissions, int requestCode)
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for Activity#requestPermissions for more details.
res = false;
ActivityCompat.requestPermissions((Activity) context, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_PERMISSION_LOCALIZATION);
}
}
return res;
}
}
Uma observação que aqui estou usando getLastKnownLocation
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Classe ObtainGPS
public class ObtainGPS extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public ObtainGPS(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// public void requestPermissions(@NonNull String[] permissions, int requestCode)
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for Activity#requestPermissions for more details.
return null;
}
}
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* @return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS");
// Setting Dialog Message
alertDialog.setMessage("GPS não está habilitado. Você deseja configura-lo?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Screenshots
Criei um repositório no Github com nome obtgps pegando cordeadas usando duas formas. Você pode baixar o projeto e fazer as devidas verificações.
Detalhes
Intensões do Google Maps
A:
Apesar da sua implementação ser mínima, para obter a localização julgo que só falta chamar mapGoogleApiClient.connect().
Faço o overrride dos métodos onStart() e onStop() assim:
@Override
public void onStart() {
super.onStart();
mapGoogleApiClient.connect();
}
@Override
public void onStop() {
super.onStop();
mapGoogleApiClient.disconnect();
}
|
[
"stackoverflow",
"0055754505.txt"
] | Q:
Section not created in program-release version C++
I am storing some variables inside custom section in my program. During debugging session I can check it is created and that it contains the necessary data. But in release mode, it disappears!
Note: I am also creating an executable section which strangely is created in both version. The CPU platform seems to make no difference.
Why doesn't the "data" segment appear in the release version?
This is a short snapshot:
// Defnitions used for better code segmentation
#define store_variable(x) __declspec(allocate(x)) //for data segment
#define store_code(seg) __declspec(code_seg(seg)) //for execution segment
#pragma section(".eqwrt", read) //weird name because I thought there would be collision
store_variable(".eqwrt") UCHAR USER_DATA[SIZE];
store_variable(".eqwrt") USHORT Version = 1;
store_code(".wsect") bool sendError();
The program (it's a dll) is compiled with a fixed base address and with /MT flag.
Release version x64. Only one segment appears-the executable one:
Debug version x64. Both segments show up:
A:
Try to disable Link-time optimizatizon scheme from the project's settings.
To do that go to: Configuration Properties General Whole Program Optimisation and set to No Whole Program Optimisation.
Most likely it has something to do with the optimisations performed during linking.
More details you can get from here : What's C++ optimization & Whole program optimization in visual studio
|
[
"stackoverflow",
"0013601076.txt"
] | Q:
Selected Row Checkmark color changing
we have a table view, with the cell selected being marked by a blue checkmark. The problem is that initially when the table loads, the selected cell will have the check mark in blue color which is what we need like in the below figure
Now when we select another row, the selected row check mark changes to white, what could be causing this issue?
A:
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
Add this if in Bellow UITableView Delegate Method Before return Cell;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
}
Hope it Help's you
|
[
"stackoverflow",
"0009261830.txt"
] | Q:
Django: conditional 500 response depending on Accept header?
Django returns an HTML error template by default when an unhandled exception happens in a view. I would like to return a JSON response instead, if the request had an "Accept: 'application/json'" header (but otherwise return the usual HTML). How might I do that?
A:
You can specify your own 500 view function, in which you should be able to modify the response accordingly. See https://docs.djangoproject.com/en/dev/topics/http/urls/#handler500
|
[
"math.stackexchange",
"0001495450.txt"
] | Q:
Show that every line $y=mx$ intersects the curve $y^2+\int _{ 0 }^{ x }{ f(t)dt=2!}$
If $f$ is a continuous function with $\displaystyle \int _{ 0 }^{ x}{
f(t)dt\rightarrow\infty } $ as $|x|\rightarrow\infty$,then show that
every line
$y=mx$ intersects the curve $\displaystyle y^2+\int _{ 0 }^{ x }{
f(t)dt=2!} $
I can't understand how to proceed with this problem.Any suggestion?
A:
Set : $\displaystyle g(x)= (mx)^2+\int_0^x f(t)\ \mathrm{d}t$, $g$ is continuous since it is the sum of two continuous
(and also differentiable) functions.
We have : $g(0)=0$, and : $\displaystyle \lim_{x\to \infty} g(x)= +\infty$, for any $m\in \mathbb{R}$ .
So the equation : $g(x)=\alpha$ has a solution for any $\alpha \geq 0$.
Here we have $\alpha =2$
|
[
"stackoverflow",
"0040288129.txt"
] | Q:
DataStax Graph Fuzz Query
I am actually experimenting with DSE (Datastax Entreprise) Graph and i am stuck in a problem: i would like to do a gremlin fuzzy query on DSE. Basicaly, it will return the strings that has the highest match scores. I know you can do that in TitanDb by using the graph.indexQuery command.
Is there any equivalent to this gremlin command in DSE?
Thank you
A:
Check out the indexing overview of DSE Graph. https://docs.datastax.com/en/latest-dse/datastax_enterprise/graph/using/indexOverview.html?hl=index
We enable this functionality through the integration with DSE Search (i.e. DataStax's integration with SOLR). Right now we are tied to String and Text searching, but in the near future we'll be able to leverage DSE Search fully through Gremlin.
|
[
"math.stackexchange",
"0000409403.txt"
] | Q:
Network's flow - a couple of issues
There are three requirements for the path to be a flow - capacity constraints, skew symmetry, and the flow conservation ( http://en.wikipedia.org/wiki/Flow_network ).
Ok, but what if the network would have only directed edges?
Green numbers are the flow function values, numbers in the squares are values of c(x, y).
Now, I don't see how the skew symmetry and the flow conservation are complied here...are they? (according to my notes they should be).
Another thing is - what actually is the flow? I guess it's not just a path between S and T vertices. I'd owe you a beer if you could explain me this as simply as possible :P
A:
Everything regarding the question should be clear from the Wikipedia entry you referred to. Anyway, flow networks are directed graphs by definiton. For 'skew symmetry' Cormen's Introduction to Algorithms says:
Skew symmetry is a notational convenience that says that the flow from a vertex $u$ to a vertex $v$ is the negative of the flow in the reverse direction.
So nothing to worry about skew symmetry. It is true for the graph by definition.
For 'flow-conservation' Cormen says:
The flow-conservation property says that the total flow out of a vertex other than the source or sink is $0$.
This property obviously holds for the given graph. For example, for vertex $1$: $f(1, s) = -1$ (due to skew symmetry), $f(1, 2) = 0$, $f(1, 4) = 0$, and $f(1, t) = 1$. Adding all of them gives $0$, hence the total flow out of vertex $1$ is indeed $0$. You should be able to prove this for other vertices.
In the given graph the net flow is $1$---that is $1$ unit of flow is leaving source ($s$) and exactly that amount of flow is reaching sink ($t$). Consult the Wikipedia entry or a good graph theory or algorithm textbook to understand what is 'flow' better.
|
[
"stackoverflow",
"0017133339.txt"
] | Q:
Implicit coercion for objects
I am having troubles with implicit coercion with the + operator in JavaScript. Namely the priority order of valueOf and toString.
var obj = {};
obj.toString(); => "[object Object]"
obj.valueOf(); => Object {}
'Hello ' + obj; => "Hello [object Object]"
So obj is implicitly coerced to a string using the toString() method over valueOf();
var obj2 = {
toString: function() {
return "[object MyObject]";
},
valueOf: function() {
return 17;
}
};
obj2.toString(); => "[object MyObject]"
obj2.valueOf(); => 17
'Hello ' + obj2; => "Hello 17"
So when I override the toString and valueOf methods, the + operator will coerce with valueOf.
What am I missing? Thanks.
A:
The answer can be found in a similar thread: valueOf() vs. toString() in Javascript
If the object can be transformed into a "primitive" JavaScript will try to treat it as a number. Otherwise string concatenation via the toString method is used. Without the valueOf method, JavaScript cannot tell how to convert the data, hence the object will be concatenated as a string.
If you're interested the precise specifications are available in the following pdf at around page 58: http://www.webreference.com/javascript/reference/ECMA-262/E262-3.pdf
Hope that helped :-)
|
[
"stackoverflow",
"0024149053.txt"
] | Q:
Sidekiq: perform_async and order-dependent operations
There's a controller action in my Rails app that contacts a user via text-message and email. For reasons I won't go into, the text-message needs to complete before the email can be sent successfully. I originally had something like this:
controller:
class MyController < ApplicationController
def contact_user
ContactUserWorker.perform_async(@user.id)
end
end
workers:
class ContactUserWorker
include Sidekiq::Worker
def perform(user_id)
SendUserTextWorker.perform_async(user_id)
SendUserEmailWorker.perform_async(user_id)
end
end
class SendUserTextWorker
include Sidekiq::Worker
def perform(user_id)
user = User.find(user_id)
user.send_text
end
end
class SendUserEmailWorker
include Sidekiq::Worker
def perform(user_id)
user = User.find(user_id)
user.send_email
end
end
This was unreliable; sometimes the email would fail, sometimes both would fail. I'm trying to determine whether perform_async was the cause of the problem. Was the async part allowing the email to fire off before the text had completed? I'm a little fuzzy on how exactly perform_async works, but that sounded like a reasonable guess.
At first, I refactored ContactUserWorker to:
class ContactUserWorker
include Sidekiq::Worker
def perform(user_id)
user = User.find(user_id)
User.send_text
SendUserEmailWorker.perform_async(user_id)
end
end
Eventually though, I just moved the call to send_text out of the workers altogether and into the controller:
class MyController < ApplicationController
def contact_user
@user.send_text
SendUserEmailWorker.perform_async(@user.id)
end
end
This is a simplified version of the real code, but that's the gist of it. It seems to be working fine now, though I still wonder whether the problem was Sidekiq-related or if something else was going on.
I'm curious whether my original structure would've worked if I'd used perform instead of perform_async for all the calls except the email call. Like this:
class MyController < ApplicationController
def contact_user
ContactUserWorker.perform(@user.id)
end
end
class ContactUserWorker
include Sidekiq::Worker
def perform(user_id)
SendUserTextWorker.perform(user_id)
SendUserEmailWorker.perform_async(user_id)
end
end
A:
If the email can only be sent after the text message has been sent, then send the email after successful completion of sending the text.
class ContactUserWorker
include Sidekiq::Worker
def perform(user_id)
SendUserTextWorker.perform_async(user_id)
end
end
class SendUserTextWorker
include Sidekiq::Worker
def perform(user_id)
user = User.find(user_id)
text_sent = user.send_text
SendUserEmailWorker.perform_async(user_id) if text_sent
end
end
class SendUserEmailWorker
include Sidekiq::Worker
def perform(user_id)
user = User.find(user_id)
user.send_email
end
end
In user.send_text you need to handle the fact that neither the text or the email has been sent.
|
[
"math.stackexchange",
"0001458872.txt"
] | Q:
Complex Portion of Exponential with Frequency Pi
I plotted the real and imaginary parts of the complex exponential
$e^{j\pi n}$ in MATLAB and got an unexpected result for the complex portion as well as something similar for $2\pi$. I was wondering why it appears as it does because I thought it would just oscillate between $\pm1$. I also plotted $e^{j(\pi/2)n}$ as well as $e^{j(3\pi/2)n}$ and both have a complex part that oscillates between $\pm1$.
Here is the code so you might reproduce it.
% Frequency
W0 = pi;
% Time
n = -20:20;
% Signal
j = sqrt(-1);
x = exp(j*W0*n);
% Plotting commands
figure(1)
subplot(2,1,1), stem(n,real(x)), xlabel('n'), title('Real part of e^{jW_0 n}');
subplot(2,1,2), stem(n,imag(x)), xlabel('n'), title('Imag. part of e^{jW_0 n}');
A:
The real part of $e^{\pi n i}$ alternates between $-1$ and $1$.
The imaginary part is nearly zero on the plot (notice $10^{-14}$ on the vertical axis). Theoretically, it should be exactly zero, but the computations introduce some small errors (rounding, truncation of power series, etc.)
|
[
"stackoverflow",
"0051253271.txt"
] | Q:
Dropping a column name that has a period in Spark dataframe
I'm having trouble dropping a column in a Spark dataframe that has a period. I know that you need to escape the column name using backticks (`). This works when I attempt to select columns, and indeed I've written my own little static function to escape all column names:
@staticmethod
def escape(columns):
return ["`" + col + "`" if "." in col else col for col in columns]
This can then be used to get my desired list of columns to select by:
desired_columns = MySparkClass.escape(
list(filter(lambda col: re.search('targetRegexStuffHere', col), target_df.columns))
)
filtered_df = df.select(desired_columns)
Using a trivial, reproducible example:
same = sqlContext.createDataFrame(
[
(1, 1, 'A', '2017-01-01'),
(2, 3, 'B', '2017-01-02'),
(3, 5, 'A', '2017-01-03'),
(4, 7, 'B', '2017-01-04')
],
('index', 'X', 'label.X.L.', 'date')
)
print(same.select('`label.X.L.`').collect())
Output here is:
[Row(label.X.L.='A'), Row(label.X.L.='B'), Row(label.X.L.='A'), Row(label.X.L.='B')]
However, removing the backticks results in an AnalysisException:
pyspark.sql.utils.AnalysisException: 'syntax error in attribute name: label.X.L.;'
When I attempt to drop the label.X.L. column, however, the backticks appear to not make any difference:
print(same.drop('`label.X.L.`').collect())
Output is
[Row(index=1, X=1, label.X.L.='A', date='2017-01-01'),
Row(index=2, X=3, label.X.L.='B', date='2017-01-02'),
Row(index=3, X=5, label.X.L.='A', date='2017-01-03'),
Row(index=4, X=7, label.X.L.='B', date='2017-01-04')]
What is the proper way to drop a column that contains a period within its name?
A:
The syntax for specifying which columns to use for select() and for drop() slightly different. When you have a period in your column name for select():
same.select('`label.X.L.`') # note the backticks
However, when you are attempting to drop:
same.drop('label.X.L.') # note the absence of the backticks
|
[
"stackoverflow",
"0031944023.txt"
] | Q:
Find index of a specific character in a string then parse the string
I have strings which looks like this [NAME LASTNAME/NAME.LAST@emailaddress/123456678]. What I want to do is parse strings which have the same format as shown above so I only get NAME LASTNAME. My psuedo idea is find the index of the first instance of /, then strip from index 1 to that index of / we found. I want this as a VBScript.
A:
Your way should work. You can also Split() your string on / and just grab the first element of the resulting array:
Const SOME_STRING = "John Doe/[email protected]/12345678"
WScript.Echo Split(SOME_STRING, "/")(0)
Output:
John Doe
Edit, with respect to comments.
If your string contains the [, you can still Split(). Just use Mid() to grab the first element starting at character position 2:
Const SOME_STRING = "[John Doe/[email protected]/12345678]"
WScript.Echo Mid(Split(SOME_STRING, "/")(0), 2)
|
[
"ru.stackoverflow",
"0000869065.txt"
] | Q:
CSS Убрать лишний пиксель у border
пишу сайт и я на этапе меню: код
у каждого элемента, кроме последнего есть свойство:
border-right:solid 1px #fb1300;
как у него убрать "лишний" пиксель внизу? (он налезает на нижний border)
A:
*,
*:before,
*:after{
box-sizing: border-box;
}
.menu {
list-style-type: none;
margin: 0px;
padding: 0px;
color: #fff;
font-size: 0;
}
.menu li {
font-size: 14px;
background: linear-gradient(to bottom, #fb0800, #ba0200);
display: inline-block;
width: 141px;
text-align: center;
height: 60px;
line-height: 60px;
border-bottom: 1px solid #000;
position: relative;
}
.menu li+li:before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 1px;
height: 100%;
background: #fb1300;
}
.menu li:first-child {
border-radius: 0px 0px 0px 10px;
}
.menu li:last-child {
border-radius: 0px 0px 10px 0px;
}
<ul class="menu">
<li>главная</li>
<li>Дымоходы</li>
<li>...</li>
</ul>
|
[
"stackoverflow",
"0005247245.txt"
] | Q:
Is it possible to define a non-generic interface which can have generic methods?
I was wondering if this code could be improved. The IProvider implements IProvider and overwrites Request(...). I'd like to combine these into a single interface. But I still need a typed and untyped interface to work with.
Is there a way to combine these where I get both or is this how the interfaces should look?
public interface IProvider
{
DataSourceDescriptor DataSource { get; set; }
IConfiguration Configuration { get; set; }
IResult Request(IQuery request);
}
public interface IProvider<T> : IProvider
{
new IResult<T> Request(IQuery request);
}
A:
If the generic type parameter T is only relevant in the context of the Request method, declare only that method as generic:
public interface IProvider
{
DataSourceDescriptor DataSource { get; set; }
IConfiguration Configuration { get; set; }
IResult Request(IQuery request);
IResult<T> Request<T>(IQuery request);
}
|
[
"stackoverflow",
"0059385471.txt"
] | Q:
separate text data with , using for loop in python
Input data:
12/12/2019 08:07:30 AM:Okay=enable
13/12/2018 02:04:32 PM:yes=disable
Output data:
12/12/2019 08:07:30
AM,Okay,enable
13/12/2018 02:04:32
PM,yes,disable
Please help me on this issue
A:
You can try this:
s = '12/12/2019 08:07:30 AM:Okay=enable'
d = '13/12/2018 02:04:32 PM:yes=disable'
pat=r'(.+?)(?=AM|PM)(\w+):(\w+)=(\w+)'
print(re.sub(pat,r'\1\n\2,\3,\4',s))
# 12/12/2019 08:07:30
# AM,Okay,enable
print(re.sub(pat,r'\1\n\2,\3,\4',d))
# 13/12/2018 02:04:32
# PM,yes,disable
|
[
"stackoverflow",
"0025589155.txt"
] | Q:
Why static variable not pointing to nil after being once initialized?
I am following one example to learn about singletons, but I am little confused with the code, particularly with the usage of static variable. Following is the code:
This is where code checks if this is the first time variable is initialized.
+ (instancetype)sharedStore
{
static BNRImageStore *sharedStore = nil;
if (!sharedStore) {
sharedStore = [[self alloc] initPrivate];
}
return sharedStore;
}
If it is the first time initPrivate: method is called:
- (instancetype)initPrivate
{
self = [super init];
if (self) {
_dictionary = [[NSMutableDictionary alloc] init];
}
return self;
}
I have a problem with first part of code, with sharedStore: method. How this variable sharedStore can retain data, when every time, we call this method to get singleton, sharedStore is made to point to nil.
Code works fine, so definitely there is nothing wrong with it. Does this mean if variable is static static BNRImageStore *sharedStore = nil; will be ignored.
Thanks in advance and above code is taken from the book I am reading "IOS Programming: The BNR Guide".
A:
the issue is that the sharedStore is declared static and NOT a local variable. A static variable is never destroyed. Static variables do not live on the stack and thus setting it to nil doesn't destroy it. So, thus in the case you've shown here the setting it to nil doesn't do anything and it doesn't enter the conditional which will create it. It's a bit counter-intuitive but does work this way.
A simple way of showing this static nature is provided in the code here: Why should you check a static variable for nil if it was initialized to nil on the previous line? namely:
void plugh(void) {
static int xyzzy = 0;
printf (" %d", xyzzy); // or Obj-C equivalent.
xyzzy++;
}
and calling it 100 times will produce:
0 1 2 3 4 ...
There's another way to vend a singleton using dispatch_once. An example is provided here with the sharedWeatherHTTPClient http://www.raywenderlich.com/59255/afnetworking-2-0-tutorial
|
[
"stackoverflow",
"0048018560.txt"
] | Q:
how to Validate Multiple TextBoxes , combo box and datetime picker infragistics
We have a code to validate all textbox below:
For Each ctl As Control In Controls
If TypeOf ctl Is Infragistics.Win.UltraWinEditors.UltraTextEditor AndAlso ctl.Text = "" Then
ctl.Focus()
MsgBox(ctl.Name)
End If
Next
Here we need to get all infragistics controls.
Or else suggest us to validate all the infragistics controls such as textbox, date time picker, combo.
A:
I got links how to validate numerous infragistics controls
https://www.infragistics.com/help/winforms/winvalidator
https://www.infragistics.com/help/winforms/winvalidator-validate-a-group-of-controls
https://www.infragistics.com/help/winforms/winvalidator-validate-all-controls-associated-with-winvalidator
https://www.infragistics.com/help/winforms/winvalidator-determine-if-a-value-is-in-a-specified-list
https://www.infragistics.com/help/winforms/winvalidator-validate-during-a-specific-event
|
[
"robotics.stackexchange",
"0000007470.txt"
] | Q:
7DOF inverse kinematics spherical wrist
Is it possible to apply kinematic decoupling for a 7 DOF 7R manipulator with spherical wrist? If it is possible, can anyone suggest a reference on how to apply this approach with a redundant manipulator with spherical wrist, or explain why it is not possible?
I'm working with Robotic Toolbox (matlab) and the numeric algorithm can find the inverse kinematics solution without a problem if I don't specify the orientation. And I was thinking about solving the problem a second time considering the spherical wrist. Will this approach work?
A:
I believe kinematic decoupling used to be the standard procedure for 6 DOF arms. (6R with spherical wrist). Where you would solve the 3 DOF position IK first, then 3 DOF orientation IK.
If you have a spherical wrist, I don't think there is any reason why you can't decouple your problem like this. However, I assume you now have a 4 DOF arm to reach a 3D point. You have 1 redundancy, so your IK will probably give you a number of solutions. So you should do your orientation IK on top of all these...
That being said, i don't believe anyone does it like this anymore. I know at least my kinematics library of choice (OpenRave) can solve 7 DOF IK problems. It does so by discretizing the extra DOF(s).
|
[
"stackoverflow",
"0009057886.txt"
] | Q:
(Beginner) How to get conditional statement to work in WordPress widget?
I am working on a WordPress widget and for some reason I can't get an if statement to work. I am trying to check to see if a variable is empty and if the variable is not empty than I want to display an image. If the variable is empty I do not want to show the image. Here is the statement:
if (empty($facebook)) {
echo '';
} else {
echo '<a href="'.$facebook.'"><img src="'.get_option('siteurl').'/wp-content/themes/SimplePhoto/widgets/facebook.png" /></a>';
}
Right now, when I run the widget, the Facebook icon shows up no matter what.
EDIT: Here is the code that builds the widget form and displays it on the front-end:
function form($instance) {
$defaults = array( 'title' => 'My Info', 'Facebook' => '', 'Twitter' => '' );
$instance = wp_parse_args( (array) $instance, $defaults );
$title = $instance['title'];
$facebook = $instance['facebook'];
$twitter = $instance['twitter'];
?>
<p>Title: <input class="widefat" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" /></p>
<p>Facebook: <input class="widefat" name="<?php echo $this->get_field_name( 'facebook' ); ?>" type="text" value="<?php echo esc_attr( $facebook ); ?>" /></p>
<p>Twitter: <textarea class="widefat" name="<?php echo $this->get_field_name( 'twitter' ); ?>" / ><?php echo esc_attr( $twitter ); ?></textarea></p>
<?php
}
//save the widget settings
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['title'] = strip_tags( $new_instance['title'] );
$instance['facebook'] = strip_tags( $new_instance['facebook'] );
$instance['twitter'] = strip_tags( $new_instance['twitter'] );
return $instance;
}
//display the widget
function widget($args, $instance) {
extract($args);
echo $before_widget;
$title = apply_filters( 'widget_title', $instance['title'] );
$facebook = empty( $instance['facebook'] ) ? ' ' : $instance['facebook'];
$twitter = empty( $instance['twitter'] ) ? ' ' : $instance['twitter'];
if ( !empty( $title ) ) { echo $before_title . $title . $after_title; };
if (empty($facebook)) {
echo '';
} else {
echo '<a href="'.$facebook.'"><img src="'.get_option('siteurl').'/wp-content/themes/SimplePhoto/widgets/facebook.png" /></a>';
}
echo $after_widget;
}
}
A:
do this
$facebook = empty( $instance['facebook'] ) ? '' : $instance['facebook'];
|
[
"stackoverflow",
"0036013594.txt"
] | Q:
How do I use a setTimeout function on some images?
I am creating a game using javascript, it starts off with six blurred images, once the image is selected it shows the unblurred image. I am wanting the unblurred images to be shown for 2 seconds, it then needs to go back to the blurred image.
The code I have works fine, however when I have tried to create a setTimeout function the images dont change anymore. I have tried to create it as an array and have the time at the end but it didnt work. I have also tried putting a time at the end of the showpicture function but again it didnt work. Can someone please help me create the setTimeout function.
My working code is below:
<!DOCTYPE html>
<html>
<head>
<title> Who Am I? </title>
<script type="text/javascript">
var imageone = document.getElementById("Zero");
var imagetwo = document.getElementById("One");
var imagethree = document.getElementById("Two");
var imagefour = document.getElementById("Three");
var imagefive = document.getElementById("Four");
var imagesix = document.getElementById("Five");
function init() {
init1();
init2();
init3();
init4();
init5();
init6();
};
function init1 () {
var imageone = document.getElementById("Zero");
imageone.onclick = showAnswerone;
}
function init2 () {
var imagetwo = document.getElementById("One");
imagetwo.onclick = showAnswertwo;
}
function init3 () {
var imagethree = document.getElementById("Two");
imagethree.onclick = showAnswerthree;
}
function init4 () {
var imagefour = document.getElementById("Three");
imagefour.onclick = showAnswerfour;
}
function init5 () {
var imagefive = document.getElementById("Four");
imagefive.onclick = showAnswerfive;
}
function init6 () {
var imagesix = document.getElementById("Five");
imagesix.onclick = showAnswersix;
}
window.onload = init;
function showAnswerone () {
var imageone = document.getElementById("Zero");
init1();
imageone.src="Zero.jpg";
}
function showAnswertwo () {
var imagetwo = document.getElementById("One");
init2();
imagetwo.src="One.jpg";
}
function showAnswerthree () {
var imagethree = document.getElementById("Two");
init3();
imagethree.src="Two.jpg";
}
function showAnswerfour () {
var imagefour = document.getElementById("Three");
init4();
imagefour.src="Three.jpg";
}
function showAnswerfive () {
var imagefive = document.getElementById("Four");
imagefive.src="Four.jpg";
}
function showAnswersix () {
var imagesix = document.getElementById("Five");
init5();
imagesix.src="Five.jpg";
}
function submitForm()
{
var var_one = 0, var_two = 0, var_three = 0;
var var_four = 0, var_five = 0, var_six = 0;
}
function var_oneb(){
var_one=5;
return true;
}
function var_onea(){
var_one=0;
return true;
}
function var_twob(){
var_two=5;
return true;
}
function var_twoa(){
var_two=0;
return true;
}
function var_threeb(){
var_three=5;
return true;
}
function var_threea(){
var_three=0;
return true;
}
function var_fourb(){
var_four=5;
return true;
}
function var_foura(){
var_four=0;
return true;
}
function var_fiveb(){
var_five=5;
return true;
}
function var_fivea(){
var_five=0;
return true;
}
function var_sixb(){
var_six=5;
return true;
}
function var_sixa(){
var_six=0;
return true;
}
function results_addition() {
var var_results=var_one+var_two+var_three+var_four+var_five+var_six;
if(var_results<=29){
document.getElementById('choice1').value="Not all answers are correct";
}
else{
if(var_results>=30){
document.getElementById('choice1').value="All answers are correct";
}
else{
document.getElementById('choice1').value="All answers are correct";
}
}
}
</script>
<style>
body {
background-color: #ff0000;
}
div#grid {
position: relative;
width: 500px;
height: 300px;
margin-left: 50;
margin-right: 50;
}
table {
border-spacing: 0px;
position: absolute;
left: 40px;
top: 40px;
border-collapse: collapse;
padding: 0px;
margin: 0px;
}
td {
border: 1px solid white;
text-align: center;
width: 160px;
height: 110px;
vertical-align: middle;
align-content: stretch;
padding: 5px;
margin: 0px;
}
h2 {
font-family: verdana, arial;
text-align: center;
color: white;
font-size: 30px;
}
h3 {
font-family: verdana, arial;
text-align: center;
color: white;
font-size: 18px;
}
</style>
</head>
<body>
<div id="grid">
<h2> Who Am I? </h2>
<table>
<tr>
<td> <img id = "Zero" src = "Zeroblur.jpg"> </td>
<td> <img id = "One" src = "Oneblur.jpg"> </td>
<td> <img id = "Two" src = "Twoblur.jpg"> </td>
</tr>
<tr>
<td> <img id = "Three" src = "Threeblur.jpg"> </td>
<td> <img id = "Four" src = "Fourblur.jpg"> </td>
<td> <img id = "Five" src = "Fiveblur.jpg"> </td>
</tr>
</table>
</div>
<br><br><br><br><br><br><br><br>
<h3> I am a Rugby League Player. </h3>
<h3> Click on me to reveal my identity! </h3>
<br>
<h3>Which Player am I</h3>
<hr>
<form action="">
<h3>Player 1 </h3>
<center>
<h3>
Shaun Johnson <INPUT TYPE="radio" NAME="Ra1" VALUE="0" onclick="var_onea()">
Sonny Bill Williams <INPUT TYPE="radio" NAME="Ra1" VALUE="5" onclick="var_oneb()">
</h3>
</center>
<br>
<hr>
<h3>Player 2 </h3>
<center>
<h3>
Gareth Widdop <INPUT TYPE="radio" NAME="Ra2" VALUE="0" onclick="var_twoa()">
Sam Tomkins <INPUT TYPE="radio" NAME="Ra2" VALUE="5" onclick="var_twob()">
</h3>
</center>
<br>
<hr>
<h3>Player 3 </h3>
<center>
<h3>
James Graham <INPUT TYPE="radio" NAME="Ra3" VALUE="5" onclick="var_threea()">
Sam Burgess <INPUT TYPE="radio" NAME="Ra3" VALUE="10" onclick="var_threeb()">
</h3>
</center>
<br>
<hr>
<h3>Player 4 </h3>
<center>
<h3>
Matthew Scott <INPUT TYPE="radio" NAME="Ra4" VALUE="5" onclick="var_foura()">
Johnathon Thurston <INPUT TYPE="radio" NAME="Ra4" VALUE="10" onclick="var_fourb()">
</h3>
</center>
<br>
<hr>
<h3>Player 5 </h3>
<center>
<h3>
Neil Lowe <INPUT TYPE="radio" NAME="Ra5" VALUE="5" onclick="var_fivea()">
Danny Brough <INPUT TYPE="radio" NAME="Ra5" VALUE="10" onclick="var_fiveb()">
</h3>
</center>
<br>
<hr>
<h3>Player 6 </h3>
<center>
<h3>
Mitch Garbutt <INPUT TYPE="radio" NAME="Ra6" VALUE="5" onclick="var_sixa()">
Ryan Hall <INPUT TYPE="radio" NAME="Ra6" VALUE="10" onclick="var_sixb()">
</h3>
</center>
<br>
<hr>
<br>
<center>
<INPUT TYPE="button" VALUE="Calculate" onclick="results_addition()"> Your Score:
<INPUT TYPE="text" id="choice1" NAME="choice1" VALUE="" SIZE=30>
</center>
</form>
</body>
</html>
A:
To display the unblurred images and then switch back to the blurred ones use this (four in this example):
function showAnswerfive () {
var imagefive = document.getElementById("Four");
imagefive.src="Four.jpg";
setTimeout (function() {
imagefive.src="Fourblur.jpg";
},2000);
}
EDIT:
Also, you can optimize those function, basically chunk down to one function, and store the pictures like so:
JS:
function showAnswerById (id) {
var imagefive = document.getElementById(id);
var blurredImage = imagefive.getAttribute("blurred-src");
var unBlurredImage = imagefive.getAttribute("unblurred-src");
imagefive.src=unBlurredImage;
setTimeout (function() {
imagefive.src=blurredImage ;
},2000);
}
HTML:
<img id="Zero" blurred-src="Zeroblur.jpg" unblurred-src="Zero.jpg" src="Zeroblur.jpg">
|
[
"stackoverflow",
"0027358902.txt"
] | Q:
Copy/paste and creating folder in android
I want to copy file from one folder to the other folder (for example : sdcard0/folder1/a.text to sdcard0/folder2 ). I have seen a lot of sample code in this site and other sites but non of them work for me . I don't know where is my problem. I also add permission to the manifest file.
what should I do?
I have several method for this, that I named them from copy1 to copy3 .
//----------Method 1
public void copy1(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
//----------Method 2
public void copy2(File src, File dst) throws IOException {
FileInputStream inStream = new FileInputStream(src);
FileOutputStream outStream = new FileOutputStream(dst);
FileChannel inChannel = inStream.getChannel();
FileChannel outChannel = outStream.getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);
inStream.close();
outStream.close();
}
//----------Method 3
public static boolean copy3(File source, File dest){
try{
// Declaration et ouverture des flux
java.io.FileInputStream sourceFile = new java.io.FileInputStream(source);
try{
java.io.FileOutputStream destinationFile = null;
try{
destinationFile = new FileOutputStream(dest);
// Lecture par segment de 0.5Mo
byte buffer[] = new byte[512 * 1024];
int nbLecture;
while ((nbLecture = sourceFile.read(buffer)) != -1){
destinationFile.write(buffer, 0, nbLecture);
}
} finally {
destinationFile.close();
}
} finally {
sourceFile.close();
}
} catch (IOException e){
e.printStackTrace();
return false; // Erreur
}
return true; // Résultat OK
}
and I use them like this:
String path=Environment.getExternalStorageDirectory().toString();
File f= new File(path +"/folder1/a.txt");
File f2= new File(path+"/folder2/" );
try{
copy1(f,f2);
}
catch(Exception e){}
and also for creating Directory :
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/AAAli");
if(!dir.exists()) {
dir.mkdirs(); // build directory
}
A:
String sourcePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/yourFolder1/yourFile.png";
File source = new File(sourcePath);
String destinationPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/yourFolder2/yourFile.png";
File destination = new File(destinationPath);
try
{
FileUtils.copyFile(source, destination);
}
catch (IOException e)
{
e.printStackTrace();
}
|
[
"stackoverflow",
"0059475343.txt"
] | Q:
JavaScript Filter() function with multiple parameters or keywords
I have one object of list of products and I have created one array to apply filter function to get parameter from that array. Like below
var selectedProducts = ['music', 'dance']
var products = [
{
ID : 1,
name : "pro1",
category : "music"
},
{
ID : 2,
name : "pro2",
category : "yoga"
},
{
ID : 3,
name : "pro3",
category : "music"
},
{
ID : 4,
name : "pro4",
category : "dance"
},
]
function filterFunction(){
return products.filter((abc) => {
selectedProducts.forEach(function(item, index){
return abc.category == selectedProducts[index]
});
});
}
What I am trying to do is when user select any checkbox, selected values will be stored in selectedProducts[] array and then on those values filter function will be called and array will be passed as paramater with forEach method. Code works fine on each iteration of loop but at the end it return me empty array of object. Is anything wrong with my code?
A:
Returning true from your forEach() loop's callback function will not have any effect on the filter condition.
Here's an alternative approach using Array.prototype.includes():
products.filter(({category}) => selectedProducts.includes(category));
Full snippet:
const selectedProducts = ['music', 'dance']
const products = [
{
ID : 1,
name : "pro1",
category : "music"
},
{
ID : 2,
name : "pro2",
category : "yoga"
},
{
ID : 3,
name : "pro3",
category : "music"
},
{
ID : 4,
name : "pro4",
category : "dance"
},
]
function filterFunction(){
return products.filter(({category}) => selectedProducts.includes(category));
}
console.log(filterFunction());
|
[
"stackoverflow",
"0009967900.txt"
] | Q:
Android and drawing star picture
I draw picture in canvas in place where I click. This is code:
public class CanvasdrawActivity extends Activity implements OnTouchListener {
ImageView imageView;
Bitmap bitmap;
Bitmap bitmap2;
Canvas canvas;
Paint paint;
float downx = 0,downy = 0,upx = 0,upy = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView = (ImageView) this.findViewById(R.id.imageView1);
Display currentDisplay = getWindowManager().getDefaultDisplay();
float dw = currentDisplay.getWidth();
float dh = currentDisplay.getHeight();
bitmap = Bitmap.createBitmap((int) dw, (int) dh,
Bitmap.Config.ARGB_8888);
bitmap2=BitmapFactory.decodeResource(getResources(),
R.drawable.star_bez_nog);
canvas = new Canvas(bitmap);
imageView.setImageBitmap(bitmap);
imageView.setOnTouchListener(this);
}
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
downx = event.getX();
downy = event.getY();
canvas.drawBitmap(bitmap2, downx, downy, null);
imageView.invalidate();
break;
}
return true;
}
}
How I can draw this picture only one time. when I click ffirst time star was drawn and when i click in other place nothing happen. draw should work only first click.
A:
Set a boolean.
Canvas canvas;
Paint paint;
Boolean drawOnlyOnce = true;
public boolean onTouch(View v, MotionEvent event) {
...
if (drawOnlyOnce) {
canvas.drawBitmap(bitmap2, downx, downy, null);
imageView.invalidate();
drawOnlyOnce = false;
}
...
|
[
"stackoverflow",
"0023326539.txt"
] | Q:
JLabel force text to fit the JLabel bounds (null layout)
i'm working with layout set to null, i have a JFrame with an aspect ratio and during the resize, this frame keep the same aspect ratio.
Every time i resize the frame i resize all my components without any problems just one with JLabel.
When i resize the bounds of a JLabel the text don't increase to fit the new bounds, the text stay at the same size.
I'm trying to solve the problem by setting every time the font size but it seems to be difficult.
Is there a way to achieve that ?
A:
Have you tried working with a particular layout that lets you maintain the aspect ratio? Such as GridbagLayout?
Use an appropriate Layout such as GridBagLayout or SpringLayout
example:
Container contentPane = jframe.getContentPane();
contentPane.setLayout ( new GridBagLayout() );
// x y w h wtx wty anchor fill T L B R padx pady
contentPane.add( myPanel, new GridBagConstraints( 0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets( 10, 10, 10, 5 ), 0, 0 ) );
contentPane.add( myPanel2, new GridBagConstraints( 1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.BOTH, new Insets( 10, 5, 10, 10 ), 0, 0 ) );
You also would like labels, etc. to be expanded as well. Hmm, I don't know of anything that will do this automatically for you. You could extend some of the components to take hints from the layout and re size appropriately. For instance, you may choose to enlarge the font when you determine more white space is available due to a window re size. I'm not aware of existing component that will do this for labels. Proportional fonts are a bit tricky to get this right. Actually, if memory serves me, I once did something similar. It was like "trial-and-error" pro-grammatically. Off screen, I would draw the character string in the estimated font size and redraw down until it fit in the allotted space with the desired margins. Sure seems like a lot of trouble to get these dynamic labels to look good!
|
[
"english.stackexchange",
"0000339247.txt"
] | Q:
Difference in pronunciation of "a team" and "A team"?
I noticed that I pronounce the A differently based on the intended meaning:
I belong to the A-team. (like ey in they)
and
I belong to a team. (like a in apple)
Are the pronunciations supposed to be different or is it an artifact of how I have learned to pronounce the alphabet and the article?
A:
In this case, when the vowel a is pronounced long and capitalized, A is an ordinal. The A Team is superior to the B Team. (you rarely hear about the C or later teams.)
A-team: A group of elite soldiers or the top advisers or workers in an organization.
Oxford Dictionaries Online
B-team is usually derogatory
Derived from high school varsity and junior varsity sports, where the "B Team" is made up of the stragglers and uncoordinated losers. Used in a situation in which someone drops, breaks, messes up, stutters during an insult, or just acts a fool.
Urban Dictionary
There was a television show in the US for several years called The A-Team. They were a group of very effective, but unconventional heroes who solved intractable problems (usually with both force and guile). Wikipedia
Although many dictionaries offer a long a pronunciation for the indefinite article, in common speech it is almost always pronounced short, as a schwa.
Oxford Dictionaries Online
A:
The article a is pronounced in many ways, but it is rare to pronounce the letter A in any way besides the ay from "play". Using the International Phonetic Alphabet, the capital A is almost always pronounced as /eɪ/. The article a may be prounounced as /eɪ/ ("play"), or it may be relaxed to /ʌ/ ("run"). (Note: some feel this is better represented as /ə/, which is an unvoiced vowel such as "comma", but its not agreed whether there is even a difference in English phonology, so if "run" and "comma" appear to have the same pronunciation to you, don't worry about this detail.)
In general, you will find English speakers relax a to be pronounced /ʌ/. However, you will find it pronounced /eɪ/ for emphatic reasons. You'll see this most often in cases where a sentence is worded ambiguously, and the extra stress on a will be used to draw the listeners attention to the fact that you're about to use the exact wording of their sentence very carefully.
|
[
"stackoverflow",
"0004814893.txt"
] | Q:
Calling the doPost in another Webapp with a Req Dispatcher forward
I have 2 web apps, no front-end(i.e html/Jsp) in either. Both have one servlet each.
Lets call them WebApp1/WebApp2 and ServiceServlet1/ServiceServlet2.
I have 2 war files, WebApp1.war and WebApp2.war and both deployed.
I call the ServiceServlet1 directly from the browser with -
http://localhost:8080/WebApp1/ServiceServlet1
Obviously the doGet method will be called(POST is associated only with FORM, correct me if I am wrong).
The ServiceServlet1 is build something like -
public class ServiceServlet1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
throws ServletException, IOException {
doPost(httpRequest, httpResponse);
}
@Override
protected void doPost(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws ServletException,
IOException {
RequestDispatcher requestDispatcher;
try {
// Process something
requestDispatcher = getServletContext().getRequestDispatcher("/WebApp2/ServiceServlet2");
requestDispatcher.forward(httpServletRequest, httpServletResponse);
} catch (IOException ioException) {
ioException.printStackTrace();
} catch (ServletException servletException) {
servletException.printStackTrace();
}
}
}
Essentially, what I require is to call the doPost() of ServiceServlet2
I have tried few different ways with httpReq.getRequestDispatcher(), sendRedirect etc. but have failed so far.
So how can I make it happen?
Thank you.
A:
In addition to the answer of ckuetbach, you can't change the request method when dispatching the request. If the second servlet cannot be changed to execute the same business logic on doGet() as well, then you have to fire a POST request yourself programmatically.
HttpURLConnection connection = (HttpURLConnection) new URL("http://localhost/WebApp2/ServiceServlet2").openConnection();
connection.setRequestMethod("POST");
InputStream response = connection.getInputStream();
// ... Write to OutputStream of your HttpServletResponse?
See also:
How to use URLConnection to fire and handle HTTP requests?
|
[
"stackoverflow",
"0027769583.txt"
] | Q:
Calling clear() on ObservableList causes IndexOutOfBoundsException
I have a ComboBox with an observablelist which is updated as the user types in characters or makes a selection. The issue I am having is caused when I select an item from the ComboBox and my listener event is called which then calls the clear() method from the ComboBox's ObservableList.
FULL CODE
public void suggestItem(ActionEvent ev){
String currentInput = foodSearch.getEditor().getText();
if(currentInput.length() > 4){
DatabaseCommunicator.openConnection();
// Returns a list no greater than size 5 of possible food items
ArrayList<String> foodList = DatabaseCommunicator.findSimilarFoods(currentInput);
ObservableList<String> comboList = foodSearch.getItems();
comboList.setAll(foodList);
DatabaseCommunicator.closeConnection();
}
}
Now when I get the error, the ObservableList appears as it should, but I still get this exception. Trying to debug this caused my IDE to freeze after the call to setAll which runs the clear() and I had to kill the IDE via terminal.
If I replace the setAll with addAll which does not clear() I get no exceptions thrown and my list is updated with the clicked item re-added.
I couldn't catch the exception in the Listener which I expected from seeing the stack trace but wanted to try it anyway.
Here is the stacktrace.
Exception in thread "JavaFX Application Thread" java.lang.IndexOutOfBoundsException
at com.sun.javafx.scene.control.ReadOnlyUnbackedObservableList.subList(ReadOnlyUnbackedObservableList.java:136)
at javafx.collections.ListChangeListener$Change.getAddedSubList(ListChangeListener.java:242)
at com.sun.javafx.scene.control.behavior.ListViewBehavior.lambda$new$178(ListViewBehavior.java:264)
at com.sun.javafx.scene.control.behavior.ListViewBehavior$$Lambda$321/1588822558.onChanged(Unknown Source)
at javafx.collections.WeakListChangeListener.onChanged(WeakListChangeListener.java:88)
at com.sun.javafx.collections.ListListenerHelper$Generic.fireValueChangedEvent(ListListenerHelper.java:329)
at com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(ListListenerHelper.java:73)
at com.sun.javafx.scene.control.ReadOnlyUnbackedObservableList.callObservers(ReadOnlyUnbackedObservableList.java:75)
at javafx.scene.control.MultipleSelectionModelBase.clearAndSelect(MultipleSelectionModelBase.java:331)
at javafx.scene.control.ListView$ListViewBitSetSelectionModel.clearAndSelect(ListView.java:1385)
at com.sun.javafx.scene.control.behavior.CellBehaviorBase.simpleSelect(CellBehaviorBase.java:260)
at com.sun.javafx.scene.control.behavior.CellBehaviorBase.doSelect(CellBehaviorBase.java:224)
at com.sun.javafx.scene.control.behavior.CellBehaviorBase.mousePressed(CellBehaviorBase.java:150)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:95)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3719)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3447)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1723)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2456)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:350)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:275)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$347(GlassViewEventHandler.java:385)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$$Lambda$169/414422402.get(Unknown Source)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:387)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:384)
at com.sun.glass.ui.View.handleMouseEvent(View.java:549)
at com.sun.glass.ui.View.notifyMouse(View.java:921)
at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
at com.sun.glass.ui.gtk.GtkApplication.lambda$null$48(GtkApplication.java:139)
at com.sun.glass.ui.gtk.GtkApplication$$Lambda$42/1091223379.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
A:
It's something of a hack, but
Platform.runLater(() -> {
ObservableList<String> comboList = foodSearch.getItems();
comboList.setAll(foodList);
}
seems to fix it. I think the issue is that you are modifying the list while the selection model is changing the selectedItems list, which violates a rule on not changing an observable list during notifications. Using the Platform.runLater(...) delays your modification until after the current event has been fully handled.
|
[
"serverfault",
"0000674444.txt"
] | Q:
Blocking spam with SpamAssassin
I have a server that runs websites and exim for e-mail. I've added countless RBLs including barracuda to try and cut back on incoming spam. However, they still keep coming in. The clients use RoundCube. Is there a way for them to submit e-mails as spam or something?
Are there any other ways I could try and cut down on the incoming spam?
A:
See also How to block IP addresses from port 25
Spambots are generally poorly configured. In particular rDNS validation fails. Most (unfortuneately not all) legitimate servers have rDSN correctly configured. This allows you to make life difficult for spambots by delaying responses for poorly configured servers. Exim allows you to do this fairly easily.
Setup ACLs for Connection, HELO, and preData .
add a warn clause with a delay for hosts which fail to the new ACLs, and the exiting mail and recipient.
This is a simple ACL clause similar to what I use (try different times):
warn
!verify = reverse_host_lookup
delay = 16s
You may want to add 'control = no_pipelining' to the connection ACL.
WARNING: Some large legitimate mail servers (banks, governments, airlines, couriers) are poorly configured and will get caught in this. You may want to whitelist them as you discover them. Some of these will fail deliveries if the timeout is too long. The RFCs specify timeouts in minutes, but the timeouts I have seen tend to be well under a minute. This is a more complex ACL clause with a white list:
warn
!verify = reverse_host_lookup
!hosts = ${if exists{CONFDIR/local_host_delay_whitelist}\
{CONFDIR/local_host_delay_whitelist}{}}
delay = 16s
|
[
"stackoverflow",
"0038236055.txt"
] | Q:
How to write to a txt file ascii characters in python?
I'm implementing a XOR method, and I want to write the ciphered message to a txt file, but in the way I'm doing it, I get strange characters instead of the message.
Here is the code:
from itertools import cycle
msg = 'RUNNINGFAST'
key = 'SADSTORY'
cipher = ''.join(chr(ord(c)^ord(k)) for c,k in zip(msg, cycle(key)))
print('%s ^ %s = %s ' % (msg, key, cipher))
msg = ''.join(chr(ord(c)^ord(k)) for c,k in zip(cipher, cycle(key)))
print('%s ^ %s = %s ' % (cipher, key, msg))
with open("XOR - Msg_Cipher.txt", "w",) as text_file:
text_file.write("msg: %s \nCipher: %s" % (msg, cipher))
the output looks like this:
the txt file looks like this:
How can I get the output inside the txt file?
Thanks for your help
A:
I think you need to use another text editor.
Windows' notepad doesn't render the control characters correctly.
Try to use Programmers Notepad or Notepad++ for example.
|
[
"stackoverflow",
"0007852207.txt"
] | Q:
Dropdown list to filter gridview
I would like my gridview to be filtered by the dropdown list I have. It is pulling specific information from the database, so when you choose a value from the dropdown list, it should search through all the records and find only records with the ddl value in them.
The code that I am using in the codebehind for the SelectedIndexChanged is not right though. I get an error message saying 'Value' is not a member of 'Integer'. This is on the line dsCompanyFilter.SelectParameters.Add
It probably has something to do with the gridview not tying to the dropdown list properly, but I am not sure how to fix that code. Please help!
<asp:Content ID="Content2" ContentPlaceHolderID="body" Runat="Server"><br /><br /><br />
<asp:linkbutton id="btnAll" runat="server" text="ALL" onclick="btnAll_Click" />
<asp:repeater id="rptLetters" runat="server" datasourceid="dsLetters">
<headertemplate>
|
</headertemplate>
<itemtemplate>
<asp:linkbutton id="btnLetter" runat="server" onclick="btnLetter_Click"
text='<%#Eval("Letter")%>' />
</itemtemplate>
<separatortemplate>
|
</separatortemplate>
</asp:repeater>
<asp:sqldatasource id="dsLetters" runat="server" connectionstring="<%$
ConnectionStrings:ProductsConnectionString %>"
selectcommand="SELECT DISTINCT LEFT(ProductName, 1) AS [Letter] FROM [Product]">
</asp:sqldatasource>
Filter By Company:<asp:DropDownList ID="ddlCompany" runat="server"
DataSourceID="dsCompanyFilter" DataTextField="CompanyName" DataValueField="CompanyID">
</asp:DropDownList>
<asp:gridview id="gvProducts" runat="server" AutoGenerateColumns="False"
datakeynames="ProductID" datasourceid="dsProductLookup"
style="margin-top: 12px;">
<Columns>
<asp:BoundField DataField="ProductName" HeaderText="ProductName"
SortExpression="ProductName" />
</Columns>
</asp:gridview>
<asp:sqldatasource id="dsProductLookup" runat="server" connectionstring="<%$
ConnectionStrings:ProductsConnectionString %>"
Selectcommand="SELECT ProductID, ProductName FROM [Product] ORDER BY [ProductName]">
</asp:sqldatasource>
<asp:SqlDataSource ID="dsCompanyFilter" runat="server"
ConnectionString="<%$ ConnectionStrings:ProductsConnectionString %>"
SelectCommand="SELECT [CompanyName], [CompanyID] FROM [Company]">
</asp:SqlDataSource>
</asp:Content>
This code filters the results in the gridview by Letter and the Dropdown. The problem is with the dropdown list filtering the gridview.
Protected Sub btnLetter_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim btnLetter As LinkButton = TryCast(sender, LinkButton)
If btnLetter Is Nothing Then
Return
End If
dsProductLookup.SelectCommand = [String].Format("SELECT ProductID, ProductName
FROM [Product]
WHERE ([ProductName] LIKE '{0}%')
ORDER BY [ProductName]", btnLetter.Text)
End Sub
This is the part that has the problem. I now get the error, must declare the scalar variable @CompanyID
Protected Sub ddlCompany_SelectedIndexChanged(ByVal sender As Object, ByVal e As
System.EventArgs) Handles ddlCompany.SelectedIndexChanged
dsProductLookup.SelectCommand = "SELECT ProductName, CompanyID, CompanyName
FROM Product, Company
WHERE CompanyID = @CompanyID
ORDER BY ProductName"
dsProductLookup.SelectParameters.Add("@CompanyID", DbType.Int32,
ddlCompany.SelectedValue)
End Sub
A:
Deleted my previous answer.
Actually try the following :
dsProductLookup.SelectParameters.Add("@ProductID",
DbType.Int32, ddlCompany.SelectedValue)
No assignment to value as it is part of the Add. Noticed this when I tried to compile a test of my previous answer which didn't work.
EDIT: I tried the above code and it worked (did it in C#) but changed it to use DbType.Int32 for second param.
|
[
"stackoverflow",
"0055176915.txt"
] | Q:
Integrating c++ and qml
Okay I'm resetting this whole post because I guess I didn't have enough " Minimal, Complete, and Verifiable example " which really is the entirety of my question, because I am just so LOST on slots and signals.. so here's 2nd attempt, I will leave out flower.cpp, but know it has a function in there
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickView>
#include <QtQuick>
#include <QNetworkAccessManager>
#include <iostream>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
#include <QNetworkReply>
#include <QObject>
#include "flower.h"
void Flower::onClicked(){
//code i've been trying to test all day
}
flower.h (my header for the class flower (the function))
#ifndef FLOWER_H
#define FLOWER_H
#include <QObject>
class Flower
{
private slots:
void onClicked();
};
#endif // FLOWER_H
main.cpp (this is where my app QML is started from, and I'm trying to setup the connection of signal and slot there)
QQuickView home;
home.setSource(QUrl::fromLocalFile("main.qml"));
home.show();
QObject *homePa = home.rootObject();
QObject *buttF = homePa->findChild<QObject*>("buttFObject");
QObject::connect(buttF, SIGNAL(qmlClick()), buttF,
SLOT(Flower.onClicked()));
this is the navmenu with the mousearea that I want to have the onClicked: command attached
Rectangle {
signal qmlClick();
id: navMenu
color: "#00000000"
radius: 0
anchors.fill: parent
z: 3
visible: false
border.width: 0
transformOrigin: Item.Center
MouseArea {
id: buttFArea
objectName: buttFObject
anchors.fill: parent
onClicked: navMenu.qmlClick()
}
}
When I try to run right now I receive this error "W libAHDP.so: QObject::connect: Cannot connect (null)::qmlClick() to (null)::Flower.onClicked()"
Apologies for my first post being very misleading and mixed up I hope this is more clear on what my issue is
A:
Only QObjects can have slots so Flower must inherit from QObject. On the other hand you are using an approach that always brings problems that is to try to obtain a QML element from C++, instead you must export the C++ element to QML using setContextProperty():
flower.h
#ifndef FLOWER_H
#define FLOWER_H
#include <QObject>
class Flower : public QObject
{
Q_OBJECT
public:
explicit Flower(QObject *parent = nullptr);
Q_SLOT void onClicked();
};
#endif // FLOWER_H
flower.cpp
#include "flower.h"
#include <QDebug>
Flower::Flower(QObject *parent) : QObject(parent)
{}
void Flower::onClicked()
{
qDebug()<< __PRETTY_FUNCTION__;
}
main.cpp
#include <QGuiApplication>
#include <QQuickView>
#include <QQmlContext>
#include "flower.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
Flower flower;
QQuickView view;
view.rootContext()->setContextProperty("flower", &flower);
view.setSource(QUrl(QStringLiteral("qrc:/main.qml")));
view.show();
return app.exec();
}
main.qml
import QtQuick 2.9
Rectangle {
color: "#00000000"
anchors.fill: parent
transformOrigin: Item.Center
MouseArea {
id: buttFArea
anchors.fill: parent
onClicked: flower.onClicked()
}
}
For more information I recommend reading Best Practices for QML and Qt Quick
|
[
"stackoverflow",
"0053347352.txt"
] | Q:
R: How can I group rows in a dataframe, ID rows meeting a condition, then delete prior rows for the group?
I have a dataframe of customers (identified by ID number), the number of units of two products they bought in each of four years, and a final column identifying the year in which new customers first purchased (the 'key' column). The problem: the dataframe includes rows from the years prior to new customers purchasing for the first time. I need to delete these rows. For example, this dataframe:
customer year item.A item.B key
1 1 2000 NA NA <NA>
2 1 2001 NA NA <NA>
3 1 2002 1 5 new.customer
4 1 2003 2 6 <NA>
5 2 2000 NA NA <NA>
6 2 2001 NA NA <NA>
7 2 2002 NA NA <NA>
8 2 2003 2 7 new.customer
9 3 2000 2 4 <NA>
10 3 2001 6 4 <NA>
11 3 2002 2 5 <NA>
12 3 2003 1 8 <NA>
needs to look like this:
customer year item.A item.B key
1 1 2002 1 5 new.customer
2 1 2003 2 6 <NA>
3 2 2003 2 7 new.customer
4 3 2000 2 4 <NA>
5 3 2001 6 4 <NA>
6 3 2002 2 5 <NA>
7 3 2003 1 8 <NA>
I thought I could do this using dplyr/tidyr - a combination of group, lead/lag, and slice (or perhaps filter and drop_na) but I can't figure out how to delete backwards in the customer group once I've identified the rows meeting the condition "key"=="new.customer". Thanks for any suggestions (code for the full dataframe below).
a<-c(1,1,1,1,2,2,2,2,3,3,3,3)
b<-c(2000,2001,2002,2003,2000,2001,2002,2003,2000,2001,2002,2003)
c<-c(NA,NA,1,2,NA,NA,NA,2,2,6,2,1)
d<-c(NA,NA,5,6,NA,NA,NA,7,4,4,5,8)
e<-c(NA,NA,"new",NA,NA,NA,NA,"new",NA,NA,NA,NA)
df <- data.frame("customer" =a, "year" = b, "C" = c, "D" = d,"key"=e)
df
A:
As a first step I am marking existing customers (customer 3 in this case) in the key column -
df %>%
group_by(customer) %>%
mutate(
key = as.character(key), # can be avoided if key is a character to begin with
key = ifelse(row_number() == 1 & (!is.na(C) | !is.na(D)), "existing", key)
) %>%
filter(cumsum(!is.na(key)) > 0) %>%
ungroup()
# A tibble: 7 x 5
customer year C D key
<dbl> <dbl> <dbl> <dbl> <chr>
1 1 2002 1 5 new
2 1 2003 2 6 NA
3 2 2003 2 7 new
4 3 2000 2 4 existing
5 3 2001 6 4 NA
6 3 2002 2 5 NA
7 3 2003 1 8 NA
|
[
"stackoverflow",
"0015979770.txt"
] | Q:
Using token from ASP.NET application to access WCF service
I have the following scenario
I have an STS that issues my tokens,I have used it to federate my ASP.NET application , this application calls A WCF Service to perform some need functionality.
But when I inspect the ClaimsPrinicipal.Current in ASP.NET application I find it were sit correctly to the claims of the user which I used to access the STS.
But when I call the service from ASP.NET application and inspect ClaimsPricipal.Current I find it equals null.
As a workaround, I passed the ClaimsPricipal.Current from the ASP.NET application and I sit Thread.CurrentPricipal in the WCF service.
However , I don't feel that it is a correct approach.
So my questions are:
1)Why the ASP.NET claims principal is not like WCF principal ?
2)What is the correct approach to use the access token to access also the WCF service?
A:
The identit does not flow automatically to your backend service - you need to do identity delegation - or ActAs as it is often called in WIF speak.
Found this:
http://weblogs.asp.net/gsusx/archive/2010/07/02/enabling-wif-actas-via-configuration.aspx
This is for WIF 1.0 - there are more samples out there.
|
[
"gis.stackexchange",
"0000114722.txt"
] | Q:
Open Source Interpolation Service?
We are seeking an open source solution for dynamic (on the fly) IDW or Kriging points interpolation.
Basically we are looking for something similar to ArcGIS Spatial Analysis Service.
Interpolation can be performed in the browser or on the server side.
A:
How about using GDAL_Grid? Just pass the arguments over to GDAL and return the raster file or render it in the web browser.
It does IDW, Nearest neighbor, and averaging and has a robust set of input parameters.
|
[
"stackoverflow",
"0060998181.txt"
] | Q:
Return an object of random type in C#
I have a factory class and I'd like it to be able to return an object of random type. The type should be chosen from a predefined list of types.
So, something like:
public class NeutralFactory : NPCFactory
{
private List<Type> humanoids = new List<Type> { typeof(Dwarf), typeof(Fairy), typeof(Elf), typeof(Troll), typeof(Orc) };
private Random random = new Random();
public Creature CreateHumanoid(int hp = 100)
{
int index = random.Next(humanoids.Count);
return new humanoids[index]();
}
}
Sadly, this does now work.
I want to be able to pass arguments to the constructors, we can assume that they all have the same signature.
The only working way to do it I found is to use a switch statement and return a different object in each case:
public Creature CreateHumanoid(int hp = 100)
{
int index = random.Next(humanoids.Count);
switch (index)
{
case 0:
return new Dwarf(hp);
case 2:
return new Fairy(hp);
case 3:
return new Elf(hp);
case 4:
return new Troll(hp);
case 5:
return new Orc(hp);
default:
throw new Exception("This should not execute.");
}
}
I don't really like it though. Is there a better way to do it?
EDIT:
Here's what I ended up using:
private List<Func<int, string, Creature>> humanoids = new List<Func<int, string, Creature>> {
(hp, name) => new Fairy(hp, name),
(hp, name) => new Troll(hp, name),
};
private List<Func<int, Creature>> animals = new List<Func<int, Creature>> {
(hp) => new Wolf(hp)
};
public override Creature CreateHumanoid(int hp = 100, string name = null)
{
int index = random.Next(humanoids.Count);
return humanoids[index](hp, name);
}
public override Creature CreateAnimal(int hp = 100)
{
int index = random.Next(animals.Count);
return animals[index](hp);
}
I have found similar questions where () => function() syntax was used, but I did not understand it, I guess those are some kind of ad-hoc delegates?
Anyways, it works as I wanted and is pretty concise.
Here's a helpful MSDN page on the Func thing for any future readers:
https://docs.microsoft.com/en-us/dotnet/api/system.func-2?view=netframework-4.8
A:
You can sore function in a List.
public class NeutralFactory: NPCFactory
{
private List<Func<int, Creature>> humanoids = new List<Func<int, Creature>> {
hp=> new Dwarf(hp),
hp=> new Fairy(hp),
hp=> new Elf(hp),
hp=> new Troll(hp),
hp=> new Orc(hp)
};
private Random random = new Random();
public Creature CreateHumanoid(int hp = 100)
{
int index = random.Next(humanoids.Count);
return humanoids[index](hp);
}
}
|
[
"stackoverflow",
"0061068032.txt"
] | Q:
Mongoose $gte date search returns documents from before that date
I have a Mongoose schema/model with a property of completedSetup that is a Date type.
Project repo: https://github.com/rmgreenstreet/custom-forms
const mongoose = require('mongoose');
const passportLocalMongoose = require('passport-local-mongoose');
const Schema = mongoose.Schema;
const Location = require('./location');
const Response = require('./response');
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const crypto = require('crypto');
const forbiddenWords = ['realtor', 'realty', 'realestate', 'agent', 'broker', 'admin'];
const userSchema = new Schema({
firstname: {
type: String,
required: true
},
lastname: {
type: String,
required: true
},
username: String,
personalEmail:{
type:String,
required:true,
unique:true
},
role:{
type:String,
default:'User'
},
isCompanyAdmin: {
type:Boolean,
default: false
},
company: {
type:Schema.Types.ObjectId,
ref: 'Company'
},
location: {
type:Schema.Types.ObjectId,
ref: 'Location'
},
image: {
url: {
type:String,
default:'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_960_720.png'
},
public_id: String
},
isExpedited: {
type:Boolean,
default:false
},
isHidden: {
type:Boolean,
default:false
},
formAccessToken: {
type: String,
default: crypto.randomBytes(16).toString('hex')
},
completedSetup: Date,
responses: [
{
type:Schema.Types.ObjectId,
ref:'Response'
}
],
createAccountToken : {
type: String,
default: crypto.randomBytes(16).toString('hex')
},
resetPasswordToken : String,
resetPasswordExpires: Date,
created:{
type:Date,
default:Date.now()
}
});
userSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model('User',userSchema);
Querying by createdDate:
let beginDate = new Date();
beginDate.setMonth(beginDate.getMonth() - 6);
if (req.body.beginDate) {
beginDate = new Date(req.body.beginDate);
}
let endDate = new Date();
if (req.body.endDate) {
endDate = new Date(req.body.endDate);
}
const recentSetups = await User.find({completedSetup: {$gt: beginDate, $lte: endDate}});
This returns all Users, not just ones with the completedSetup between beginDate and endDate.
The strange thing is that the same query returns correctly on other schemas/models, but their dates are set differently.
On some models I have a created property that is set by default to Date.now(), that is set at creation, and the query returns those fine.
However seeding data for the completedSetup uses a pickaADate function that I've defined to choose a date sometime in the previous year, or in the current year up to the current month (this is a portfolio project still in development):
const fs = require('fs');
const faker = require('faker');
const crypto = require('crypto');
const Company = require('./models/company');
const Location = require('./models/location');
const User = require('./models/user');
const Form = require('./models/form');
const Question = require('./models/question');
const Response = require('./models/response');
const sampleImages = fs.readdirSync('./public/images/seeds');
function flipACoin() {
const yesOrNo = Math.floor(Math.random() *2);
// console.log(yesOrNo);
return yesOrNo;
}
async function pickADate() {
return new Promise((resolve, reject) => {
try {
const today = new Date();
const day = Math.ceil(Math.random() * 27);
// const thisOrLastYear = flipACoin();
const month = Math.ceil(Math.random() * today.getMonth())
const returnDate = new Date(today.getFullYear() - flipACoin(),month,day);
resolve(returnDate);
return;
} catch (err) {
console.log(`Error creating random date: ${err.message}`);
reject(Date.now());
return;
}
});
};
async function seedDefaultQuestions() {
try {
console.log('clearing all default questions from database')
await Question.deleteMany({});
} catch (err) {
console.log(err.message);
}
try {
console.log('adding default questions to database')
const defaultQuestionsJSON = await JSON.parse(await fs.readFileSync('./private/defaultQuestions.json'));
for (let question of defaultQuestionsJSON) {
// console.log(question);
await Question.create(question);
}
console.log(`${defaultQuestionsJSON.length} default questions added to database`);
} catch (err) {
console.log(err.message);
}
};
async function clearDatabase() {
console.log('Clearing database \n Clearing Companies');
await Company.deleteMany({});
console.log('All Companies deleted \n Clearing Locations');
await Location.deleteMany({});
console.log('All Locations deleted \n Clearing Users');
await User.deleteMany({role: {$ne:'owner'}});
console.log('All Users deleted \n Clearing Forms');
await Form.deleteMany({});
console.log('All forms deleted \n Clearing responses');
await Response.deleteMany({});
console.log('Database cleared');
};
async function seedDatabase() {
// const companyCount = Math.ceil(Math.random() * 200);
const companyCount = 10;
const defaultQuestions = await Question.find({isDefault:true});
async function createLocations(companyId) {
const locationCount = Math.ceil(Math.random() * 5);
let locationsArr = [];
for (let i = 0; i < locationCount; i++) {
let isPrimary = false;
if (i=== 0) {
isPrimary = true;
}
const randomImageIndex = Math.ceil(Math.random() * sampleImages.length);
const newLocation = await Location.create({
primary: isPrimary,
officeNumber: Math.ceil(Math.random() * 1000).toString(),
name: faker.company.companyName(),
phone: faker.phone.phoneNumber(),
fax: faker.phone.phoneNumber(),
address: {
streetNumber: Math.random(Math.ceil() * 1000),
streetName: faker.address.streetName(),
secondary: `Ste ${faker.random.alphaNumeric()}`,
city: faker.address.city(),
state: faker.address.stateAbbr(),
postal: faker.address.zipCode(),
country: 'USA'
},
website: faker.internet.url(),
images: [
{
secure_url:`/images/seeds/${sampleImages[randomImageIndex]}`
}
],
company: companyId,
created: await pickADate()
});
await newLocation.save();
newLocation.contacts = await createUsers(newLocation._id, companyId, 'Admin', (Math.ceil(Math.random() * 5)));
await newLocation.save();
console.log(`Location ${newLocation.name} created with ${newLocation.contacts.length} contacts`)
await createUsers(newLocation._id, companyId, 'User', (Math.ceil(Math.random() * 30)));
locationsArr.push(newLocation._id);
await newLocation.addDefaultForm();
}
return locationsArr;
};
async function createUsers(locationId, companyId, role, count) {
let contactsArr = [];
for (let i = 0; i < count; i++) {
const newFirstName = await faker.name.firstName();
const newLastName = await faker.name.lastName();
let newUser;
try {
newUser = await User.register({
firstname: newFirstName,
lastname: newLastName,
username: newFirstName+newLastName,
personalEmail: newFirstName+newLastName+'@test.com',
role: role,
company: companyId,
location: locationId,
formAccessToken: crypto.randomBytes(16).toString('hex'),
createAccountToken: crypto.randomBytes(16).toString('hex'),
created: await pickADate()
},'password');
} catch (err) {
if (err.message.includes('UserExistsError')) {
continue;
}
}
if(role === 'User');{
if(flipACoin()) {
newUser.responses.push(await createResponse(newUser));
await newUser.save();
} else {
continue;
}
if(flipACoin()) {
newUser.completedSetup = await pickADate();
await newUser.save();
} else {
continue;
}
};
contactsArr.push(newUser._id);
console.log(`${role} ${newUser.firstname} ${newUser.lastname} created`);
};
return contactsArr;
};
async function createResponse(user) {
return new Promise(async (resolve, reject) => {
console.log(`Creating a response for ${user.firstname}`)
const makeString = (charLimit) => {
let str = faker.lorem.paragraph()
if (str.length > charLimit) {
str = str.slice(0, charLimit - 1)
}
return str
}
let response = await Response.create({owner:user._id, created:await pickADate()});
try {
for (let question of defaultQuestions) {
const answer = {
questionId: question._id
}
if(question.inputType == 'Checkbox') {
answer.value = true;
}
if(question.inputType == 'Email') {
answer.value = faker.internet.email();
}
if(question.inputType == 'File') {
continue;
}
if(question.inputType == 'Image') {
continue;
}
if(question.inputType == 'Number') {
answer.value = Math.ceil(Math.random() * 99);
}
if(question.inputType == 'Password') {
answer.value = 'Pa55w0rd123';
}
if(question.inputType == 'Radio') {
question.value = 'No';
}
if(question.inputType == 'Select') {
question.value = "At&t";
}
if(question.inputType == 'Tel') {
answer.value = faker.phone.phoneNumber();
}
if (question.inputType == 'Text') {
if(question.maxLength) {
answer.value = makeString(question.maxLength);
} else {
answer.value = faker.lorem.words()
}
}
if(question.inputType == 'Textarea') {
answer.value = faker.lorem.paragraph();
}
if(question.inputType == 'Url') {
answer.value = faker.internet.url();
}
response.answers.push(answer);
}
await response.save();
resolve(response._id);
return;
} catch (err) {
console.log(`Error creating random response: ${err.message}.`);
reject(response);
return;
}
});
}
console.log(`Creating ${companyCount} companies`)
for(let i = 0; i < companyCount; i++) {
const newCompany = await Company.create({
name: faker.company.companyName(),
created: await pickADate()
});
newCompany.locations = await createLocations(newCompany._id);
await newCompany.save();
console.log(`${newCompany.name} created with ${newCompany.locations.length} locations`)
}
console.log('database seeded')
};
module.exports = {seedDatabase, clearDatabase, seedDefaultQuestions};
I'm thinking the issue is in that function generating a random date from the beginning of last year up to the current date, but I honestly can't see how new Date(yyyy(integer),monthIndex,day) would be any different from the date created by Date.now(), according to MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date under "Individual Date and Time Component Values"
Here is how the User data looks in MongoDB, the completedSetup property is the last one, and it looks to be formatted correctly:
Lastly, here is the log of some of what the query returns (hit the character limit with all of it):
[
{
image: {
url: 'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_960_720.png'
},
role: 'Admin',
isCompanyAdmin: false,
isExpedited: false,
isHidden: false,
formAccessToken: 'de5459c2cbf3ca1cbdb0a5daceb6ab61',
responses: [ 5e8b71b7e75a0726242637b9 ],
createAccountToken: 'a826054b8055243c52247a656eed9340',
created: 2020-03-04T06:00:00.000Z,
_id: 5e8b71b6e75a0726242637b8,
firstname: 'Larue',
lastname: 'Armstrong',
username: 'LarueArmstrong',
personalEmail: '[email protected]',
company: 5e8b71abe75a072624263688,
location: 5e8b71b6e75a0726242637b5,
__v: 1,
completedSetup: 2020-03-07T06:00:00.000Z
},
{
image: {
url: 'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_960_720.png'
},
role: 'User',
isCompanyAdmin: false,
isExpedited: false,
isHidden: false,
formAccessToken: '7bf9d040c0009691191f3122c14d3d51',
responses: [ 5e8b71c2e75a07262426392a ],
createAccountToken: 'b284c3f43fad0081f967f06926ee1d6d',
created: 2019-11-25T06:00:00.000Z,
_id: 5e8b71c1e75a072624263929,
firstname: 'Lance',
lastname: 'Wolff',
username: 'LanceWolff',
personalEmail: '[email protected]',
company: 5e8b71bfe75a0726242638dd,
location: 5e8b71bfe75a0726242638de,
__v: 1,
completedSetup: 2020-03-02T06:00:00.000Z
},
{
image: {
url: 'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_960_720.png'
},
role: 'User',
isCompanyAdmin: false,
isExpedited: false,
isHidden: false,
formAccessToken: '319cd6d626a48617c012be6c25fe66a8',
responses: [ 5e8b71c5e75a072624263977 ],
createAccountToken: '43e9161a30f7ebd672315c761da9e3d7',
created: 2019-06-03T05:00:00.000Z,
_id: 5e8b71c5e75a072624263976,
firstname: 'Kailey',
lastname: 'Ruecker',
username: 'KaileyRuecker',
personalEmail: '[email protected]',
company: 5e8b71bfe75a0726242638dd,
location: 5e8b71bfe75a0726242638de,
__v: 1,
completedSetup: 2020-02-23T06:00:00.000Z
},
{
image: {
url: 'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_960_720.png'
},
role: 'User',
isCompanyAdmin: false,
isExpedited: false,
isHidden: false,
formAccessToken: 'ccb5fc2c6ff671a8cb5bdcf432cbcb1b',
responses: [ 5e8b71c7e75a0726242639bd ],
createAccountToken: '8d3aa2ecd6e0da797d8cbf9846c78c9b',
created: 2019-04-20T05:00:00.000Z,
_id: 5e8b71c6e75a0726242639bc,
firstname: 'Skyla',
lastname: 'Dicki',
username: 'SkylaDicki',
personalEmail: '[email protected]',
company: 5e8b71bfe75a0726242638dd,
location: 5e8b71bfe75a0726242638de,
__v: 1,
completedSetup: 2019-10-22T05:00:00.000Z
},
{
image: {
url: 'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_960_720.png'
},
role: 'User',
isCompanyAdmin: false,
isExpedited: false,
isHidden: false,
formAccessToken: '0641d2cf09459724ffea35d5cc96e2f1',
responses: [ 5e8b71c7e75a0726242639e0 ],
createAccountToken: '0f5e1bfd23df18835378c314efbcb206',
created: 2019-12-02T06:00:00.000Z,
_id: 5e8b71c7e75a0726242639df,
firstname: 'Rasheed',
lastname: 'Walsh',
username: 'RasheedWalsh',
personalEmail: '[email protected]',
company: 5e8b71bfe75a0726242638dd,
location: 5e8b71bfe75a0726242638de,
__v: 1,
completedSetup: 2020-02-16T06:00:00.000Z
},
{
image: {
url: 'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_960_720.png'
},
role: 'User',
isCompanyAdmin: false,
isExpedited: false,
isHidden: false,
formAccessToken: '7f584ded07bfe5b20e95ef72ed2a7749',
responses: [ 5e8b71cae75a072624263a2b ],
createAccountToken: '0934cd5e7ccb75d476ecc23624e491f1',
created: 2020-02-27T06:00:00.000Z,
_id: 5e8b71cae75a072624263a2a,
firstname: 'Leanna',
lastname: 'Kuphal',
username: 'LeannaKuphal',
personalEmail: '[email protected]',
company: 5e8b71bfe75a0726242638dd,
location: 5e8b71bfe75a0726242638de,
__v: 1,
completedSetup: 2019-11-02T05:00:00.000Z
}
]
In the full list (something like 60+ results) several are before 11/2019, like the one in this snippet that is from 10/2019.
A:
As usual, I feel dumb now that I've found the issue.
The problem was in the getPoints function.
It was treating every item in every sub-array it received as a point, and creating a point for it. So if the graphDatasets looked like:
[
['Invitations','Completions','Setups'],
[/* actual points data */]
]
And the points data had 7 months worth in it, it was adding 3 more points to the points array, extending the number of points.
I had to completely rewrite the structure of graphDatasets and update the renderCanvas function accordingly:
/* Don't know why I didn't have this as arrays of objects before, it's so much simpler */
const graphDatasets = [
[
{label:'Invitations',payload:recentInvitations,searchProperty:'created'},
{label:'Completions',payload:recentCompletions,searchProperty:'created'},
{label:'Setups',payload:recentSetups,searchProperty:'completedSetup'}
],
[
{label:'Companies',payload:recentCompanies,searchProperty:'created'},
{label:'Locations',payload:recentLocations,searchProperty:'created'}
]
];
//converts full object data from server into {month: String, count: Number} objects
//Add searchProperty argument
function getPoints(items, searchProperty) {
let points = [];
//access the data to be turned into points using the value at the .payload property
items.payload.forEach((item) => {
/* find the date to compare against using the searchProperty provided */
const workingDate = new Date(item[searchProperty])
const monthYear = `${workingDate.getMonth() + 1}/${workingDate.getFullYear()}`;
let existingPoint = points.find(point => point.x === monthYear);
if (existingPoint) {
existingPoint.y ++;
} else {
points.push({x:monthYear, y: 1});
}
});
return points;
};
// Returns the max Y value in our data list
function getMaxY(data) {
var max = 0;
for(var i = 0; i < data.length; i ++) {
if(data[i].y > max) {
max = data[i].y;
}
}
max += 10 - max % 10;
return max;
}
/* Removes objects from combined data where month matches, in order to draw only one copy of that
month on the X axis */
function removeDuplicates(originalArray, objKey) {
var trimmedArray = [];
var values = [];
var value;
for(var i = 0; i < originalArray.length; i++) {
value = originalArray[i][objKey];
if(values.indexOf(value) === -1) {
trimmedArray.push(originalArray[i]);
values.push(value);
}
}
return trimmedArray;
};
/* compare two arrays and if there are any missing months in either array, add them with a y value of 0, then sortby month/year */
function equalize(arr1, arr2) {
let newArr = arr2.reduce(function (result, obj2) {
if (arr1.some(obj1 => obj1['x'] === obj2['x'])) {
return result;
}
return [...result, {'x' : obj2['x'], 'y':0}];
}, arr1);
newArr.sort(function (a, b) {
a = a.x.split('/');
b = b.x.split('/')
return new Date(a[1], a[0], 1) - new Date(b[1], b[0], 1)
});
return newArr;
};
function renderCanvas(canvas, data) {
console.log('drawing on canvas');
const colors = ['indigo','blue','green','orange','purple','teal','fuschia'];
if(canvas.getContext) {
var xPadding = 30;
var yPadding = 30;
var xLength = canvas.width - yPadding;
var yLength = canvas.height - xPadding;
var pointsArr = [];
data.forEach(function (obj) {
pointsArr.push(getPoints(obj, obj.searchProperty));
});
for (let i = 0; i < pointsArr.length -1 ; i++) {
pointsArr[i] = equalize(pointsArr[i], pointsArr[i+1]);
};
var combinedData = Array.prototype.concat.apply([], pointsArr);
combinedData.sort(function(a,b) {
return new Date(a.created) - new Date(b.created)
});
var filteredPoints = removeDuplicates(combinedData, 'x');
/* cuts X axis into a number of sections double the number of points */
var xSpacing = xLength / (filteredPoints.length * 2);
var yMax = getMaxY(combinedData);
var ctx = canvas.getContext('2d');
ctx.font = 'italic 8pt sans-serif';
ctx.beginPath();
ctx.lineWidth = 6;
ctx.moveTo(yPadding,0);
ctx.lineTo(yPadding,yLength);
ctx.lineTo(canvas.width,yLength);
ctx.stroke();
ctx.closePath();
// Return the y pixel for a graph point
function getYPixel(val) {
return yLength - ((yLength / yMax) * (val));
}
// Return the y pixel for a graph point
function getXPixel(val) {
return ((xSpacing + yPadding) + (xSpacing * (2 * val)))
}
function drawLine(points, color, legendVal) {
/* move one xSpacing out from y Axis */
ctx.moveTo(yPadding + xSpacing, getYPixel(points[0].y));
ctx.beginPath();
ctx.fillStyle=color;
ctx.strokeStyle=color;
points.forEach((point) => {
const x = getXPixel(points.indexOf(point));
const y = (getYPixel(point.y)) ;
ctx.lineWidth = 2;
ctx.lineTo(x,y);
ctx.closePath();
ctx.stroke();
ctx.beginPath();
ctx.arc(x,y,5,0,360,false);
ctx.fillText(point.y, x + 2, y - 15);
ctx.closePath();
ctx.fill();
ctx.moveTo(x,y);
});
/* will need to update this (and other stuff) but use the label property of the data to label the line on the graph */
ctx.moveTo(canvas.width - yPadding, getYPixel(points[points.length-1].y));
ctx.fillText(legendVal, canvas.width - 20, getYPixel(points[points.length-1].y));
}
// Draw the X value texts
for(var i = 0; i < filteredPoints.length; i ++) {
if (i===0) {
ctx.fillText(filteredPoints[i].x, yPadding, yLength +20);
}else {
ctx.fillText(filteredPoints[i].x, (yPadding) + (xSpacing * (2 * i)), yLength + 20);
}
}
// Draw the Y value texts
ctx.textAlign = "right"
ctx.textBaseline = "middle";
for(var i = 0; i <= yMax; i += 10) {
if (i === yMax) {
ctx.fillText(i, xPadding - 10, getYPixel(i-1));
} else {
ctx.fillText(i, xPadding - 10, getYPixel(i));
}
};
pointsArr.forEach(async function (points) {
drawLine(points, colors[pointsArr.indexOf(points)], data[pointsArr.indexOf(points)].label);
});
}
};
NodeList.prototype.indexOf = Array.prototype.indexOf
canvases.forEach((canvas) => {
renderCanvas(
canvas,
graphDatasets[canvases.indexOf(canvas)]
);
});
|
[
"stackoverflow",
"0017083896.txt"
] | Q:
How to cancel Files.copy() in Java?
I'm using Java NIO to copy something:
Files.copy(source, target);
But I want to give users the ability to cancel this (e.g. if the file is too big and it's taking a while).
How should I do this?
A:
Use the option ExtendedCopyOption.INTERRUPTIBLE.
Note:
This class may not be publicly available in all environments.
Basically, you call Files.copy(...) in a new thread, and then interrupt that thread with Thread.interrupt():
Thread worker = new Thread() {
@Override
public void run() {
Files.copy(source, target, ExtendedCopyOption.INTERRUPTIBLE);
}
}
worker.start();
and then to cancel:
worker.interrupt();
Notice that this will raise a FileSystemException.
|
[
"pt.stackoverflow",
"0000294853.txt"
] | Q:
Dimensão da imagem renderizada pelo html2canvas
Eu tenho um script que cria uma imagem de uma div utilizando html2canvas e gostaria de saber se há alguma maneira de alterar o whidth e o height dessa imagem.
<div id="MinhaDiv">Conteúdo a ser renderizado</div>
<input id="Gerador" type="button" value="Gerar Imagem"/>
<div id="IMGfinal" ></div>
<script>
$(document).ready(function(){
var element = $("#MinhaDiv");
$("#Gerador").on('click', function () {
html2canvas(element, {
onrendered: function (canvas) {
$("#IMGfinal").append(canvas);
}
});
});
</script>
A:
A documentação do html2canvas oferece opções de configuração extras como width e height, que podem ser declaradas na própria função:
$(document).ready(function(){
var element = $("#MinhaDiv");
$("#Gerador").on('click', function () {
html2canvas(element, { width: 500, height: 500,
onrendered: function (canvas) {
$("#IMGfinal").append(canvas);
}
});
});
|
[
"math.stackexchange",
"0000237790.txt"
] | Q:
What is degree of freedom in statistics?
In statistics, degree of freedom is widely used in regression analysis, ANOVA and so on. But, what is degree of freedom ?
Wikipedia said that
The number of degrees of freedom is the number of values in the final calculation of a statistic that are free to vary.
Mathematically, degrees of freedom is the number of dimension of the domain of a random vector, or essentially the number of 'free'
components: how many components need to be known before the vector is
fully determined.
However, it is still hard for me to understand the concept intuitively.
Question:
Could anyone provide a intuitive explain to the concept and anything can help me understand?
Thanks!
Update:
I'm NOT asking how to calculate degree of freedom.
Let me give an example:
For Chi-squared distribution, different degree of freedom produces different probability density function. Could you explain it intuitively?
A:
Intuitively degrees of freedom denotes how many independent things are there. As we introduce constraints, we take away the degree of freedom.
First I'll try to answer your question about Chi-square.
Chi-square distribution with $n$ degree of freedom is the sum of squares $n$ independent standard normal distributions $N(0,1)$ hence we've got $n$ things that vary independently.
I'll start with mechanical example, as degree of freedom is similar in every field.
Consider an airplane flying. It has three degrees of freedom in the usual universe of space, and can be located only if three coordinates are known. These might be latitude, longitude, and altitude; or might be altitude, horizontal distance from some origin, and an angle; or might be direct distance from some origin, and two direction angles. If we consider a given instant of time as a section through the space-time universe, the airplane moves in a four‑dimensional path and can be located by four coordinates, the three previously named and a time coordinate.Hence it now has $4$ d.f.
Note that we assumed that plane is not rotating.
Now considering statistical degrees of freedom..
Similar meaning.
Degree of freedom of a statistic is number of values in calculation of statistic that are independent to vary.As we add restriction to observations, we reduce the degree of freedom.Imposing a relationship upon the observations is equivalent to estimating a parameter from them. The number of degrees of freedom is equal to the number of independent observations, which is the number of original observations minus the number of parmeters estimated from them.
Consider the calculation of mean $\frac {\sum_{i=1}^n X_n }{n}$, we are interested in estimation of error which are estimated by residues. Sum of residuals is $0$. Knowledge of any $n-1$ residues gives the remaining residue. So, only $n-1$ can vary independently. Hence they have $n-1$ d.f.
However d.f is mainly used in regression analysis, and ANOVA. You may note that all the distributions with so called d.f correspond to particular cases in linear statistics. Hence d.f is at the best artificial as they are not constraints on the random variable, but are actually degree of freedom of some quantities in some application from where these distributions originated.
Also, For people who are interested, < http://courses.ncssm.edu/math/Stat_Inst/Worddocs/DFWalker.doc > seems to be quite good read.
A:
Two people are sitting at a bar, you and your friend. There are two sorts of juice before you, one sweet, one sour. After you have chosen your drink, say the sweet one, your friend has no more choice - so degree of freedom is "1": only one of you can choose.
Generalize it to a group of friends to understand higher degrees of freedom...
A:
When you estimate parameters in statistics, suppose you use a parameter (which you have estimated) to estimate another parameter, then you lose $1$ degree of freedom and you end up with $n-1$ degrees of freedom where $n$ is the number of 'individuals' in the population with which you are working.
One example is when working with normal distributions
$$\sigma=\sqrt{\frac{\sum(x-\mu)}{n}^2}$$
let $s$ be the estimate of the population standard deviation ($\sigma$). We use the mean value $\bar x$ instead of $\mu$.
$$s=\sqrt{\frac{\sum(x-\bar x)}{n-1}^2}$$
Here $\bar x$ is an estimate of $\mu$. We estimate $\sigma$ by using an estimate of $\mu$. Hence we lose $1$ of degree of freedom, resulting in $n-1$ degrees of freedom.
|
[
"stats.stackexchange",
"0000373412.txt"
] | Q:
What are the properties of real life probability distributions?
Because of No Free Lunch Theorem, no machine learning algorithm can be said to be better than the other. However, in practice some algorithms are almost always better than the others. For example random forests and other tree based ensemble methods almost always beat other algorithms, see this paper.
One reply to this seemingly conflicting situation might be to note that No Free Lunch Theorem is true when we test algorithms on all possible data generating distributions. But in real life we have only a subset of these distributions. So my question is what are the properties of these real life probability distributions?
A:
The reasons that neural networks are such a hot topic right now is partially because of NN successes in image tasks, such as object recognition, facial recognition and other tasks. Trees simply don't do these tasks very well.
So, if you're willing to accept that images of ordinary objects are one type of data distribution, then you'll find that trees do not do very well against this distribution. Therefore, there is no contradiction with the NFL because another method (CNNs) outperforms trees.
See:
What are the current state-of-the-art convolutional neural networks?
|
[
"stackoverflow",
"0034954483.txt"
] | Q:
Using Spreadsheet in Query of Queries
I am reading a spreadsheet any trying to then run it in a query or Queries
<cfspreadsheet action="read"
src="#request.dropfolder##arguments.DSN#"
name="qryFromFile"
excludeHeaderRow="true"
headerrow="true">
<cfquery name="qryResult" dbtype="query">
SELECT EID
, CAST(#arguments.Config[2]# AS Decimal) AS [Value]
, 0 AS Invalid
, '<li><span><b>Comments:</b></span>' + Comments + ' on <time>' + [Date] + '</time></li>' AS Skyhook
FROM qryFromFile
ORDER BY EID
</cfquery>
Do I have to beild the table piece by piece?
A:
To get CF to stuff the contents into a query, you need to use the "query" attribute, not the "name" attribute
<cfspreadsheet action="read"
src="#request.dropfolder##arguments.DSN#"
query="qryFromFile"
excludeHeaderRow="true"
... >
|
[
"stackoverflow",
"0006713292.txt"
] | Q:
How to install .CSI file for Code Signing and load app to BlackBerry?
I've developed a PhoneGap application that I intend to deploy to my BlackBerry Bold 9700. My development tools includes NotePad++, Apache Ant, Sun JDK and BlackBerry WebWorks SDK as dictated on this page here http://www.phonegap.com/start#blackberry.
I applied for Signing Keys from the Blackberry website and received a .CSI file via email. The email offers instructions for various ways of processing the .CSI file, but none of the ways explain how to do it with the current tools I have installed.
Is there an easy way to proceed with my .CSI file without installing Eclipse, Visual Studio or any other IDE? If so, can someone dictate step by step what to do?
A:
I hope you got the solution for that. I was having the same issues. I hope my solution will work for anyone.
After getting the *.csi files from blackberry, you need to install them on your computer.
For those of you who are using Ant to build applications which described here http://www.phonegap.com/start#blackberry.
this will work you.
For installing the *.csi files in your computer you need SignatureTool.jar . This is located in your c:\BBWP\bin directory.
Next copy all the *.csi files to the above directory and run this command from the terminal in sequence.
c:\BBWP\bin>SignatureTool.jar client-RBB-2053305203.csi
c:\BBWP\bin>SignatureTool.jar client-RCR-2053305203.csi
c:\BBWP\bin>SignatureTool.jar client-RRT-2053305203.csi
If you don't have a private key installed you need to create one. And use the pin number which you used during the registration process. The installation is easy you will not have any problems with it.
Hope it helps anyone
Thank you
|
[
"stackoverflow",
"0049771107.txt"
] | Q:
Checkout Page Loads Without CSS Woocommerce
I have created a custom theme using Underscores Starter Theme.
I have installed Woocommerce( Got the messege that my theme is not compitable) , but all the pages are working just fine, except from the Cart and the Checkout page.
These 2 pages have no CSS applied as seen in the picture below.
Can anyone tell me how to fix this? Thanks
A:
Working solutions:
copy the woocomerce folder from plugin add add in your current active theme folder.
check the checkout page template and check the page.php file thats is includes get_header(); and get_footer().
|
[
"stackoverflow",
"0036142669.txt"
] | Q:
Getting totals from list of lists and apply it to a dictionary
I have a list of lists such as this:
[['blah', 5], ['blah', 6], ['blah',7], ['foo', 5], ['foo', 7]]
What I want to do is create a list of dictionaries where the first index of the list is the key word and the second is the running total.
The end results needs to look something like this:
[{'name': 'blah', 'total': 18}, {'name': 'foo', 'total': 12}]
A:
I would use a Counter here:
from collections import Counter
res = Counter()
for k, v in data:
res.update({k: v})
print(res)
output:
Counter({'blah': 18, 'foo': 12})
But if you really want the output you asked for:
final = [{'name': k, 'total': v} for k, v in res.items()]
print(final)
output:
[{'total': 18, 'name': 'blah'}, {'total': 12, 'name': 'foo'}]
|
[
"stackoverflow",
"0005957066.txt"
] | Q:
Android test application directly on device
is there a way to compile an apk and test it directly in an usb-attached device ? The emulator is way too slow for a fluid development.
A:
Using eclipse, make sure the project is debuggable, software for the phone is installed on the computer. Set the phone to accept unknown recourses. First connect the phone, then start eclipse (sometimes the other way round results in the phone not being found) If you try to run the application eclipse should prompt you asking witch device to use. Click your phone and presto!
|
[
"latin.stackexchange",
"0000009003.txt"
] | Q:
Did the word "citione" meaning "bump in the head" exist in Latin?
In the Spanish language site someone asked about the etymology of the word chichón (link in Spanish), meaning bump (typically in the head as a result of a hit). The most common theory is that it is just an augmentative for chicha, an informal version for flesh. But then I found this in a book from 1611:
This text properly defines what a chichón is, but then it states that it comes from Latin citione, a word with the same meaning, derived from the verb cire.
I have not found the word citione in any Latin dictionaries. So in order to know the reliability of this book, I ask: did the word citione exist at any time in the history of the Latin language? If not, what were the words used in Latin for bump (as a blow in the head)?
A:
My guess, for what it's worth, is that chichon originates from the verb cieo, cire,civi, citum, (which loses the e in compounds excio, accio etc.). The verb's general sense, like that of its compounds, is to agitate, stir up, cause, stimulate and so on.
It's not hard to imagine a noun citio being formed from the supine stem to mean a 'blow', 'incentive' etc. — or even the 'bump' suggested in the question.
|
[
"stackoverflow",
"0051684861.txt"
] | Q:
How does R represent NA internally?
R seems to support an efficient NA value in floating point arrays. How does it represent it internally?
My (perhaps flawed) understanding is that modern CPUs can carry out floating point calculations in hardware, including efficient handling of Inf, -Inf and NaN values. How does NA fit into this, and how is it implemented without compromising performance?
A:
R uses NaN values as defined for IEEE floats to represent NA_real_, Inf and NA. We can use a simple C++ function to make this explicit:
Rcpp::cppFunction('void print_hex(double x) {
uint64_t y;
static_assert(sizeof x == sizeof y, "Size does not match!");
std::memcpy(&y, &x, sizeof y);
Rcpp::Rcout << std::hex << y << std::endl;
}', plugins = "cpp11", includes = "#include <cstdint>")
print_hex(NA_real_)
#> 7ff80000000007a2
print_hex(Inf)
#> 7ff0000000000000
print_hex(-Inf)
#> fff0000000000000
The exponent (second till 13. bit) is all one. This is the definition of an IEEE NaN. But while for Inf the mantissa is all zero, this is not the case for NA_real_. Here some source
code
references.
|
[
"puzzling.stackexchange",
"0000085048.txt"
] | Q:
SOLV for Narcissistic UVC
This puzzle highlights some cyclic power Relations.
Please provide detailed reasoning of derivation of digits from various power relations given below:
$Given$:
$A$, $C$, $L$, $N$, $O$, $S$, $U$, $V$ are all distinct digits varying from 0 to 9.
$SOLV$, $UVC$, $LSU$, $VAN$ are concatenated Numbers.
1) $S^L$ + $O^L$ + $L^L$ + $V^L$ = $UVC$
2) $U^L$ + $V^L$ + $C^L$ = $LSU$
3) $L^L$ + $S^L$ + $U^L$ = $VAN$
4) $V^L$ + $A^L$ + $N^L$ = $UVC$
Back to Step 2..Repeat and Rinse Cycle of nice Power Relations.
A:
I believe the following values are consistent with the equations:
A = 6, C = 7, L = 3, N = 0, O = 4, S = 5, U = 2, V = 1
My first discovery is that
If L is 4 or greater, one of the remaining digits must be 6 or greater since there are eight of them total, and 6^4 exceeds 1000. Meanwhile, if L is 2 or less, this also does not work because of the second equation, where U^2+V^2+C^2 = 200 + SU. Assuming maximum values for U, V, and C, you would get 81+64+49 = 194, which is insufficient. Therefore, L must be equal to 3.
Working from Equations 1 and 4:
S^3+O^3+3^3 = A^3+N^3, as both equations equal to UVC and the V^L's cancel out. I feel like there may have been a more elegant way to figure this out, but I recall that 3^3 + 4^3 + 5^3 = 6^3, so I believe S and O are 4 and 5 while A and N are 0 and 6.
This gives us:
216 + V^3 = UVC The remaining possibilities for V are 2, 1, 7, 8, and 9, however we can rule out the latter two from equation 2 as 8^3 exceeds 400 and therefore cannot sum to LSU. 7 does not work as you result with 559, therefore V would have to be both 5 and 7. 2 does not work as your result would be 224, and both C and S/O cannot be 4. Lastly V=1 gives you a result of 217, making U = 2, V = 1, and C = 7. So far we are consistent.
Now back to equation 2:
We have 2^3 + 1^3 + 7^3 = LSU, resulting in LSU = 352, giving us L = 3 and U = 2, which is consistent, and S = 5, leaving O to equal 4. We are now left with A and N.
Finally with equation 3:
3^3 + 5^3 + 2^3 = VAN, resulting in VAN = 160. Once again confirming V = 1, as well as A = 6 and N = 0, consistent with our original hypothesis from Equations 1 and 4.
|
[
"math.stackexchange",
"0002601509.txt"
] | Q:
Calculating the probability to hit a number after already reaching a previous number
Let's say there is an infinite scale from $1$-infinity. We are starting from one and increasing by tenths.
The chance of getting to any given number is $1$/( that number ) $=$ ( reciprocal ). So for example, the chance of getting to $1.5$ is $1/1.5 = 66.67\ \%$, the chance of getting to $2$ is $1/2 = 50\ \%$, and so on.
If we've already made it to a certain point ( arbitrarily picking $1.5$ as an example ), what is the probability of making it to any other given point ( let's say $2.5$ ) ?.
A:
This seems like an exercise in conditional probability. Recall that
$$
\mathbb{P}[A|B] = \frac{\mathbb{P}[A \cap B]}{\mathbb{P}[B]}.
$$
Let $B$ be the event of reaching past the first point and $A$ be the event of reaching past the second point. Can you finish this?
|
[
"stackoverflow",
"0032866239.txt"
] | Q:
Error ERROR_RECOGNIZER_BUSY with offline speech recognition
I have made research on google offline speech recognition. but it works fine in google nexus 5(OS:-4.4) but same build if I implement in Samsung galaxy s5(OS:-5.0) it is not recognizing and it is showing this error:
8- ERROR_RECOGNIZER_BUSY.
Below is my code. By keeping this link as reference I have made a changes http://www.truiton.com/2014/06/android-speech-recognition-without-dialog-custom-activity/
Without internet voice must recognize. I have worked on Pocket sphinx but it take lot of side voice so client have rejected it.
public class VoiceRecognitionActivity extends Activity implements RecognitionListener {
private TextView returnedText;
private static ProgressBar progressBar;
private static SpeechRecognizer speech = null;
private static Intent recognizerIntent;
private String LOG_TAG = "VoiceRecognitionActivity";
private Button button1;
Activity activity = VoiceRecognitionActivity.this;
private TextView textView2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
returnedText = (TextView) findViewById(R.id.textView1);
textView2 = (TextView) findViewById(R.id.textView2);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
button1 = (Button) findViewById(R.id.button1);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
// toggleButton = (ToggleButton) findViewById(R.id.toggleButton1);
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities( new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() != 0)
{
createSpeechAgain(VoiceRecognitionActivity.this);
}
else
{
textView2.setText("Recognizer_not_present");
}
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
speech.stopListening();
speech.destroy();
createSpeechAgain(VoiceRecognitionActivity.this);
}
});
}
private void createSpeechAgain(VoiceRecognitionActivity voiceRecognitionActivity) {
progressBar.setVisibility(View.INVISIBLE);
speech = SpeechRecognizer.createSpeechRecognizer(voiceRecognitionActivity);
speech.setRecognitionListener(voiceRecognitionActivity);
recognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE, "en-US");
recognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, voiceRecognitionActivity.getPackageName());
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3);
//recognizerIntent.putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, Boolean.FALSE);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS, 20000);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS, 20000);
// EXTRA_PREFER_OFFLINE
progressBar.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(true);
speech.startListening(recognizerIntent);
}
@Override
public void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
/*if (speech != null) {
speech.destroy();
Log.i(LOG_TAG, "destroy");
}*/
}
@Override
public void onBeginningOfSpeech() {
Log.i(LOG_TAG, "onBeginningOfSpeech");
progressBar.setIndeterminate(false);
progressBar.setMax(10);
}
@Override
public void onBufferReceived(byte[] buffer) {
Log.i(LOG_TAG, "onBufferReceived: " + buffer);
}
@Override
public void onEndOfSpeech() {
Log.i(LOG_TAG, "onEndOfSpeech");
progressBar.setIndeterminate(false);
progressBar.setVisibility(View.INVISIBLE);
speech.stopListening();
}
@Override
public void onError(int errorCode) {
String errorMessage = getErrorText(errorCode);
Log.d(LOG_TAG, "FAILED " + errorMessage);
textView2.setText(errorMessage);
}
@Override
public void onEvent(int arg0, Bundle arg1) {
Log.i(LOG_TAG, "onEvent");
}
@Override
public void onPartialResults(Bundle arg0) {
Log.i(LOG_TAG, "onPartialResults");
}
@Override
public void onReadyForSpeech(Bundle arg0) {
Log.i(LOG_TAG, "onReadyForSpeech");
}
@Override
public void onResults(Bundle results) {
Log.i(LOG_TAG, "onResults");
ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
String text = "";
for (String result : matches)
text += result + "\n";
returnedText.setText(text);
Log.v(LOG_TAG, "onResults---> " + text);
progressBar.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(true);
speech.startListening(recognizerIntent);
}
@Override
public void onRmsChanged(float rmsdB) {
//Log.i(LOG_TAG, "onRmsChanged: " + rmsdB);
progressBar.setProgress((int) rmsdB);
}
public String getErrorText(int errorCode) {
String message;
switch (errorCode) {
case SpeechRecognizer.ERROR_AUDIO:
message = "Audio recording error";
Log.v("LOG_TAG", message);
progressBar.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(true);
speech.startListening(recognizerIntent);
break;
case SpeechRecognizer.ERROR_CLIENT:
message = "Client side error";
Log.v("LOG_TAG", message);
progressBar.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(true);
speech.startListening(recognizerIntent);
break;
case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
message = "Insufficient permissions";
Log.v("LOG_TAG", message);
progressBar.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(true);
speech.startListening(recognizerIntent);
break;
case SpeechRecognizer.ERROR_NETWORK:
message = "Network error";
Log.v("LOG_TAG", message);
break;
case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
message = "Network timeout";
Log.v("LOG_TAG", message);
break;
case SpeechRecognizer.ERROR_NO_MATCH:
message = "No match";
Log.v("LOG_TAG", message);
progressBar.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(true);
speech.startListening(recognizerIntent);
break;
case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
message = "RecognitionService busy";
Log.v("LOG_TAG", message);
speech.stopListening();
speech.destroy();
createSpeechAgain(VoiceRecognitionActivity.this);
break;
case SpeechRecognizer.ERROR_SERVER:
message = "error from server";
Log.v("LOG_TAG", message);
break;
case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
message = "No speech input";
Log.v("LOG_TAG", message);
progressBar.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(true);
speech.stopListening();
speech.destroy();
createSpeechAgain(VoiceRecognitionActivity.this);
break;
default:
message = "Didn't understand, please try again.";
break;
}
return message;
}
}
Xml :-
<?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:orientation="vertical" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:src="@drawable/ic_launcher" />
<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/toggleButton1"
android:layout_marginTop="28dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/progressBar1"
android:layout_centerHorizontal="true"
android:layout_marginTop="47dp" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/imageView1"
android:layout_alignLeft="@+id/imageView1"
android:text="Restart" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="19dp"
android:text="" />
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.offlinegooglespeechtotext"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="19"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".VoiceRecognitionActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Logcat:-
09-30 18:05:54.732: D/ResourcesManager(3941): creating new AssetManager and set to /data/app/com.example.offlinegooglespeechtotext-2/base.apk
09-30 18:05:54.772: V/BitmapFactory(3941): DecodeImagePath(decodeResourceStream3) : res/drawable-xxhdpi-v4/sym_def_app_icon.png
09-30 18:05:54.772: V/BitmapFactory(3941): DecodeImagePath(decodeResourceStream3) : res/drawable-xxhdpi/ic_launcher.png
09-30 18:05:54.787: V/BitmapFactory(3941): DecodeImagePath(decodeResourceStream3) : res/drawable-xxhdpi-v4/ic_ab_back_holo_dark_am.png
09-30 18:05:54.797: V/BitmapFactory(3941): DecodeImagePath(decodeResourceStream3) : res/drawable-xxhdpi-v4/sym_def_app_icon.png
09-30 18:05:54.817: D/Activity(3941): performCreate Call secproduct feature valuefalse
09-30 18:05:54.817: D/Activity(3941): performCreate Call debug elastic valuetrue
09-30 18:05:54.827: D/OpenGLRenderer(3941): Render dirty regions requested: true
09-30 18:05:54.867: I/(3941): PLATFORM VERSION : JB-MR-2
09-30 18:05:54.867: I/OpenGLRenderer(3941): Initialized EGL, version 1.4
09-30 18:05:54.877: I/OpenGLRenderer(3941): HWUI protection enabled for context , &this =0xb39090d8 ,&mEglDisplay = 1 , &mEglConfig = -1282088012
09-30 18:05:54.887: D/OpenGLRenderer(3941): Enabling debug mode 0
09-30 18:05:54.957: V/LOG_TAG(3941): No match
09-30 18:05:54.957: D/VoiceRecognitionActivity(3941): FAILED No match
09-30 18:05:54.982: I/Timeline(3941): Timeline: Activity_idle id: android.os.BinderProxy@24862afe time:5837375
09-30 18:05:55.607: I/VoiceRecognitionActivity(3941): onReadyForSpeech
09-30 18:05:55.947: I/VoiceRecognitionActivity(3941): onBeginningOfSpeech
09-30 18:05:57.252: I/VoiceRecognitionActivity(3941): onEndOfSpeech
09-30 18:05:57.322: V/LOG_TAG(3941): No match
09-30 18:05:57.322: D/VoiceRecognitionActivity(3941): FAILED No match
09-30 18:05:57.332: V/LOG_TAG(3941): No match
09-30 18:05:57.332: D/VoiceRecognitionActivity(3941): FAILED No match
09-30 18:05:57.347: V/LOG_TAG(3941): No match
09-30 18:05:57.347: D/VoiceRecognitionActivity(3941): FAILED No match
09-30 18:05:57.367: V/LOG_TAG(3941): RecognitionService busy
09-30 18:05:57.392: D/VoiceRecognitionActivity(3941): FAILED RecognitionService busy
09-30 18:05:57.392: E/SpeechRecognizer(3941): not connected to the recognition service
09-30 18:05:58.232: I/VoiceRecognitionActivity(3941): onReadyForSpeech
09-30 18:06:03.287: V/LOG_TAG(3941): No speech input
09-30 18:06:03.302: D/VoiceRecognitionActivity(3941): FAILED No speech input
09-30 18:06:03.302: E/SpeechRecognizer(3941): not connected to the recognition service
A:
ERROR_RECOGNIZER_BUSY is often thrown when you didn't close the SpeechRecognizer proprely. Yo probably are already using one instance of the SpeechRecognizer.
See this http://developer.android.com/reference/android/speech/SpeechRecognizer.html
|
[
"stackoverflow",
"0022050741.txt"
] | Q:
What is the best way to make a java class library in Android with Eclipse?
I wonder, What is the best way to make a java class library in Android with Eclipse?. I know if I have done well.
I created an Android project and indicated that a library project. And without creating any activities.
Then I think my classes.
I create a folder called "jar"
Exporto classes to jar and keep in the "jar" folder.
In the projects that I want to add I add this jar as external jar.
This is what I do but I honestly do not know if it is right. The idea is to create general classes and be able to share and maintain it properly for other projects.
A:
The general idea with a library project is you create classes within it. Then you reference them via your main projects manifest.
Add the library project in the main project settings and you will have general classes that you can share to any project.
I assume this is what you are looking for based on your post.
Edit
Here is how to do it:
1) Set project to be library (you have said you have done this).
2) Put your classes in your library project. (So you can call them from other projects).
3) Go to the main project and right click on it, select Android from the settings. This is where you turned your library project, into a library project.
4) Anyway, at the bottom click add.
5) In the manifest, create and activity reference to a class in the library project.
6) So if you are trying to get MainActivity you call com.library.project.package.MainActivity
Now you will have the MainActivity viewing able if you ran the project.
|
[
"stackoverflow",
"0015874667.txt"
] | Q:
sort collection of category by name
I have custom links in menu that shows categories in drop-down.
For that I made a file in catalog/navigation->mainmenu.phtml
(a custom file)
Now, I want to show categories after sorting it by name. please help me how can I sort collection of categories by name. I already set order of category in admin. But in front-end it show unsorted.
Code is:-
<?php $defaultcategory= Mage::app()->getStore()->getRootCategoryId();?>
<?php $mainchildren = Mage::getModel('catalog/category')->getCategories($defaultcategory);?>
<ul>
<?php foreach ($mainchildren as $subcategory) : ?> <?php // 2 level ?>
<?php if($subcategory->getIsActive()):?>
<li id="show_subcat" class="<?php if($i==1): echo 'first'; endif; ?>" >
<?php $childid=$subcategory->getId();?>
<?php $subchild = Mage::getModel('catalog/category')->getCategories($childid);?>
<?php foreach ($subchild as $subchildcategory) : ?>
<?php $path=$subchildcategory->getRequestPath()?>
<?php break;?>
<?php endforeach ?>
<a href="<?php echo $this->getUrl().$path; ?>">
<?php echo $name= $subcategory->getName().$subcategory->getEnable() ?>
</a>
</li>
<?php endif;?>
<?php endforeach; ?>
</ul>
A:
$categories = Mage::helper('catalog/category');
$collection = $categories->getStoreCategories(false,true,false);
foreach($collection as $_category)
{
//Do something
echo $_category->getName();
}
use this code to get collection and follow this link for more detailIn magento - same code for getting all categories running well with sorted in localhost but not in web server
|
[
"serverfault",
"0000116898.txt"
] | Q:
Server Administration with webadmin
Were recently going to start an ecommerence website that also stores Credit Card details and such. Our security is well on the software side, but with regards to the entire OS, we fall weak and are looking to sure our station. I came across a tool called webmin that helps you configure your linux box. How good is this tool and do you guys recommend this tool to be used to secure a website? For example i saw that the tool allows you to play with IPTables.
Is this a good tool to use to properly secure a website against any attacks. We have also ensured MySQL is secure following this tutorial http://www.securityfocus.com/infocus/1726
A:
Webmin is a good tool, but it's also another potential security hole...Make sure you lock it down so it can only be accessed from trusted hosts.
It's basically a graphical front-end for a ton of command line stuff. It can't do anything that you can't do on a command line, but it makes some of those things a little more friendly...So if you already know how to secure a box, it'll help.
If you don't know, however, it's not going to change anything.
My advice is, unless you absolutely have to, do NOT store credit card details. Store the last four digits for verification, and pass the rest up to your merchant provider, and let them shoulder the burden.
When you step into the world of hardened credit card handling machines, you have to understand that you need to keep on top of that machine constantly because every new vulnerability will get tried against it at some point.
|
[
"stackoverflow",
"0039425183.txt"
] | Q:
sum() with conditions provides incorrect result in dplyr package
When applying sum() with conditions in summarize() function, it does not provide the correct answer.
Make a data frame x:
x = data.frame(flag = 1, uin = 1, val = 2)
x = rbind(x, data.frame(flag = 2, uin = 2, val = 3))
This is what x looks like:
flag uin val
1 1 1 2
2 2 2 3
I want to sum up the val and the val with flag == 2, so I write
x %>% summarize(val = sum(val), val.2 = sum(val[flag == 2]))
and the result is:
val val.2
1 5 NA
But what I expect is that val.2 is 3 instead of NA. For more information, if I calculate the conditional summation first then the total summation, it comes out with the correct answer:
x %>% summarize(val.2 = sum(val[flag == 2]), val = sum(val))
val.2 val
1 3 5
Moreover, if I only calculate the conditional summation, it works fine too:
x %>% summarize(val.2 = sum(val[flag == 2]))
val.2
1 3
A:
Duplicate names are causing you problems. In this code
x %>% summarize(val = sum(val), val.2 = sum(val[flag == 2]))
You have two val objects. One created from val = sum(val) and other from the data frame x. In your code, you change val from the data frame value to val=sum(val) = 5. Then you do
`val[flag == 2]`
which gives a vector c(2, NA), since val = 5. Hence, when you add 2 + NA you get NA. The solution, don't use val twice,
x %>% summarize(val_sum = sum(val), val.2 = sum(val[flag == 2]))
|
[
"stackoverflow",
"0000569350.txt"
] | Q:
Flex FileReference.download - is it possible to open associated application
When using FileReference.download() to retrieve a file from a server, I'd like to give the user the option to open the associated application directly rather than having to save it to disk first.
Is this possible in Flex 3? And, if so, how is it done!
Thanks,
Mark
ps. I've tried doing URLLoader.load(URLRequest) also, but no dice...
A:
navigateToURL(urlReq, "_blank") works in most cases, but do not open Excel, CSV files(MS office apps) in IE 7 and older versions.
|
[
"stackoverflow",
"0038192711.txt"
] | Q:
How to retrieve multiple keys in Firebase?
Considering this data structure:
{
"users":{
"user-1":{
"groups":{
"group-key-1":true,
"group-key-3":true
}
}
},
"groups":{
"group-key-1":{
"name":"My group 1"
},
"group-key-2":{
"name":"My group 2"
},
"group-key-3":{
"name":"My group 3"
},
"group-key-4":{
"name":"My group 4"
},
}
}
I could get the groups of a particular user with:
firebase.database().ref('users/user-1/groups').on(...)
Which would give me this object:
{
"group-key-1":true,
"group-key-3":true
}
So now I want to retrieve the info for those groups.
My initial instinct would be to loop those keys and do this:
var data = snapshot.val()
var keys = Object.keys(data)
for (var i = 0; i < keys.length; i++) {
firebase.database().ref('groups/' + keys[i]).on(...)
}
Is this the appropriate way to call multiple keys on the same endpoint in Firebase?
Does Firebase provide a better way to solve this problem?
A:
Is this the appropriate way to call multiple keys on the same endpoint
in Firebase?
Yes, generally this is a good solution to retrieve every group this way.
Does Firebase provide a better way to solve this problem?
I don't think Firebase provides any other function/query that could help in this case.
Anyway, this could be improved saving the ref in a variable and looping on the keys of the object directly. Also, if you just need to retrieve those data once, you should use once() instead of on()
var groupRef = firebase.database().ref('groups/')
var data = snapshot.val()
for (var groupID in data) {
groupRef.child(data[groupID]).once(...)
}
Another way could be using Firebase's functions for the data snapshots, like forEach
snapshot.forEach(function(childSnapshot) {
groupRef.child(childSnapshot.key).once(...)
})
A:
Yes, you are going in the right way. As written in this question firebase will pipeline your requests and you won't have to be concerned about performance and roundtrip time. As soon as your iteration starts you will be receiving firebase data. So keep in mind to handle it properly in your ui.
Another option, that will depends on how big your /groups data will grow, is to keep a snapshot (could be a $firebaseObject if you are using angularfire) of the entire /groups branch that will refresh whenever data changes. Then you just have to track this snapshot. But again, if you are planning to play with a big amount of groups your current solution is a better choice.
Also, I recommend you to take care of setting an on event for each group you retrieve. Keep in mind that the callback will be triggered whenever the data changes (depends on the setted event). Depending on your use case you should consider using .once("value" since it will trigger the data only once, making it more reliable, more performatic and will avoid handling callbacks when you are not expecting them.
|
[
"stackoverflow",
"0007861689.txt"
] | Q:
Checking a number range with regular expressions
I'm using a regular expression to validate a certain format in a string. This string will become a rule for a game.
Example: "DX 3" is OK according to the rule, but "DX 14" could be OK too... I know how to look at the string and find one or more "numbers", so the problem is that the regex will match 34 too, and this number is out of "range" for the rule...
Am I missing something about the regex to do this? Or is this not possible at all?
A:
Unfortunately there's no easy way to define ranges in regex. If you are to use the range 1-23 you'll end up with a regex like this:
([1-9]|1[0-9]|2[0-3])
Explanation:
Either the value is 1-9
or the value starts with 1 and is followed with a 0-9
or the value starts with 2 and is followed with a 0-3
A:
It is not that short, and not flexible.
If you search for 1 to 19, you can search for "DX 1?[0-9]", for example, but if it doesn't end at a number boundary, it get's ugly pretty soon, and changing the rules is not flexible.
Splitting the String at the blank, and then using x > 0 and x < 24 is better to understand and more flexible.
|
[
"stackoverflow",
"0001556584.txt"
] | Q:
Is there a perfomance gain on the language chosen and DB?
We have our current system using PHP and Microsoft SQL Server.
I am trying to work out if there will be a performance gain in using PHP and MySQL?
It will require some effort to change to this platform so I am hoping to find out as much as I can. Are there any questions I should be asking myself to determine the correct choice?
Thanks all
More Info
100 of Millions Records Processed Reguraly (monthly)
PHP + MS SQL Server run on the same machine
Windows Enivronment
Clarification
I was initially hoping for this swap to be a magic solution, obviously not!!
To keep this thread useful, can we concentrate on what effect switching to MySQL or any other DB system would have on an overall application that has been finely tuned and nothing else can be done!
A:
You may want to profile your application first, and determine how much time is being spent in the database, and how much time in each query.
Then it is easier to answer, as you can say that the application spends 3% in the database, and out of that 27% are in selects and the rest are inserts that involve triggers.
Also, which OS would MySQL be on?
Is it on a separate computer than the PHP server?
What is your current architecture like?
If you are looking at the fact that both your webserver and db server are on the same computer, and then you separate them for MySQL, and you get a performance increase, it is most likely due to the fact that the single cpu on your first computer doesn't have to do double duty now.
Which version of PHP? Would that be changed?
Are you using the mssql functions, odbc functions or pdo currently?
A:
In most cases, I'd wouldn't start thinking about swapping a database back-end for performance reasons until I was sure everything else had been exhausted.
RDBMSes are sophisticated animals. Before you consider switching them out, take a good look at your current database. Even better -- pay a specialist with SQLServer experience to do so. Badly configured databases are everywhere.
You might see a performance increase switching, or you might take a hit. Until you know that your current database is properly tuned, it's all just guesswork.
As James Black just answered, the right way to increase performance is to profile your application, and figure out where it's spending its time.
|
[
"stackoverflow",
"0045794039.txt"
] | Q:
How convert string to utf-8? (Swift, Alamofire)
Me need so that Alamofire send utf-8 parameters to my server, now he transmits English characters normally, but Russian characters as hieroglyphs. After checking the encoding I found that it is used maccyrillic characters.
let parameters: Parameters = ["username": login.text!, "password": password.text!]
Alamofire.request("link ti site", method: .post, parameters: parameters).responseJSON { response in
switch response.result {
case .success:
let json = JSON(response.result.value)
case .failure( _):
var errorString = "NULL"
if let data = response.data {
if let json = try? JSONSerialization.jsonObject(with: data, options: []) as! [String: String] {
errorString = json["error"]!
}
}
}
}
Need your help. Thanks you.
A:
Swift 3
let newStr = String(utf8String: stringToDecode.cString(using: .utf8)!)
Source StackOverFlow
|
[
"tex.stackexchange",
"0000106953.txt"
] | Q:
How to create multicolumns list environment with the package 'enumerate'?
Let us consider The following example
\documentclass{article}
\usepackage{enumerate}
\begin{document}
\begin{enumerate}
\item Which of the following numbers is the largest ?\\
$2^{3^4},2^{4^3},3^{2^4},3^{4^2},4^{2^3},4^{3^2}.$
\begin{enumerate}[(a)]
\item $2^{3^4}$
\item $3^{4^2}$
\item $4^{3^2}$
\item $4^{2^3}$
\end{enumerate}
\end{enumerate}
\end{document}
This produces :
But I'd like to produce the following using the same package :
OR
OR
How can I do that?
A:
You can use the multicol package:
\documentclass{article}
\usepackage{enumerate}
\usepackage{multicol}
\begin{document}
\begin{enumerate}
\item Which of the following numbers is the largest?\\
$2^{3^4}$, $2^{4^3}$, $3^{2^4}$, $3^{4^2}$, $4^{2^3}$, $4^{3^2}$.
\begin{enumerate}[(a)]
\begin{multicols}{2}
\item $2^{3^4}$
\item $3^{4^2}$
\item $4^{3^2}$
\item $4^{2^3}$
\end{multicols}
\end{enumerate}
\end{enumerate}
\end{document}
Here's another option, using this time the enumitem package and its inline option:
\documentclass{article}
\usepackage[inline]{enumitem}
\begin{document}
\begin{enumerate}
\item Which of the following numbers is the largest?\\
$2^{3^4}$, $2^{4^3}$, $3^{2^4}$, $3^{4^2}$, $4^{2^3}$, $4^{3^2}$.
\begin{enumerate*}[label=(\alph*),itemjoin={\hspace{\fill}}]
\item $2^{3^4}$
\item $3^{4^2}$
\item $4^{3^2}$
\item $4^{2^3}$
\end{enumerate*}
\end{enumerate}
\end{document}
|
[
"tex.stackexchange",
"0000055019.txt"
] | Q:
Different chapters, different layout
On request, I have two different layouts for chapters for a book. The first one is exclusive to the Chapter 1 and the other one is for the others. The layout affect how the sections, definitions and paragraphs are displayed. I have the code to handle this in a little class file. This is a MWE:
\documentclass[12pt,letterpaper]{book}
\usepackage{amsmath,amsfonts,amssymb,amsthm}
\usepackage{thmtools}
\usepackage{ifthen,calc}
\usepackage{blindtext}
\parindent=0mm
\newtheorem{teo}{Theorem}[section]
\newtheorem{axi}{Axiom}
\newtheorem{lem}{Lemma}
\newcounter{definition}
\declaretheoremstyle[%
spaceabove=6pt,%
spacebelow=6pt,%
headfont=\normalfont\bf,%
notefont=\normalfont\bf,
notebraces={{}{}},
bodyfont=\itshape,
headpunct={.}]{defistyle}
\declaretheorem[
name={Definition},
numberlike=definition,
style=defistyle]{defi}
\renewcommand\thesection
{\arabic{chapter}.\arabic{section}}
\makeatletter
\renewcommand\@seccntformat[1]{
{\csname the#1\endcsname}.\hspace{0.5em}}
\renewcommand\section{\@startsection
{section}{1}{0mm}
{6pt}
{1pt}
{\bfseries}}
\renewcommand\paragraph{\@startsection
{paragraph}{3}{0cm}
{6pt}
{1pt}
{\bfseries}}
\makeatother
\makeatletter
\newcommand{\capi}[1]{
\chapter{#1}
\ifthenelse{\value{chapter}=2}{
\renewcommand\section{\@startsection
{section}{1}{0mm}
{0pt}
{1pt}
{\Large}}
\@addtoreset{definition}{section}
\renewcommand{\thedefi}{\thesection.\arabic{definition}}
}{}}
\makeatother
\begin{document}
\capi{Some preliminaries}
\blindtext
\section{the first thing}
\blindtext[1]
\begin{defi}
The thing $1$ is real number. If $x$ is real then $x+1$ is real.
\end{defi}
\blindtext
\capi{Cool stuff}
\blindtext
\section{Complex things}
bla bla bla
\begin{defi}
We say that a number $x$ is complex if it is not really a number.
\end{defi}
\blindtext
\end{document}
As you can see, my actual way to handle the different style for each chapter is not so elegant. I have the book splitted in several files, one per chapter. When I'm reviewing the book I'm select the chapters I want to see via the \includeonly command. The problem is that in order to get the proper look of the sections, paragraphs and definitions I always have to include the chapter 2. Also, I'll would like to avoid to define a new command to the chapters. My question is: is there a way to improve this?
A:
Just define \capi to redefine itself when it's not the first chapter, so that the test and the redefinition will be performed only once.
\makeatletter
\newcommand{\capi}{%
\ifnum\value{chapter}>0
\changesectionanddefi
\let\capi\chapter
\fi
\chapter
}
\def\changesectionanddefi{%
\renewcommand\section{\@startsection{section}{1}{0mm}{6pt}{1pt}{\Large}}%
\@addtoreset{definition}{section}%
\renewcommand{\thedefi}{\thesection.\arabic{definition}}%
}
\makeatother
You can even do better: redefine \chapter so as to get rid of the non standard \capi command:
\makeatletter
\let\leo@chapter\chapter
\renewcommand{\chapter}{
\ifnum\value{chapter}>0
\changesectionanddefi
\let\chapter\leo@chapter
\fi
\leo@chapter
}
\def\changesectionanddefi{%
\renewcommand\section{\@startsection{section}{1}{0mm}{6pt}{1pt}{\Large}}%
\@addtoreset{definition}{section}%
\renewcommand{\thedefi}{\thesection.\arabic{definition}}%
}
\makeatother
So, no \capi with this, but the usual \chapter.
Be careful with end-of-lines in definitions. Also check the parameters to \@startsection: your code was not working correctly.
A:
Your problem is that you use a suboptimal condition. The condition is not that the chapter counter is equal to 2 but that the counter is greater than 1. Then the condition holds for all sections in all chapters. Thus you can then define \section to change its layout depending on the condition instead of placing the redefinition of \section inside the \chapter command.
Downside: the test will be executed whenever a section is processed (rather than only during chapter 2 once) but that is will not make a noticable difference in processing time.
|
[
"stackoverflow",
"0019718703.txt"
] | Q:
PHP array declaration issue
$info = array(
"First_Names" => "John",
"Last_Names" => "Smith",
"Gender" => "Male",
);
array_push($info["First_Names"], "$fname");
print_r ($info);
I started learning PHP through a high school class. I'm not exactly knowledgeable nor do I pay attention much, but I'm completely stuck on this;
What I'm trying to do is get the variable $fname which is defined by the user (Jack, James, Shelly, etc) to be pushed into the array First_Names which is inside the array of $info. I'm not sure where it's going wrong, but PHP is not declaring $info as an array (I think, it states "Warning: array_push() [function.array-push]: First argument should be an array in /home/a4938424/public_html/process.php on line 22". If I print out the array it will show up the default names and gender,and if I echo out the $fname variable it shows up properly.)
I've consulted two different people and neither of their suggestions worked, now I'm stumped completely and everyone is out of suggestions. Does anyone see what's going on with it? Thanks for any responses, please be aware that I barely know any PHP.
A:
$info['First_Names'] is not an array, it is a string ("John"). If you define it as an array, it might work ;)
|
[
"stackoverflow",
"0055543726.txt"
] | Q:
JMeter - Avoid threads abrupt shutdown
I have a testPlan that has several transacion controllers (that I called UserJourneys) and each one is composed by some samplers (JourneySteps).
The problem I'm facing is that once the test duration is over, Jmeter kills all the threads and does not take into consideration if they are in the middle of a UserJourney (transaction controller) or not.
On some of these UJs I do some important stuff that needs to be done before the user logs in again, otherwise the next iterations (new test run) will fail.
The question is: Is there a way to tell to JMeter that it needs to wait every thread reach the end of its flow/UJ/TransactionController before killing it?
Thanks in advance!
A:
This is not possible as of version 5.1.1, you should request an enhancement at:
https://jmeter.apache.org/issues.html
The solution is to add as first child of Thread Group a Flow Control Action containing a JSR223 PreProcessor:
The JSR223 PreProcessor will contain this groovy code:
import org.apache.jorphan.util.JMeterStopTestException;
long startDate = vars["TESTSTART.MS"].toLong();
long now = System.currentTimeMillis();
String testDuration = Parameters;
if ((now - startDate) >= testDuration.toLong()) {
log.info("Test duration "+testDuration+" reached");
throw new JMeterStopTestException("Test duration "+testDuration+"reached ");
} else {
log.info("Test duration "+testDuration+" not reached yet");
}
And be configured like this:
Finally you can set the property testDuration in millis on command line using:
-JtestDuration=3600000
If you'd like to learn more about JMeter and performance testing this book can help you.
|
[
"stackoverflow",
"0057199372.txt"
] | Q:
TypeScript: function return type based on argument, without overloading
Is it possible to return a function's type based on an argument?
I saw Variable return types based on string literal type argument, but it uses overloading. Here, I have 100+ types, so I do not want to do overloading.
interface Registry {
A: number,
B: string,
C: boolean,
// ... 100 more types like this
}
function createType<T = Registry[typeof myType]>(myType: keyof Registry, value: any): T {
// do some magic
// ...
return value;
}
const a = createType('A', 2); // Expected type: number. Actual: error above
Playground Link
A:
You can do it, but you will need a type parameter to capture the argument passed in. With this new type parameter you can index into your Registry to get the type you want:
interface Registry {
A: number,
B: string,
C: boolean
}
function createType<K extends keyof Registry>(type: K, value: Registry[K]): Registry[K] {
return value;
}
const a = createType('A', 2); // ok
const b = createType('B', 2); // err
|
[
"stackoverflow",
"0026191073.txt"
] | Q:
Operator '/' can't be applied to operands of types 'decimal' and 'double' - NCalc
I'm trying to run this formula in NCalc:
"( Abs([a] - [b]) / ( ([a] + [b]) / 2.0 ) ) * 100"
I get the error:
Operator '/' can't be applied to operands of types 'decimal' and 'double'
The [a] and [b] parameters are passed as Decimals. I tried putting 'm' on the 2 and 100 like so:
"( Abs([a] - [b]) / ( ([a] + [b]) / 2m ) ) * 100m"
But it throws an exception:
Additional information: extraneous input 'm' expecting ')' at line 1:36
I followed this question, but it didn't help me. The same question posted on codeplex with no answer. Any ideas?
A:
Possible workaround is to pass 2m as parameter to make it recognized properly as a decimal value, for example :
string strExp = "( Abs([a] - [b]) / ( ([a] + [b]) / [c] ) ) * 100";
Expression e = new Expression(strExp);
e.Parameters["a"] = 3.5m;
e.Parameters["b"] = 1m;
e.Parameters["c"] = 2m; //<- pass 2m as expression parameter
|
[
"stackoverflow",
"0011091924.txt"
] | Q:
drawing waveform - converting to DB squashes it
I have a wave file, i have a function that retrieves 2 samples per pixel then i draw lines with them. quick and painless before i deal with zooming. i can display the amplitude values no problem
that is an accurate image of the waveform. to do this i used the following code
//tempAllChannels[numOfSamples] holds amplitude data for the entire wav
//oneChannel[numOfPixels*2] will hold 2 values per pixel in display area, an average of min amp, and average of max
for(int i = 0; i < numOfSamples; i++)//loop through all samples in wave file
{
if (tempAllChannels[i] < 0) min += tempAllChannels[i];//if neg amp value, add amp value to min
if (tempAllChannels[i] >= 0) max += tempAllChannels[i];
if(i%factor==0 && i!=0) //factor is (numofsamples in wav)/(numofpixels) in display area
{
min = min/factor; //get average amp value
max = max/factor;
oneChannel[j]=max;
oneChannel[j+1]=min;
j+=2; //iterate for next time
min = 0; //reset for next time
max = 0;
}
}
and that's great but I need to display in db so quieter wave images arent ridiculously small, but when i make the following change to the above code
oneChannel[j]=10*log10(max);
oneChannel[j+1]=-10*log10(-min);
the wave image looks like this.
which isnt accurate, it looks like its being squashed. Is there something wrong with what I'm doing? I need to find a way to convert from amplitude to decibels whilst maintaining dynamics. im thinking i shouldnt be taking an average when converted to DB.
A:
Don't convert to dB for overviews. No one does that.
Instead of finding the average over a block, you should find the max of the absolute value. By averaging, you will loose a lot of amplitude in your high frequency peaks.
|
[
"stackoverflow",
"0037459500.txt"
] | Q:
python help! invalid literal for int() with base 10:
hi currently doing a code where the programe recalls two files one with positions of words the other words the following code combines them however when i change my code to be imported from a file i get the following error (if compressed_sentence[(int(i)-1)]==uncompressed: ValueError: invalid literal for int() with base 10: "['1',")
here is my code aswell:
uncompressed = 0
file1 = open ("NonDupT2.txt" , "r")
compressed_sentence=file1.read()
file1.close()
file1 = open ("PositionT2.txt" , "r")
compressed_Positionsonly=file1.read()
file1.close()
compressed_Positions= compressed_Positionsonly.split()
print(str(compressed_Positions))
for i in compressed_Positions:
if compressed_sentence[(int(i)-1)]==uncompressed:
print(compressed_sentence[(int(i))])
uncompressed = compressed_sentence[(int(i))]
else:
print(compressed_sentence[(int(i)-1)])
uncompressed=compressed_sentence[(int(i)-1)]
print(str(int(i)))
however it work when the variables are detemined by the program
uncompressed = 0
compressed_sentence = ['hello' , 'hello' , 'why' , 'hello' , 'lmao']
compressed_Positions = ['1' , '1' , '2' , '1' , '3']
print(str(compressed_Positions))
for i in compressed_Positions:
if compressed_sentence[(int(i)-1)]==uncompressed:
print(compressed_sentence[(int(i))])
uncompressed = compressed_sentence[(int(i))]
else:
print(compressed_sentence[(int(i)-1)])
uncompressed=compressed_sentence[(int(i)-1)]
print(str(int(i)))
A:
The issue is that the compressed_Positions are read wrongly. The file reads the contents as one string. That string is the entire contents of the text file.
The split operator makes a list of strings. The first element of that list is everything from the file until the first space and that appears to be
'[1,'
And that is what is interpreted by int() and that does not work. I think that your PositionT2.txt contains:
[1, 1, 2, 1, 3]
It works if it contained:
1 1 2 1 3
To make the program work the same as the example with the explicit definition, you need a split operator for compressed_sentences as well and your NonDupT2.txt file must contain
hello hello why hello lmao
Instead of spaces, you can also use line breaks as separators in your text file.
Good luck,
Joost
|
[
"stackoverflow",
"0051326430.txt"
] | Q:
Selected value in ComboBox is not inserted correctly into cell
I have the following Excel spreadsheet:
A B
1 ComboBox1
2 1.000
3 10.000
4 100.000
5
This list is loaded into a ComboBox using the following VBA:
Sub UserForm_Activate()
Dim myArr As Variant
Dim myRng As Range
Set myRng = Sheet1.Range("A2:A4")
ReDim myArr(myRng.Cells.Count)
Dim i As Long
For i = LBound(myArr) To UBound(myArr)
myArr(i) = Format(myRng.Cells(i + 1), "#,##")
Next i
ComboBox1.List = myArr
End Sub
This VBA is needed to have the thousands seperator within the ComboBox.
All this works fine so far.
Now I want to insert the selected value from the ComboBox into Cell B1:
Sub ComboBox1_Change()
Sheet1.Range("B1").Value = ComboBox1.Value
End Sub
Unfortunately, this VBA does not insert the value I selected in the ComboBox. It always cuts the last three 0 so when I select 1.000 in the ComboBox in Cell B1 the value 1 is inserted, instead of 10.000 the value 10 is inserted and so on.
I guess the issue is resulting from formatting with the "#,##" in the VBA code for the ComboBox but I could not find a solution yet to keep the thousands sperator in the ComboBox and insert the correct value in Cell B1.
Do you have any idea how I can solve this issue?
A:
10.000 is understood as 10,000 in Excel, thus the last trailing zeroes are removed automatically. To make sure that you get what you want, the best way is to remove the . from the Combobox1 and to pass it to Excel:
Range("B1") = Replace(ComboBox1, ".", "")
There is an option to pass the 2.000 in text format in Excel:
Range("B1") = ComboBox1
|
[
"mathoverflow",
"0000323922.txt"
] | Q:
What is the minimum $k$ such that $A^k \equiv I$ mod p for invertible matrices?
Let $F$ be a finite field of order $p$, where $p$ is prime. For any $n\times n$ matrix $A$ that is invertible over $F$, then there would appear to exist integers $k$ such that $A^{k} = I$. My question is simply what is the minimum value of $k$ (as a function of $n$ and $p$), which I will call $k_{n,p}$, such that this relation holds for all choices of $A$.
Proving that such an integer exists is relatively straightforward. By assumption, there exists a $B$ such that $AB = I$. Furthermore, there are precisely $\gamma_{n}(p) = (p^n - 1)(p^n-p) \ldots (p^n - p^{n-1})$ matrices satisfying the requirements for $A$. Since invertible matrices form a group, this implies that there exist distinct integers $a$ and $b$ between $1$ and $\gamma_{n}(p)+1$ such that $A^a = A^b$, and hence $B = A^{a-b-1} = A^{k-1}$. This implies that $k_{n,p} \leq \gamma_n(p)$. Furthermore, since the order of the group of invertible matrices over $F$ is $\gamma_n(p)$, and the powers of $A$ form a subgroup of this group, Lagrange's theorem implies that $k_{n,p}$ must divide $\gamma_n(p)$. So my question amounts to whether $k_{n,p} = \gamma_n(p)$, or whether you can do better.
This would essentially be an equivalent of Fermat's little theorem for matrices, but in searching such literature I have only been able to turn up trace relations, and so if this is well known, or if my reasoning is flawed, I would appreciate a pointer to the relevant literature (or to my error).
A:
The quantity that you are trying to compute is called the exponent of the group $\text{GL}_n(\mathbb F_p)$. As you note by Lagrange ,it always divides the order of the group. More generally, one can ask about the exponent of the group $\text{GL}_n(\mathbb F_q)$, where $q$ is a power of $p$. You'll find a detailed answer/discussion at https://math.stackexchange.com/questions/292620/exponent-of-gln-q
|
[
"stackoverflow",
"0050508061.txt"
] | Q:
ArangoDB:Can I safely increase the vm.max_map_count as per installation recommendation
When I upgrade to 3.3.5 version of ArangoDB, there is the following warning
2018-05-24T10:25:32Z [26942] WARNING {memory} maximum number of memory mappings per process is 65530, which seems too low. it is recommended to set it to at least 512000
2018-05-24T10:25:32Z [26942] WARNING {memory} execute 'sudo sysctl -w "vm.max_map_count=512000"'
Is it safe to tinker with the system setting (as I understand it)? And what is the meaning of increasing the max_map_count toArangoDb in particular?
A:
It is safe to increase this value. It allows applications to allocate more RAM. The preset value on different distributions are sane values for user interaction. However, when you operate inherently memory-heavy applications like databases, you might have to relax such limits to your needs. Having said that, if you have a malicious program on your system, it also is allowed to allocate more memory.
But let's not forget, that the warning is only a warning. So for as long as your database is not huge, you are not working with lots of open cursors you and don't experience any performance issues, you might not have to make any changes for now. Just keep it in the back of your head, so that you know, what to tweak, when suddenly performance goes down.
Also, the MMFile storage engine is more affected than the RocksDB engine.
|
[
"stackoverflow",
"0006470084.txt"
] | Q:
Template format in C++
I came across the following snippet in the implementation of a N-ary tree in a textbook,
template <typename Object, int N>
From what I understand, a template's main purpose is to provide "generality" to the code so that a particular variable can be of any type, represented via Object
i.e if you have template <typename Object> then we may write the following in the code: Object variable1;, where Object is of any type.
Based on my description,
1) By specifying a particular variable type (in this case int for N) arn't we going against the main purpose of templates?
Then...
2)Why would we do this? Isn't it better to include the N variable in the constructor?
A:
In C++, templates can be instantiated on more than just types. They can be instantiated on specific values, if the programmer so desires. In template<int N> class Foo, N is treated as a constant, if you will: instantiate this template and make the constant N have this value.
Arrays, for example, should be of fixed-size (that's how they are, by definition, expected to behave). Therefore, they should be templated with a given constant size. In the upcoming C++ standard, you can instantiate an array by doing std::array<int, 7>; this is an object of type array-of-ints-of-size-seven — yes, the size is a characteristic of the type of an array.
In a nutshell, C++ also allows you to instantiate templates with values, not just with types, because certain types should be defined by a constant value. In the example I gave, the size of the array is a characteristic of the type, not of the object.
|
[
"stackoverflow",
"0028774328.txt"
] | Q:
Emacs M-x term can't find node/coffee
I've been plonking around on mac-emacs, and I've M-x install-package-d coffee-mode. I decided to try out the coffee-compile-file command, but when I ran it, it failed, complaining that it couldn't find the coffee command.
So, I open up terminal, on ZSH and Bash. coffee and node run fine on both. So, split my emacs screen, plink out M-x term, let bash load, and type coffee:
bash-3.2$ coffee
bash: coffee: command not found
Odd. I tried the same for node and npm.
bash-3.2$ node
bash: node: command not found
bash-3.2$ npm
bash: npm: command not found
My question is, why does this happen only on M-x term, and how can I fix it.
A:
I've found a solution with help from @Etan Reisner and @Akira (Thanks guys!), so I'll post it here. I'll also wait for other people who might want to expand on this answer before giving myself all the credit.
Firstly, as one may find using which coffee, coffee is located in /usr/local/bin. For some reason, M-x term's $PATH doesn't include that directory, whereas terminal bash does.
We can add /usr/local/bin to emacs' $PATH by adding this line to our .emacs:
(setenv "PATH" (concat (getenv "PATH") ":/usr/local/bin"))
Now, when I open up M-x term and run coffee, it works fine:
bash-3.2$ coffee
coffee>
However, I notice that running M-x coffee-repl still fails with 'no such file or directory: coffee'. This can be fixed by adding this to .emacs:
(setq exec-path (append exec-path '("/usr/local/bin")))
Note that doesn't solve the problem of ugly colour escape sequences in the REPL. Ah, well, that's solved elsewhere. Besides, M-x ansi-term works so much better with colour.
|
[
"expressionengine.stackexchange",
"0000015335.txt"
] | Q:
How to hide unused member pages from public/google
I recently discovered that member pages for my EE site are showing up in Google search results, even though I'm not currently using members (beyond super admins) and I have no public member page templates.
Here's an example of the page I'm seeing: http://www.weddingwise.co.nz/member/1
Is there any way to hide all pages with "member" in segment1 so they are not visible to public or to Google?
A:
Under Members -> Preferences in the control panel, you can set the Profile Triggering Word (see docs) to % which will make them completely inaccessible from the frontend.
Another technique is to configure it randomly in the config.php like this:
$config['profile_trigger'] = rand(0,time());
|
[
"stackoverflow",
"0002911094.txt"
] | Q:
Outputting all PHP errors to database not error_log
Is it possible to make all PHP errors be written to MySQL instead of to the standard error_log file. I guess this would be possible if i wrote my own error handler from scratch but i have a lot of legacy code in place and ideally i would just make 1 global change and that would be it. Can this be done?
A:
I don't think it can be done without building an own error handler, but technically, that is the one global change you're looking for.
Modified example from the manual:
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
// you'd have to import or set up the connection here
mysql_query("INSERT INTO error_log (number, string, file, line) ".
"VALUES .....");
/* Don't execute PHP internal error handler */
return true;
}
then
// set to the user defined error handler
$old_error_handler = set_error_handler("myErrorHandler");
|
[
"math.stackexchange",
"0001775430.txt"
] | Q:
Why is $d(f,f_n)=1/2$?
I am having trouble fully understanding this:
For the sequence
$f_n(x) = \frac{x^n}{1+x^n}$
on the interval [0,1], the limit function is
$$f(x) = \left\{\begin{array}{ll}{1\over2}&\text{ if }x=1 \\ 0&\text{ if }x\neq 1\end{array}\right.$$
I am having trouble understanding why $\sup\{|f_n-f|\}$ is $1/2$, even though I've read the answers on this old thread: Uniform convergence with two limits.
I think the argument goes:
If you let $x\rightarrow 1$, you get $f_n=0$ because $f_n$ doesn't take the value of $1/2$ until $x$ is exactly 1. But $f(1)=1/2$ so the supremum is $1/2$. Is this correct?
I just don't understand this argument, because if you let $x\rightarrow1$, isn't $f$ also $0$, for the same reason as $f_n$? (And therefore the supremum should be $0$?).
I hope someone can understand my confusion and perhaps take me through all the steps of showing that the distance is $1/2$.
A:
Fix $n$. Note that
$$
f_{n}(1)=\frac{1^{n}}{1+1^{n}}=\frac{1}{2}.
$$
Since $f_{n}$ is continuous, it follows that there is a sequence
$(x_{m})_{m}$ such that $0\leq x_{m}<1$ for all $n$, $x_{m}\rightarrow1$,
and $f_{n}(x_{m})\rightarrow1/2$. However, $f(x_{m})=0$. Therefore,
we have
$$
\sup_{[0,1]}\left|f_{n}-f\right|\geq\sup_{m}\left|f_{n}(x_{m})-f(x_{m})\right|=\sup_{m}\left|f_{n}(x_{m})\right|=\frac{1}{2}.
$$
As for the reverse direction of the inequality, note that
$$
f_{n}^{\prime}(x)=\frac{nx^{n-1}}{\left(x^{n}+1\right)^{2}}
$$
so that $f_{n}$ is nondecreasing on $[0,1]$. Moreover, $f_{n}(0)=0$
and $f_{n}(1)=1/2$ (as shown above).
|
[
"stackoverflow",
"0010918475.txt"
] | Q:
Struggling to get Mink working with Behat
I've been following this guide (and installed everything through composer): http://docs.behat.org/cookbook/behat_and_mink.html and am attempting to get Behat + Mink working but everytime I try and run bin/behat I get the following error:
PHP Fatal error: Call to a member function getSession() on a non-object in vendor/behat/mink-extension/src/Behat/MinkExtension/Context/RawMinkContext.php on line 80
That line of code is:
return $this->getMink()->getSession($name);
So for some reason the mink attribute is empty but I've no idea why.
My .feature file is exactly the same as the one in the guide, the FeatureContext class is also from the guide:
use Behat\Behat\Context\ClosuredContextInterface,
Behat\Behat\Context\TranslatedContextInterface,
Behat\Behat\Context\BehatContext,
Behat\Behat\Exception\PendingException;
use Behat\Gherkin\Node\PyStringNode,
Behat\Gherkin\Node\TableNode;
use Behat\MinkExtension\Context\MinkContext;
/**
* Features context.
*/
class FeatureContext extends MinkContext
{
}
and my vendor/behat/mink/behat.yml file contains:
context:
extensions:
Behat\MinkExtension\Extension:
base_url: 'http://en.wikipedia.org/'
goutte: ~
selenium2: ~
I've also tried making my class extend BehatContext and then call useContext but that gives me the same error. Behat itself seems to work it's just anything with Mink produces that fatal error and I've no idea how to fix it.
A:
This is because you should copy vendor/behat/behat/behat.yml.dist file to your/project/root/behat.yml, rather than editing the file in the vendor dir and add extesions to the default section.
And here's what it looks like:
default:
extensions:
Behat\MinkExtension\Extension:
base_url: http://lunch-time/app_dev.php
goutte: ~
selenium2: ~
paths:
features: features
bootstrap: features/bootstrap
annotations:
paths:
features: features/annotations
closures:
paths:
features: features/closures
|
[
"hermeneutics.stackexchange",
"0000019653.txt"
] | Q:
What kind of entity does "φάντασμα" in Matthew 14:26 refer to?
In Matthew 14 when the disciples see Jesus walking on the water,
ἐταράχθησαν λέγοντες ὅτι φάντασμά ἐστιν, καὶ ἀπὸ τοῦ φόβου ἔκραξαν.
they were terrified, and said, “It is a ghost!” and they cried out in fear. (Matt 14:26b, ESV)
In Second Temple Judaism, to my knowledge, there was no equivalent to a ghost. Am I wrong? What does "φάντασμα” mean here?
A:
The only definition offered for φάντασμα by the very comprehensive A Greek-English Lexicon of the New Testament (BDAG) is "apparition, especially ghost". As such, we should be cautious of any other interpretation. None-the-less, let's examine the evidence for (near) contemporary belief in ghosts:
A common belief: evidence
Meyer's Commentary suggests that the belief in "apparitions" was common in Jesus' time. He cite's Plato's Phaedo
And, my friend, we must believe that the corporeal is burdensome and heavy and earthly and visible. And such a soul is weighed down by this and is dragged back into the visible world, through fear of the invisible and of the other world, and so, as they say, it flits about the monuments and the tombs, where shadowy shapes of souls have been seen, figures of those souls which were not set free in purity but retain something of the visible; and this is why they are seen.
Euripides' Hecuba (a ghost delivers the entire opening monologue), and Lucian's Philopseudes
'We were only trying,' he said, 'to convince this man of adamant that there are such things as supernatural beings and ghosts, and that the spirits of the dead walk the earth and manifest themselves to whomsoever they will.'
as examples in Greek culture.
Arguably, the most relevant example from the Old Testament (Apocrypha) occurs in Wisdom, which was written 100-200 years before Jesus' time.
Were partly vexed with monstrous apparitions, and partly fainted, their heart failing them: for a sudden fear, and not looked for, came upon them. (17:15 Brenton's translation)
See also Wisdom 17:3-4. Earlier examples include Deut 18:10-11
There shall not be found among you anyone who makes his son or his daughter pass through the fire, one who uses divination, one who practices witchcraft, or one who interprets omens, or a sorcerer, or one who casts a spell, or a medium, or a spiritist, or one who calls up the dead. (NASB)
Although it forbids the practice of calling them, it still is strong evidence in belief of spirits of the dead, that is ghosts.
In I Samuel 28, there is extended passage where Saul has the ghost of Samuel conjectured up by a medium.
See also Josephus' Antiquities (60-70 years after Jesus):
As these men said thus, and called upon Alexander's ghost for commiseration of those already slain, and those in danger of it, all the bystanders brake out into tears.
...And now, O thou most impudent body of mine, how long wilt thou retain a soul that ought to die, in order to appease the ghosts of my brother and my mother?
Other commentaries
Other commentaries agree that the belief in ghosts was likely common among first century Jews. Gill's Exposition says:
The Jews, especially the sect of the Pharisees, had a notion, from whom the disciples might have their's, of spirits, apparitions, and demons, being to be seen in the night; hence that rule, "it is forbidden a man to salute his friend in the night, for we are careful, lest, "it should be a demon".'' (citing T. Bab. Megilla, fol. 3. 1. and Sanhedrim, fol. 44. 1.)
Matthew Poole says
By this it seemeth that the doctrine of spirits was not strange to that age, though they had a sect of Sadducees which denied it.
The Benson Commentary says
that the Jews in general, particularly the Pharisees, believed in the existence of spirits, and that spirits sometimes appeared, is evident from Luke 24:37; Luke 24:39, and Acts 23:8-9.
Conclusion
While some certainly doubted the existence of ghosts, a significant percentage (probably the majority) of the Jewish population believed in ghosts.
|
[
"magento.stackexchange",
"0000189815.txt"
] | Q:
Deploying Static Content on M2 doesn't work
I am trying to deploy static content on my production site but I am receiving the error in the screenshot. Why is this occurring?
A:
I was able to replicate similar behaviour with changing database credentials to wrong ones.
By the error seems that bin/magento executable thinks that the app is not installed and I would start with checking if configs in app/etc folder are correct, all files present and env.php values are correct.
|
[
"stackoverflow",
"0048416016.txt"
] | Q:
How to get the latest file update in last six hours in a folder using python
I am trying to write a python program lists the files updated/created in last six hour using python.
A:
This will give you what you want, although you might want to be careful with timezone offset values -
import os
import datetime as dt
folder_loc = '.'
check_tm = dt.datetime.now() - dt.timedelta(hours=6)
files = os.listdir(folder_loc)
for file in files:
file_loc = os.path.join(folder_loc, file)
updated_tm = os.path.getmtime(file_loc)
updated_dt = dt.datetime.fromtimestamp(updated_tm)
if updated_dt > check_tm:
print('{} was updated within 6 hours'.format(file_loc))
Hope this helps.
|
[
"stackoverflow",
"0001401537.txt"
] | Q:
Get Android View Instance
This is a dumb question and I know the answer is sitting in front of me, I'm just having trouble searching for it in the right way.
I've got a custom view that has been set as the content view and inflated from xml. How can I access the instance to call methods on it from the activity class? I remember seeing something akin to getResourceById() a while back, but now I can't seem to find it and I'm not even sure if that's the best way to do it.
Sorry for the dumb question.
A:
If you have used an inflater, you will be given an instance of a View class. You then use your instance like so
LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = li.inflate(R.layout.small_listview_row, null);
TextView tvItemText = (TextView)row.findViewById(R.id.tvItemText);
|
[
"stackoverflow",
"0060821057.txt"
] | Q:
How to use use recursion to return an array of substrings
I am trying to break a string down into substrings of size 3, and convert each substring into an array of strings, and return the final array recursively.
So far I have the following:
private static String[] substrings(String string) {
// base case
if (string.length() <= 3) return new String[] { string };
// this will return
return (Stream.concat(Arrays.stream(new String[]{string.substring(0,3)}), Arrays.stream(new String[] {string.substring(3)})).toArray(String[]::new));
}
How would you call the last function recursively and how I would merge the String substrings recursively.
Any input appreciated.
A:
is this what you are after? ArrayUtils.addAll() is from apache common lang library.
Although i don't think it is very intuitive and efficient. iterative way is preferred.
String[] substrings(String string){
//exist condition
if (string.length() <= 3) return new String[] { string };
//get the substrings recursively
String first = string.substring(0,3);
return ArrayUtils.addAll(new String[] { first }, substrings(string.substring(3)));
}
|
[
"stackoverflow",
"0025392043.txt"
] | Q:
Why do min-height property which is applied to the outer div increase the height of the inner div?
HTML :
<div>
<div></div>
</div>
CSS :
div {
background: #BCCF03;
min-height: 300px
}
div div {
background: #5DAF33;
height: 22px
}
JSfiddle
As we can see, min-height is applied only to the outer div, but it increases the height of the inner div too. Why does it happen? min-height isn't an inherited property.
A:
It is the way you wrote your css. Give the divs classes and it wont happen.
HTML :
<div class="outer">
<div class="inner"></div>
</div>
CSS :
.outer {
background: #BCCF03;
min-height: 300px
}
.inner {
background: #5DAF33;
height: 22px
}
To further elaborate, you are setting all divs min-height to 300px. This will be the case on all divs unless it is explicitly set afterwards.
|
[
"health.stackexchange",
"0000003316.txt"
] | Q:
Standing up while deeply inhaling can cause a blood pressure fall?
Someone told me a few months ago of a technique to stop hiccups. When I followed the simple instructions given to me at that time it was extremely effective.
Recently, I tried to reproduce the technique:
breathed in while squatting down, placing the knees against the chest;
slowly breathed out while standing up with the arms stretched forward;
hold the breath for about one minute.
The hiccups didn't stop this time, so I thought I must have mistaken the breathing order. Therefore I tried reversing:
breathed out while squatting down;
slowly breathed in (until full lung capacity) while standing up;
Once I stood up, I immediately felt symptoms described in Orthostatic hypotension (found this page through a comment to another question similar to mine):
dimmed vision with flashes and momentary blindness;
generalized numbness/tingling and fainting;
headache.
I squatted down again after approximately 3-5 seconds and the symptoms subsided (with the exception of the headache, which lingered for a while), and I still had the hiccups.
I gave up on the technique and later managed to stop the hiccups while having some yogurt in my mouth and drink it with the head down (close to my knees).
I'm assuming that in the second sequence the blood flows rapidly to the legs and at the same time to the diaphragm to help filling the lungs, causing a blood pressure fall, and the head, in this case, is primarily affected. I'd like to confirm if this makes any sense.
A:
There seem to be a couple different issues under discussion. I will attempt to explain the relevant physiology and respond to the query in the title.
Hiccup interruption. Most physical techniques involve stimulating efferent vagal tone. These are effective.1 Commonly used methods (similar to those used to abort supraventricular tachycardia) include:
cold stimulation of the nasopharynx (upside down with ice water in the mouth will do it),
carotid sinus massage, and
Valsalva maneuver.
In theory, a sudden increase in afterload could also stimulate vagal tone via baroreceptors. When you describe squatting and breath-holding maneuvers, this is reminiscent of techniques that affect afterload and preload,2 namely:
squatting (vs. standing) increases both preload and afterload;
deep inspiration increases preload to the R heart but decreases venous return to the L heart and thus systemic (including carotid sinus) pressure.
In theory, squatting and exhaling would be the combination that most effectively increases afterload and could theoretically trigger a vagal response. However, I’m not aware of any data suggesting that these are practically effective for termination of hiccups.
Orthostasis. You have outlined an effective method of temporarily depriving your brain of adequate blood flow and eliciting symptoms of orthostatic hypotension.3 This is due to decreased preload to the L heart, most marked upon inspiration occurring simultaneous with standing from the squatting position. This tends to trigger the sympathetic nervous system rather than the parasympathetic. It is the latter that is associated with vagal tone helpful for terminating hiccups.
In summary:
Yes, standing up while inhaling will cause systemic blood pressure to fall with resulting decreased cerebral perfusion. This is generally unpleasant and does not come highly recommended. This is unlikely to be effective for hiccups.
1. I have elsewhere outlined the physiology of hiccups (=singultus), which provides some background on why such maneuvers are effective.
2. Techniques known to every med student from their application to dynamic auscultation of heart murmurs.
3. Apologies for the self-promotion, really, but I also answered a question about the visual component of this syndrome, one of the lesser appreciated aspects.
|
[
"stackoverflow",
"0041387646.txt"
] | Q:
Php update database if checkbox is not checked
so I have a dynamically generated table
<tr>
<td><?php echo $row['RequestID']?></td>
<td><?php echo $row['FirstName'] . " " . $row['LastName']?></td>
<td><?php echo $row['DateRequested']?></td>
<td><?php echo $row['DateNeeded']?></td>
<td><?php echo $row['TotalPrice']?></td>
<td><?php echo $row['Company']?></td>
<td><?php echo $row['Account']?></td>
<td><?php echo $row['Brand']?></td>
<td><?php echo $quantity?></td>
<td><input type="checkbox" name="bill[]" value=<?php echo '"' . $row['RequestID'] . '"'; if($row['BillBack'] == "1") {echo "checked='checked'"; } ?></td>
</tr>
and I want to update the database when a row is checked or unchecked.
if(isset($_POST['submit'])){//to run PHP script on submit
if(!empty($_POST['bill'])){
// Loop to store and display values of individual checked checkbox.
foreach($_POST['bill'] as $selected){
echo "hello";
$sql2 = "UPDATE Requests SET BillBack = '1' WHERE RequestID = '$selected'";
$result2 = $conn->query($sql2);
}} elseif(empty($_POST['bill'])){
// Loop to store and display values of individual checked checkbox.
foreach($_POST['bill'] as $selected){
echo "hello";
$sql2 = "UPDATE Requests SET BillBack = '0' WHERE RequestID = '$selected'";
$result2 = $conn->query($sql2);
}}
}
Now. The if statement works like a charm. For every checked checkbox on a submit, that record gets updated. The issue comes with unchecking the checkboxes. As you can see, checked boxes are found by finding what is not empty. But, when I delete that exclamation point, it does not effectively do the opposite. It also doesn't work as it's own if statement, as a straight else statement, and checking for !isset. Is this because of how the inputs are deemed checked? is there a syntax error? I've done about 5 hours of error checking, googling, and I couldn't figure it out.
Thanks guys
A:
Its very simple: just update ALL your entries to 0, an then set 1 on those that are checked.
//to run PHP script on submit
if(isset($_POST['submit'])){
// Setting everyone to 0
$sql2 = "UPDATE Requests SET BillBack = '0'";
$result2 = $conn->query($sql2);
// Setting only those checked to 1
if(!empty($_POST['bill'])){
// Loop to store and display values of individual checked checkbox.
foreach($_POST['bill'] as $selected){
echo "hello";
$sql3 = "UPDATE Requests SET BillBack = '1' WHERE RequestID = '$selected'";
$result3 = $conn->query($sql3);
}
}
}
EDIT:
Be aware that having queries inside a foreach may cause overload in your server, to avoid this, you can store the ids of entries that you want to update and use it in only one query outside the foreach:
//to run PHP script on submit
if(isset($_POST['submit'])){
// Setting everyone to 0
$sql2 = "UPDATE Requests SET BillBack = '0'"; // Maybe add a WHERE clause, like BizzyBob pointed out
$result2 = $conn->query($sql2);
// Setting only those checked to 1
if(!empty($_POST['bill'])){
// Initialize an array of selected ids
$selected_ids = array();
// Loop to store individual checked checkboxes on array
foreach($_POST['bill'] as $selected){
$selected_ids[] = $selected;
}
// Get the ids separated by comma
$in_clause = implode(", ", $selected_ids);
// Do only one sql query
$sql3 = "UPDATE Requests SET BillBack = '1' WHERE RequestID in (".$in_clause.")";
$result3 = $conn->query($sql3);
}
}
|
[
"stackoverflow",
"0008866672.txt"
] | Q:
AndEngine SceneTouchEvent
I am using AndEngines onSceneTouchEvent method to create a jump affect for a sprite.
The issue i am having is that if the user touches the screen for instance they triple tap the screen the sprite will keep jumping, what i want is for it to receive only 1 click and do one jump for the one touch.
Here is what i am using which is causing this issue.
As you see i try to use a mIsJumping boolean and when the player collides with a invisible rectangle, it is set to false again to allow for jumping again.
@Override
public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
if(pSceneTouchEvent.isActionUp()){
if(mIsJumping == false){
SequenceEntityModifier jumpModifier = new SequenceEntityModifier(
new MoveYModifier(.6f, player.getY(), player.getY() - 250, EaseQuadOut.getInstance()),
new MoveYModifier(.6f, player.getY() - 250, player.getY(), EaseBounceOut.getInstance()));
player.registerEntityModifier(jumpModifier);
}
}
return false;
}
From my description above how can i only register one touch even and jump once until the sprite collides with the rectangle?
A:
There's even an easier solution - use an IEntityModifierListener.
Create the listener this way:
final IEntityModifier.IEntityModifierListener listener = new IEntityModifier.IEntityModifierListener() {
@Override
public void onModifierStarted(IModifier<IEntity> pModifier,
IEntity pItem) {
}
@Override
public void onModifierFinished(IModifier<IEntity> pModifier,
IEntity pItem) {
mIsJumping = false;
}
};
Register it to the MoveYModifier that moves the player down. So, when the modifying ends (The jump modification ends), mIsJumping will be false. Also, remember to set mIsJumping to true when the jump starts.
|
[
"stackoverflow",
"0052862997.txt"
] | Q:
Adding multiple middleware to Restify conditionalHandler
Looking to use the Restify conditionalHandler plugin, and I have multiple middleware in certain routes.
Looking to convert this:
server.put('/forceUpdate', middleware.requiresLogin, versionController.update);
into something like this
server.put('/addVersion', restify.plugins.conditionalHandler([
{version: '1.1.3', handler: middleware.requiresLogin, versionController.update},
{version: '2.0.1', handler: middleware.requiresLogin, versionController.update}
]));
I can't chain the middleware in the handler, is there a best practice for this?
Does handler accept an array?
My other thought adding more middleware as conditionalHandlers, but that seems excessive.
Any help would be appreciated.
A:
Yes, you can pass an array of middleware functions according to the documentation. So your code will look like this:
server.put('/addVersion', restify.plugins.conditionalHandler([
{version: '1.1.3', handler: [middleware.requiresLogin, versionController.update]},
{version: '2.0.1', handler: [middleware.requiresLogin, versionController.update]}
]));
|
[
"stackoverflow",
"0009457243.txt"
] | Q:
How to select a text box on a webpage
How can I select a text box that is available on a webpage so that my program can add data to the selected text box?
I am trying to setup a C# program that will auto login to a series of websites.
Example website:
http://what.cd/login.php
Current Code:
private void login()
{
System.Net.HttpWebRequest whatCDReq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://what.cd/login.php");
HTMLDocument htmlDoc = new HTMLDocumentClass();
htmlDoc = (HTMLDocument)webBrowser1.Document;
HTMLInputElement username = (HTMLInputElement)htmlDoc.all.item("p", 0);
username.value = "Test";
}
A:
Look, what you want to do is send form requests to the server. Parse the webpage for text box form controls and submit the data in a format that the server can use (usually, the data handling is done within PHP on the server end).
Look in the webpage file for a reference to the Javascript function that performs the action itself (it should format the data and send it to the server). I'd recommend implementing that by translating it to your language of choice OR you could run the Javascript function directly through some 3rd party library (despite what you may think, I find that the first option is ultimately easier for small tasks like this).
|
[
"math.stackexchange",
"0000027662.txt"
] | Q:
extend an alternative definition of limits to one-sided limits
The following theorem is an alternative definition of limits. In this theorem, you don't need to know the value of $\lim \limits_{x \rightarrow c} {f(x)}$ in order to prove the limit exists.
Let $I \in R$ be an open interval, let $c \in I$, and let $f: I-{c} \rightarrow R$ be a function. Then $\lim \limits_{x \rightarrow c} {f(x)}$ exists if for each $\epsilon > 0$, there is some $\delta > 0$ such that $x,y \in I-{c}$ and $\vert x-c \vert < \delta$ and $\vert y-c \vert < \delta$ implies $\vert f(x)-f(y) \vert < \epsilon$.
I have extended this to a theorem for one-sided limits: $\lim \limits_{x \rightarrow c+} {f(x)}$ exists if or each $\epsilon > 0$, there is some $\delta > 0$ such that $c<x<c+ \delta$, and $c<y<c+ \delta$ implies $\vert f(x)-f(y) \vert < \epsilon$.
My question is: how to prove this extension to one-sided limits? I'm not familiar with Cauchy sequences, so I would prefer $\epsilon$-$\delta$ proof.
A:
You have essentially the same difficulty as in the previous question: figuring out a "target" number $L$ for the limit.
(By the way: if you don't know what Cauchy sequences are, you should have said something in that previous problem!)
You can proceed in a similar manner. First, you want to find a potential "target." For $\epsilon_n = \frac{1}{n}$, you know there is a $\delta_n$ (which you may assume is less than or equal to $\frac{1}{n}$ and less than $\delta_{n-1}$) such that for all $x$ and $y$, if $c\lt x\lt c+\delta_n$ and $c\lt y \lt c+\delta_n$, then $|f(x)-f(y)|\lt \frac{1}{n}$.
Note that this means that the values of $f$ on $(c,c+\delta_n)$ are bounded: for any $x\in (c,c+\delta_n)$, you know that $|f(x) - f(c+\delta_n/2)|\lt \frac{1}{n}$, so $|f(x)| \lt \frac{1}{n}+|f(c+\delta_n/2)|$.
In particular, there is a greatest lower bound $a_n$ to $f(c,c+\delta_n)$. Since $(c,c+\delta_{n+1})\subseteq (c,c+\delta_n)$, we have that $a_n\leq a_{n+1}$. So the sequence $a_1,a_2,\ldots$ is an increasing function. The sequence is bounded above, so the sequence converges to some $L$.
The obvious "target" for the limit is $L$. So, let $\epsilon\gt 0$, and you want to show that there is a $\delta\gt 0$ such that for all $x$, if $c\lt x\lt c+\delta$, then $|f(x)-L|\lt \epsilon$.
Since $L$ is the least upper bound of $a_1,a_2,\ldots$, there exists $N$ such that $L-\frac{\epsilon}{2} \lt a_n \leq L$ for all $n\geq N$. And there exists an $M$ such that $\frac{1}{M}\lt \frac{\epsilon}{4}$. Let $K=\max\{M,N\}$, and consider $\delta=\delta_K$.
We know that since $a_K$ is the greatest lower bound of $f(c,c+\delta_K)$, there exists $y\in (c,c+\delta_K)$ such that $a_K\leq f(y)\lt a_K+\frac{\epsilon}{4}$.
Now suppose that $c\lt x \lt c+\delta_K$. Then
\begin{align*}
|f(x)-L| &\leq |f(x)-f(y)|+|f(y)-a_K| + |a_K-L| &&\mbox{(triangle inequality)}\\\
&\lt \frac{1}{K} + |f(y)-a_K| + |a_K-L| &&\mbox{(choice of $\delta_K$)}\\\
&\leq \frac{1}{K} + \frac{\epsilon}{4} + |a_K-L| &&\mbox{(choice of $y$)}\\\
&\leq \frac{1}{K} + \frac{\epsilon}{4} + \frac{\epsilon}{2} &&\mbox{(since $K\geq N$)}\\\
&\lt \frac{\epsilon}{4} + \frac{\epsilon}{4} + \frac{\epsilon}{2} &&\mbox{(since $K\geq M$)}\\\
&=\epsilon.
\end{align*}
(With this in mind, you can try doing the two-sided version of the problem without invoking Cauchy sequences; the idea is very similar, and you don't need to consider both least upper bounds and greatest lower bounds for $f(c-\delta_n,c+\delta_n)$, just one of the two and use their limit as a "target". Once you know what to aim for, hitting it becomes much easier).
|
[
"stackoverflow",
"0025409815.txt"
] | Q:
Project No Longer Functional in Android Studio
I originally imported the Adobe Marketing Cloud (Omniture) v3x into my project, then changed my mind and replaced it with v4. I ran into problems with v4 though, and decided to remove it and go back to the original v3 library. When I tested it last night, it was working fine and sending hits like I expected. This morning I fired it up, and the project no longer works at all. It tries to start up, seems to fail at remotely loading assets (never a problem before), and eventually crashes without giving me a meaningful exception. All I get are screens and screens of stuff like this:
08-20 12:17:05.018 31576-31777/com.newspress.hurricanehub D/dalvikvm﹕ JIT unchain all for threadid=1
08-20 12:17:05.769 31576-31777/com.newspress.hurricanehub W/dalvikvm﹕ threadid=32: spin on suspend #1 threadid=1 (pcf=0)
08-20 12:17:06.519 31576-31777/com.newspress.hurricanehub W/dalvikvm﹕ threadid=32: spin on suspend #2 threadid=1 (pcf=0)
08-20 12:17:06.519 31576-31777/com.newspress.hurricanehub I/dalvikvm﹕ "downloader" prio=5 tid=32 RUNNABLE
08-20 12:17:06.519 31576-31777/com.newspress.hurricanehub I/dalvikvm﹕ | group="main" sCount=0 dsCount=0 obj=0x43195640 self=0x61f07738
08-20 12:17:06.519 31576-31777/com.newspress.hurricanehub I/dalvikvm﹕ | sysTid=31777 nice=10 sched=0/0 cgrp=apps/bg_non_interactive handle=1643150224
08-20 12:17:06.519 31576-31777/com.newspress.hurricanehub I/dalvikvm﹕ | state=R schedstat=( 0 0 0 ) utm=4 stm=1 core=0
08-20 12:17:06.519 31576-31777/com.newspress.hurricanehub I/dalvikvm﹕ at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
08-20 12:17:06.519 31576-31777/com.newspress.hurricanehub I/dalvikvm﹕ at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:405)
08-20 12:17:06.519 31576-31777/com.newspress.hurricanehub I/dalvikvm﹕ at com.squareup.okhttp.Connection.upgradeToTls(Connection.java:208)
08-20 12:17:06.519 31576-31777/com.newspress.hurricanehub I/dalvikvm﹕ at com.squareup.okhttp.Connection.connect(Connection.java:161)
08-20 12:17:06.519 31576-31777/com.newspress.hurricanehub I/dalvikvm﹕ at com.squareup.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:246)
08-20 12:17:06.519 31576-31777/com.newspress.hurricanehub I/dalvikvm﹕ at com.squareup.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:186)
08-20 12:17:06.519 31576-31777/com.newspress.hurricanehub I/dalvikvm﹕ at com.squareup.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:375)
08-20 12:17:06.519 31576-31777/com.newspress.hurricanehub I/dalvikvm﹕ at com.squareup.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:328)
08-20 12:17:06.519 31576-31777/com.newspress.hurricanehub I/dalvikvm﹕ at com.squareup.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:196)
08-20 12:17:06.519 31576-31777/com.newspress.hurricanehub I/dalvikvm﹕ at com.squareup.okhttp.internal.http.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
08-20 12:17:06.519 31576-31777/com.newspress.hurricanehub I/dalvikvm﹕ at com.squareup.okhttp.internal.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:25)
08-20 12:17:06.529 31576-31777/com.newspress.hurricanehub I/dalvikvm﹕ at com.mapbox.mapboxsdk.tileprovider.tilesource.WebSourceTileLayer.getBitmapFromURL(WebSourceTileLayer.java:174)
08-20 12:17:06.529 31576-31777/com.newspress.hurricanehub I/dalvikvm﹕ at com.mapbox.mapboxsdk.tileprovider.tilesource.WebSourceTileLayer.getDrawableFromTile(WebSourceTileLayer.java:120)
08-20 12:17:06.529 31576-31777/com.newspress.hurricanehub I/dalvikvm﹕ at com.mapbox.mapboxsdk.tileprovider.tilesource.WebSourceTileLayer.getDrawableFromTile(WebSourceTileLayer.java:28)
08-20 12:17:06.529 31576-31777/com.newspress.hurricanehub I/dalvikvm﹕ at com.mapbox.mapboxsdk.tileprovider.modules.MapTileDownloader$TileLoader.loadTile(MapTileDownloader.java:154)
08-20 12:17:06.529 31576-31777/com.newspress.hurricanehub I/dalvikvm﹕ at com.mapbox.mapboxsdk.tileprovider.modules.MapTileModuleLayerBase$TileLoader.run(MapTileModuleLayerBase.java:316)
08-20 12:17:06.529 31576-31777/com.newspress.hurricanehub I/dalvikvm﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
08-20 12:17:06.529 31576-31777/com.newspress.hurricanehub I/dalvikvm﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
08-20 12:17:06.549 31576-31777/com.newspress.hurricanehub I/dalvikvm﹕ at java.lang.Thread.run(Thread.java:841)
08-20 12:17:06.569 31576-31777/com.newspress.hurricanehub I/dalvikvm﹕ [ 08-20 12:17:06.569 31576:31777 I/dalvikvm ]
"main" prio=5 tid=1 RUNNABLE JIT
I could post my full log if that would helpful, but there's a LOT of that. I've tried everything I know. I took the module out of the project and put it back in, I tried deleting my gradle and iml files and reimporting, I even reset the project to a previous commit from before I changed any libraries or had done anything that would hurt the project. Same result, it's just completely broken now, won't load anything, and eventually crashes. Any insight? I don't really know where to look or what to try at this point.
A:
Turned out I was mistaken in assuming something I had changed in the code was causing the issue. Once I realized older apks were also broken, further testing revealed the data stream for the map was trying to load so many polygons it was crashing the Linux kernel. Once I removed the polygons from the map, everything worked fine. If something breaks I just always figure I probably broke it, but that isn't always a safe assumption!
|
[
"stackoverflow",
"0056084604.txt"
] | Q:
regexp_replace to truncate string at specified character with postgresql
I want to get friendly URLs in postgres. Example:
I would like url = https://this-is-the-domain-i-want/?but_not_this#stuff%stuff and url = https://this-is-the-domain-i-want/this-too/?but_not_this#stuff%stuff to return https://this-is-the-domain-i-want/ and https://this-is-the-domain-i-want/this-too/ respectively.
I can successfully use a nested regexp_replace for this:
REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(url, '\?(.)', ''), '\%(.)', ''), '#(.*)', '')
but I was hoping for something cleaner (that wouldn't require iterating over that url multiple times.
I know regex has a | or, but I've tried REGEXP_REPLACE(url, '\?(.*)|\%(.*)|\#(.*)|\_(.*)', '') with no success.
A:
So basically you just want to remove the query string and fragments, i.e. everything after a ? including the ? and analog for #.
That would be:
regexp_replace(url, '[\?#].*', '');
I wouldn't remove _ and % as they can have meaning in the identification of main resource (_ is just a legal character and % introduces an URL encoded character).
|
[
"stackoverflow",
"0008429695.txt"
] | Q:
How to apply turnstile effect for each UI element in a page
When the application starts, I have a splashscreen after which the mainpage.xaml is loaded. The Mainpage has a lot of UI elements such as buttons and textblocks. It takes about a second or two to load this so I thought some animation could fill in the gap. Else it might look a bit awkward.
Windows phone native application such as the messages, uses some default animation when the page opens right, the pivot headers swivels in then followed by the other UI, the door opening kind of thing. After a bit of researchin I found that they are the default fault turnstile animations.
<toolkit:TransitionService.NavigationInTransition>
<toolkit:NavigationInTransition>
<toolkit:NavigationInTransition.Backward>
<toolkit:TurnstileTransition Mode="BackwardIn"/>
</toolkit:NavigationInTransition.Backward>
<toolkit:NavigationInTransition.Forward>
<toolkit:TurnstileTransition Mode="ForwardIn"/>
</toolkit:NavigationInTransition.Forward>
</toolkit:NavigationInTransition>
</toolkit:TransitionService.NavigationInTransition>
<toolkit:TransitionService.NavigationOutTransition>
<toolkit:NavigationOutTransition>
<toolkit:NavigationOutTransition.Backward>
<toolkit:TurnstileTransition Mode="BackwardOut"/>
</toolkit:NavigationOutTransition.Backward>
<toolkit:NavigationOutTransition.Forward>
<toolkit:TurnstileTransition Mode="ForwardOut"/>
</toolkit:NavigationOutTransition.Forward>
</toolkit:NavigationOutTransition>
</toolkit:TransitionService.NavigationOutTransition>
So I have put in the above code just above the </phone:PhoneApplicationPage> tag of the MainPage. But the elements of the page do not have the turnstile animation, how can i apply it to the other UI elements in the page?? Could someone guide me on this?
Alfah
A:
What you are referring to is called a "feather turnstile" or "peel" transition.
There are three implementations that I know of:
Colin Eberhardt's "peel" animation as part of his Metro In Motion series (free, includes source)
Clarity Consulting's turnstile transition (free, includes source)
Telerik's RadControls for Windows Phone (not free, no source)
None of the above integration into the toolkit's transition framework. I've considered doing so myself, but never had the time.
A:
The Windows Phone Toolkit also has the TurnstileFeather transition. This basically seems to be activated as follows,
Change App.xaml.cs so that RootFrame = new TransitionFrame()
Include the toolkit in the XAML for the animated page e.g. xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
Include the following XAML just after the opening tag (similar to what you pasted),
<toolkit:TransitionService.NavigationInTransition>
<toolkit:NavigationInTransition>
<toolkit:NavigationInTransition.Backward>
<toolkit:TurnstileFeatherTransition Mode="BackwardIn"/>
</toolkit:NavigationInTransition.Backward>
<toolkit:NavigationInTransition.Forward>
<toolkit:TurnstileFeatherTransition Mode="ForwardIn"/>
</toolkit:NavigationInTransition.Forward>
</toolkit:NavigationInTransition>
</toolkit:TransitionService.NavigationInTransition>
<toolkit:TransitionService.NavigationOutTransition>
<toolkit:NavigationOutTransition>
<toolkit:NavigationOutTransition.Backward>
<toolkit:TurnstileFeatherTransition Mode="BackwardOut"/>
</toolkit:NavigationOutTransition.Backward>
<toolkit:NavigationOutTransition.Forward>
<toolkit:TurnstileFeatherTransition Mode="ForwardOut"/>
</toolkit:NavigationOutTransition.Forward>
</toolkit:NavigationOutTransition>
</toolkit:TransitionService.NavigationOutTransition>
Finally on each container element place the following attribute toolkit:TurnstileFeatherEffect.FeatheringIndex="0" with the number relating to the order in which you want the elements to peel away in. e.g.
<TextBlock toolkit:TurnstileFeatherEffect.FeatheringIndex="0">Cheetah</TextBlock>
<TextBlock toolkit:TurnstileFeatherEffect.FeatheringIndex="1">Hare</TextBlock>
<TextBlock toolkit:TurnstileFeatherEffect.FeatheringIndex="2">Tortoise</TextBlock>
|
[
"pt.stackoverflow",
"0000233432.txt"
] | Q:
Problema ao gravar os dados da ComboBox no Postgresql
Primeiro este é o código do banco que estou utilizando:
CREATE TABLE perguntas (
cod_pergunta SERIAL PRIMARY KEY NOT NULL,
pergunta VARCHAR(500),
opcao_um VARCHAR(500),
opcao_dois VARCHAR(500),
opcao_tres VARCHAR(500),
opcao_quatro VARCHAR(500),
opcao_correta INTEGER,
IDcategoria INTEGER,
CONSTRAINT fk_categoria FOREIGN KEY (IDcategoria) REFERENCES categoria(cod_categoria)
);
CREATE TABLE categoria (
cod_categoria SERIAL PRIMARY KEY NOT NULL,
categoria VARCHAR(15),
descricao VARCHAR(140)
);
Eu consigo gravar os valores na tabela perguntas porém o valor do combobox 'categoria' está gravando errado quando tento gravar o primeiro valor.
Imagem do formulário:
Código do botão Gravar:
private void btnGravar_Click(object sender, EventArgs e)
{
//Verifica qual radio button está selecionado
int valor;
valor = 0;
if (rbCorreta1.Checked == true)
valor = 1;
else if (rbCorreta2.Checked == true)
valor = 2;
else if (rbCorreta3.Checked == true)
valor = 3;
else if (rbCorreta4.Checked == true)
valor = 4;
else
MessageBox.Show("Selecione a resposta correta!");
//Verifica qual o valor do combobox está selecionado e guarda o ID para gravar
string IndexSelecionado = cbCategoria.SelectedIndex.ToString();
string str = "Host=127.0.0.1;Username=postgres;Password=adm;Database=dbquiz";
string gravarsql = "INSERT INTO perguntas (pergunta, opcao_um, opcao_dois, opcao_tres, opcao_quatro, opcao_correta, idcategoria) " + " VALUES ('" + txtPergunta.Text + "', '" + txtResposta1.Text + "', '" + txtResposta2.Text + "', '" + txtResposta3.Text + "', '" + txtResposta4.Text + "', '" + valor + "', '"+ IndexSelecionado + "');";
Npgsql.NpgsqlConnection con = new Npgsql.NpgsqlConnection(str);
Npgsql.NpgsqlCommand cmd = new Npgsql.NpgsqlCommand(gravarsql, con);
cmd.CommandType = CommandType.Text;
con.Open();
try
{
int n = cmd.ExecuteNonQuery();
if (n > 0)
{
MessageBox.Show("Efetuado!");
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.ToString());
}
finally
{
con.Close();
}
}
O erro que aparece é este abaixo, porém só acontece quando quero gravar o 1º valor do combobox porque os demais da pra gravar só que grava o index errado:
Ex.
categorias: 1-Teste, 2-Foo, 3-Stack;
Quando seleciono o 2, grava o 3.
Código para preencher o Combobox:
string str = "Host=127.0.0.1;Username=postgres;Password=adm;Database=dbquiz";
Npgsql.NpgsqlConnection con = new Npgsql.NpgsqlConnection(str);
con.Open();
try
{
string sql = "SELECT categoria.cod_categoria, categoria.categoria FROM categoria;";
Npgsql.NpgsqlCommand cmd = new Npgsql.NpgsqlCommand(sql, con);
Npgsql.NpgsqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
this.cbCategoria.DataSource = dt;
this.cbCategoria.DisplayMember = "categoria";
this.cbCategoria.ValueMember = "cod_categoria";
reader.Close();
reader.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
con.Dispose();
}
A:
Isso acontece porque você está usando o SelectedIndex como o valor de categoria, só que não necessariamente estes valores (index do combobox e id da tabela) serão correspondentes. Na verdade, é muito difícil que isso aconteça.
O que você precisa salvar é o Id da categoria selecionada. Como você preenche o combobox com DisplayMember e ValueMember, pode apenas alterar uma linha de código para resolver isso.
Esta linha
string IndexSelecionado = cbCategoria.SelectedIndex.ToString();
Deveria ser
string IndexSelecionado = cbCategoria.SelectedValue.ToString();
Aliás, seria bom também mudar o nome da variável para não ficar confuso, mas isso é com você.
Acho importante comentar que você está fazendo um mau uso das exceções mostrando apenas a mensagem dela. Uma das coisas que você mais vai precisar quando tiver ocorrendo uma exceção na aplicação é o stacktrace (que está sendo ignorado) para poder rastreá-la.
Outra coisa é que seria legal separar as responsabilidades da aplicação, fazer a conexão com o banco em um lugar apenas e reaproveitar isso em outros lugares. Isso evita bastante repetição de código e ajuda na manutenção mais tarde.
Claro que estes não são pontos principais da pergunta, só achei importante citá-los.
|
Subsets and Splits