text
stringlengths
64
89.7k
meta
dict
Q: PHP: encoding meta data for Facebook Strangest thing: I'm trying to get facebook to recognize the "&" sign within the <meta property='og:title' content="data"/> field. I have content being extracted from a db where I urlencode: & becomes &amp; but facebook doesn't pick up the encoding.. Except, when I just plainly add a &amp; to the code itself, it picks it up.. It seems as though it's specifically having an issue with reading the php conversion of the symbols. Any idea? Been stuck on this for too long. I've been using the facebook linter to test this. A: If nobody else gives you an exact fix, I think you might benefit from looking at the raw HTTP traffic. There are lots of tools, the lowest level is wire shark.
{ "pile_set_name": "StackExchange" }
Q: Añadir elemento nuevo a lista Tengo un problema a la hora de añadir un elemento a una lista al final de la lista . La función que tengo es: void aniadir(struct Lista *lista){ struct Alumno aux; printf("Escribe numero matricula, nombre, apellidos y nota del alumnos"); scanf("%d %s %s %d", &aux.Matricula, &aux.Nombre, &aux.Apellidos, &aux.Nota); lista->Datos[lista->Numero]=aux; lista->Numero++; //Estos printf son solo para comprobar printf("\n %d %s %s %d", aux.Matricula, aux.Nombre, aux.Apellidos, aux.Nota); printf("\n %d %s %s %d", lista->Datos[lista->Número].Matricula, lista->Datos[lista->Número].Nombre, lista->Datos[lista->Número].Apellidos, lista->Datos[lista->Número].Nota); } También he probado a: lista->Datos[lista->Número].Matricula=aux.Matricula; lista->Datos[lista->Número].Nombre=aux.Nombre; lista->Datos[lista->Número].Apellidos=aux.Apellidos; lista->Datos[lista->Número].Nota=aux.Nota; En vez de: lista->Datos[lista->Número]=aux; No me aparecen errores. Cuando ejecuto el programa e intento añadir a 457 Marcos FernandezGarcia 8 El resultado es: 457 Marcos FernandezGarcia 8 273738382882 @ Pwk 2893 Por lo tanto el alumno si está guardado en aux pero no soy capaz de meterlo en la lista Las estructuras son: typedef char Cadena [MAX] struct Alumno{ int Matricula; Cadena Nombre; Cadena Apellidos; int Nota; }; struct Lista{ int Numero; struct Alumno Datos[MAXC]; }; // MAX está declarado al principio con valor 40 // MAXC está declarado al principio con valor 30 Estoy trabajando en Code::Blocks Main: int main(){ struct Lista lista; FILE *f; lista.Numero=0; int n; meterEnLista(&lista) //Esta función mete los datos del fichero en la lista do{ printf("Seleccione la operacion \n1.Mostrar Lista\n2.Añadir Alumno\n3.Guardar Lista\n0. Salir"); scanf("%d", &n); switch(n){ case 1: mostrarLista(&lista); //Recorre la lista. Funciona perfectamente break; case 2: aniadir(&lista); break; case 3: fichero=fopen("Clase.txt","w"); guardarLista(&lista,f); //Guarda en el fichero la lista. Funciona perfectamente break; } while( n!=0); return 0; } A: El código tiene varios errores: 1.- El miembro Datos no es un array de estructuras, por lo tanto, es ilegal escribir una sentencia así: lista->Datos[lista->Número]=aux; 2.- El tipo del miembro Datos no puede ser Lista, de lo contrario, no podrás tener acceso a los miembros de la estructura Alumno. La estructura Lista debería estar definida de esta forma: struct Lista { int Número; struct Alumno Datos[50]; }; 3.- En la función scanf debes pasar la dirección de memoria de la variable y no su contenido: scanf("%d", n); Esto provoca un fallo de segmentación, ya que la función estaría accediendo a memoria que no le pertenece al programa. Solución: //El ampersand se usa para pasar la dirección de memoria de "n". scanf("%d", &n); 4.- Estás incrementando el miembro Numero antes de mostrar la información: lista->Datos[lista->Numero]=aux; lista->Numero++; //Estos printf son solo para comprobar printf("\n %d %s %s %d", aux.Matricula, aux.Nombre, aux.Apellidos, aux.Nota); printf("\n %d %s %s %d", lista->Datos[lista->Número].Matricula, lista->Datos[lista->Número].Nombre, lista->Datos[lista->Número].Apellidos, lista->Datos[lista->Número].Nota); Al principio Numero vale 0 pero luego lo incrementas a 1 y recién ahí muestras la información, sin embargo, imprimirá contenido basura, porque la información está en la posición anterior (en este caso en la posición 0). Solución: Debes incrementar el miembro Numero al final: lista->Datos[lista->Numero]=aux; //Estos printf son solo para comprobar printf("\n %d %s %s %d", aux.Matricula, aux.Nombre, aux.Apellidos, aux.Nota); printf("\n %d %s %s %d", lista->Datos[lista->Número].Matricula, lista->Datos[lista->Número].Nombre, lista->Datos[lista->Número].Apellidos, lista->Datos[lista->Número].Nota); lista->Numero++; Recomendación: Deberías de añadir una condición en la función aniadir para que no sobrepase el límite del array (en este caso es 50).
{ "pile_set_name": "StackExchange" }
Q: Dynamic-usercontrol click event UserControl: private string lastName; public string LastName { get { return lastName; } set { lastName = value; lastNameTextBox.Text = value; } } Form: using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString)) { myDatabaseConnection.Open(); using (SqlCommand SqlCommand = new SqlCommand("Select LasatName from Employee", myDatabaseConnection)) { int i = 0; SqlDataReader DR1 = SqlCommand.ExecuteReader(); while (DR1.Read()) { i++; UserControl2 usercontrol = new UserControl2(); usercontrol.Tag = i; usercontrol.LastName = (string)DR1["LastName"]; usercontrol.Click += new EventHandler(usercontrol_Click); flowLayoutPanel1.Controls.Add(usercontrol); } } } The form loads the records from database and display each LastName in each usercontrols' textbox that created dynamically. How to show additonal information such as address in form's textbox when a dynamic-usercontrol is click? Attempt: private void usercontrol_Click(object sender, EventArgs e) { using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString)) { myDatabaseConnection.Open(); using (SqlCommand mySqlCommand = new SqlCommand("Select Address from Employee where LastName = @LastName ", myDatabaseConnection)) { UserControl2 usercontrol = new UserControl2(); mySqlCommand.Parameters.AddWithValue("@LastName", usercontrol.LastName; SqlDataReader sqlreader = mySqlCommand.ExecuteReader(); if (sqlreader.Read()) { textBox1.Text = (string)sqlreader["Address"]; } } } } A: First. In your first code fragment, you execute "Select ID from ...", but expect to find field "LastName" in the reader - not going to work. Second. If you know that you will need more information from Employee table, I suggest that you store it in the same UserControl where you put the LastName. Execute "Select * from ...", add another field and property to UserControl2 and assign it in the Read loop: usercontrol.Address = (string)DR1["Address"]; Third. In your second code fragment, use UserControl2 usercontrol = (UserControl2)sender; instead of UserControl2 usercontrol = new UserControl2(); because newly created user control will not have any LastName assigned. Then: private void usercontrol_Click(object sender, EventArgs e) { UserControl2 usercontrol = (UserControl2)sender; textBox1.Text = usercontrol.Address; }
{ "pile_set_name": "StackExchange" }
Q: ASP split config files For a school project we are trying to get our ASP.net project as modular as we can. We want to split up our Web.config so that we have separate files to store our database queries in. One for each "model" to be exact. I tried to look on the internet for more information about this but I could not really find any good answer to this question that I understood. So how can we split up queries into separate config files and access them? A: First of all I have to back up what others have said, you really should not be storing queries in your web.config, they should be hardcoded in the apps if you aren't using an ORM. If you really want to look into having the queries in files and modular files you could look into using resource files. Now these should be used for localisations and things that are considered "resources" however there is no reason why you couldn't put queries into them. This way you could have one resource file per module. Which is modular as you want. So given your example you would have a resources file called recipes. Then you would have a key of SelectOwn and the value is then your query. You can then access this in your code behind by saying Recipies.SelectOwn which at least is a nicer API. I would though double check your home work, is there a reason you can't put queries in your code? Even as constant strings?
{ "pile_set_name": "StackExchange" }
Q: In a Java Android Application how to search record of Registered users for login via SQLite Database Ok so I am currently trying to make a Simple Register and Log in page using SQL Lite. I currently have no problems with creating or inserting values into the database. What I want to do is using an if-else statement for the Login, whereby it will deny the user if there is no record (or mistyped) found in the database and will only allow when they enter the username and password correctly. Attached is my code. Please advise. Thanks package mdad.project; import com.example.manandhowproject.R; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class Login extends Activity { SQLiteDatabase db; Button btnLogin, btnSignUp; EditText etUsername, etPassword; SQLiteOpenHelper dbhelper; Cursor cursor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login); etUsername = (EditText)findViewById(R.id.etUsername); etPassword = (EditText)findViewById(R.id.etPassword); Button button = (Button)findViewById(R.id.btnLogin); db = dbhelper.getReadableDatabase(); button.setOnClickListener(new OnClickListener(){ public void onClick (View V){ Toast.makeText(getApplicationContext(), "Log In Success ! ", Toast.LENGTH_LONG).show(); Intent msg1 = new Intent(Login.this, Userreg.class); startActivity(msg1); } }); Button btnSignUp = (Button) findViewById (R.id.btnSignUp); btnSignUp.setOnClickListener(new OnClickListener (){ public void onClick (View V) { Toast.makeText(getApplicationContext(), "Sign Up Success ! ", Toast.LENGTH_LONG).show(); String username= etUsername.getText().toString(); String password= etPassword.getText().toString(); String sql = "insert into Registration (Username ,Password) values( '"+username+"','"+password+"')"; String result = updateTable(sql); etUsername.setText(""); etPassword.setText(""); }}); String sql="create table if not exists Registration (recld integer PRIMARY KEY autoincrement, Username text, Password text)"; String result = createDatabase(sql, "Reg.db"); } String createDatabase(String sql, String dbName) { try{ System.out.println(sql); db = SQLiteDatabase.openOrCreateDatabase("sdcard/" + dbName,null); db.beginTransaction(); db.execSQL(sql); db.setTransactionSuccessful(); db.endTransaction(); } catch (Exception e){ Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show(); System.out.println(e.toString()); return ("error open DB"); } return ""; } String updateTable(String sql) { try{ System.out.println(sql); db.beginTransaction(); db.execSQL(sql); db.setTransactionSuccessful(); db.endTransaction(); }catch (Exception e) { System.out.println(e.toString()); return ("Error updating DB"); } return ("DB updated"); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } A: CHECK THIS THREAD TOO CURSOR DISCUSSION on STACK Try something like this! I would recommend to make a. separate class inherited by SqliteOpenHelper so you could work with more clean code public Cursor getUserLogedIn(String Sql,SQLiteDatabase db){ Cursor mCursor =db.rawQuery(sql) return mCursor; } //then do this to read in your click listener after execution of the method Cursor incmoningCursor = getUserLogedIn("select * from Registration where username="+incomingUserEmail+ "and password="+incmoingPassword,db) try { while (cursor.moveToNext()) { ... //read out the cursor and compare each string with your //editTextString here } } finally { cursor.close(); } } or you can send directly your entered texts into the method like this public int checkLogin(String incomingUsername, String incomingPassword){ String[] selectionArgs = new String[]{incomingUsername, incomingPassword}; try { int i = 0; Cursor c = null; c = db.rawQuery("select * from Registration where username=? and password=?", selectionArgs); c.moveToFirst(); i = c.getCount(); c.close(); return i; } catch(Exception e) { e.printStackTrace(); } return 0; in the main activity of your button listener try this! button.setOnClickListener(new OnClickListener(){ public void onClick (View V){ if(checkLogin(etUsername.getText().toString(), etPassword.getText().toString()) == 1){ Toast.makeText(getApplicationContext(), "Log In Success ! ", Toast.LENGTH_LONG).show(); Intent msg1 = new Intent(Login.this, Userreg.class); startActivity(msg1); }else{ Toast.makeText(getApplicationContext(), "Wrong Username/password combination", Toast.LENGTH_LONG).show(); } } });
{ "pile_set_name": "StackExchange" }
Q: Did my former supervisor steal my research proposal? When I was a master student I worked in a PhD proposal with my master's supervisor. I applied with that proposal to obtain a scholarship from the university, however because I did not get the scholarship, and she didn't have money for paying the research expenses for the study I couldn't pursue the project. Recently, checking the university page of my former supervisor, I saw advertised the same proposal I wrote and submitted for the scholarship application, exactly with the same words, same theoretical framework, same research questions, etc., she did not change a thing, and she is now advertising it as a "possible PhD project" for a new student that would like to apply for it (and probably get the money we needed for the research). Is that considered as stealing work? Can I report her somehow? I wrote all the proposal with constant feedback from her so I don't know if that gives her full authorship of it? A: It was a proposal, not a publication. The ethics would depend at least a bit on how much she contributed to the effort. But it isn't necessary for her to leave the research undone if you have gone away and she participated. She can certainly follow up on it, even with another student. It would really only be unethical if you brought the proposal to her, relatively complete. In would have been better had she contacted you before proceeding, of course. I don't know if that was possible. But if you are still in academia, you might be able to get back into this research, even if not as her student. You need to contact her with a request to participate, reminding her of your earlier work on the proposal. You might be able to achieve an authorship position, provided that you continue to contribute. But your past work probably won't be enough. Note that I'm basing this on the fact that a proposal for research isn't the same as the research being completed. It is a proposal to study something. It is primarily an idea that might go somewhere. If you can't participate, for whatever reason, you might still be able to get an acknowledgement in whatever results from the idea. You have to ask, of course.
{ "pile_set_name": "StackExchange" }
Q: Android lifecycle - are my ideas correct? I have read about android life cycle in a couple of books and official documentation, but still am unable to get my thoughts in one place and understand it completely. I am developing simple app, in which I use fragments, so this makes it even harder, as fragments have separate life cycle from applications. So I would like to ask you a couple of questions: My application is a simple logger of various data, so basically user only needs to enter data and look at it. As I understand, cycles like onPause, onResume, onStop I shouldn't worry about? I guess my real question is which android life cycle methods are essential for every application? Is it considered to be a very bad practice if you are (fragment vise) calling all methods and managing all views in onCreateView? Do you know any simple and yet good guides which could help me to understand how to manage android life cycle correctly? A: OnResume and onPause are very important part of the lifecycle, and you should worry about it. Whenever a user change from you App to another, o goes to the notifications, or whatever, always will be calling onPause() when it goes to another app, and onResume() when it came back. You have to understand that you Activity may be killed, (if the system don't have enough resources), in that case onCreate will be called first, but if not, then will jump the onCreate and goes to onResume(). onStop is mostly no necessary, as you should free all your resources in onPause() because after the onPause call, you don't know if your activity will be killed by the system. Fragments includes the same Activity lifecycle callbacks plus their own callbacks.
{ "pile_set_name": "StackExchange" }
Q: Java power set through backtrack algorithm I seem to be having an issue regarding implementing a power set algorithm using backtrack. What I am trying to achieve is rather simple, generate the power set of any given numbers: Ex. [1 2 3] => [1] [2] [3] ; [1,2] [1,3] [2,3] ; [1,2,3] My algorithm is using a stack to place the numbers, it adds the numbers to the stack and sends them for calculations. The code is as follows: public int calculatePowerSet(int x, LinkedList<Integer> arr) { int size = 1; int nrOfTimes=0; int calculate =0; boolean goOn=true; Stack<Integer> stack = new Stack<Integer>(); int k=0, len = arr.size(); double temp=0.0f; while(size<=len) { goOn=true; stack.push(arr.get(0)); k = arr.indexOf(stack.peek()); temp = size; //ignore these as they are for calculating time temp/=len; //ignore these as they are for calculating time temp*=100; //ignore these as they are for calculating time setPowerSetPrecentage((int)temp); while(goOn) { if(isStopProcess())return 0; if((k==len)&&(stack.size()==0)) goOn=false; else if(stack.size()==size) { String sign = ""; if((stack.size()%2)==0) sign="+"; else sign="-"; calculate =calculateSets(stack.toArray(), sign, calculate, x); k = arr.indexOf(stack.pop())+1; } else if(k==len) k = arr.indexOf(stack.pop())+1; else { prepereStack(stack,arr.get(k)); k++; } } size++; } return calculate; } Here is the calculate method: private int calculate(int[] arr2, int x) { int calc=1; float rez = 0; for(int i=0;i<arr2.length;i++) calc*=arr2[i]; rez = (float)(x/calc); calc = (int) (rez+0.5d); return calc; } The code seems to be working perfectly for all numbers bellow 20, but after that i seem to be getting wrong results. I cannot check manually through the numbers as there are hundreds of combinations. For example for one input of 25 numbers i should get a result of 1229, instead i get 1249. I am not sure what i am missing as i think the algorithm should be working in theory, so if anyone has any suggestions that would be great. A: I would recommend separating out the generation of the power sets from your calculation. While there are some very efficient algorithms for generating power sets I would suggest keeping it quite simple until you need the efficiency. private void forEachSet(List<Integer> currentSet, List<Integer> rest) { if (rest.isEmpty()) { process(currentSet); } else { Integer nextInt = rest.remove(0); forEachSet(currentSet, rest); currentSet.add(nextInt); forEachSet(currentSet, rest); current.remove(nextInt); rest.add(nextInt); } } public forEachSet(List<Integer> set) { forEachSet(new ArrayList<>(), new ArrayList<>(set)); }
{ "pile_set_name": "StackExchange" }
Q: Export a variable from PHP to shell I'm trying to set a variable that should be accessible from outside PHP. Ideally this should be a local variable, but environment variables are also welcome. First, I've tried putenv(), but this gives no result: $ php -r "putenv('PHP_TEST=string');" ; echo $PHP_TEST $ When i call getenv() from the same script — it results in the right 'string' value. Safe mode is off, but the manual says 'PHP_' prefix is vital with safe=on so I use it just in case :) Then I try system() or shell_exec(): $ php -r "shell_exec('PHP_TEST=string');" ; echo $PHP_TEST $ php -r "shell_exec('export PHP_TEST=string');" ; echo $PHP_TEST $ Is there a workaround? what might be the reason? I'm using Ubuntu Linux 9.10 "Karmic", but FreeBSD server gives the same result. A: If you're trying to pass some output to a shell variable, you can do it like this: $ testvar=$(php -r 'print "hello"') $ echo $testvar hello Showing how export affects things: $ php -r '$a=getenv("testvar"); print $a;' $ export testvar $ php -r '$a=getenv("testvar"); print $a;' hello In these examples, the interactive shell is the parent process and everything else shown is a child (and siblings of each other).
{ "pile_set_name": "StackExchange" }
Q: How to remove active class from default tab to another tab based on the URL? I want a John's tab to be active using the class "active" when the page loads. However, if the URL ends with a specific hashtag (in this case #cindy), I want Cindy's tab to activate when the page loads instead (example: 'www.index.html#cindy'). I've gotten the page to activate John's tab so far, but I don't know where to go from here to make go to Cindy's tab based off the URL. Any help would be appreciated. CSS #main-container .onPage.active { display: block; } #main-container .onPage { display: none; } HTML <div id="main-container"> <div class="box"> <div class="btnList" id="tabs"> <ul> <li> <a class="tab linkSection" href="#james"><span>James</span></a> </li> <li> <a class="tab linkSection" href="#cindy"><span>Cindy</span></a> </li> </ul> </div> <div class="onPage" id="james"> <div> <h1 class="icon"><span class="b"></span>Meet James</h1><br> </div> </div> <div class="onPage" id="cindy"> <div> <h1 class="icon"><span class="b"></span>Meet Cindy</h1><br> </div> </div> </div> </div> JS $(document).ready(function() { $("div#james.onPage").addClass("active"); }); A: Get hash from url and check if it is blank or not and take decision from that which one to activate. $(document).ready(function() { var hash = window.location.hash; if(hash) { $("div" + hash + ".onPage").addClass("active"); } else { $("div#james.onPage").addClass("active"); } });
{ "pile_set_name": "StackExchange" }
Q: How to map JSON Arrays in RestKit I have some troubles mapping a JSON Array to RestKit. This is what the JSON File looks like: {"issuelist":[ { "issue":[ { "id":1, "beschreibung":"", "name":"Test1" }, { "id":2, "beschreibung":"", "name":"Test2" } ] } ]} I am interested in the "issue"s array. This is my mapping for a single issue: RKObjectMapping *objectMapping = [RKObjectMapping mappingForClass:[self class] usingBlock:^(RKObjectMapping *mapping) { [mapping mapAttributes:@"name", @"beschreibung", nil]; [mapping mapKeyPathsToAttributes: @"id", @"identifier", nil]; }]; And here is how I setup my ObjectMapping RKObjectMappingProvider *omp = [RKObjectManager sharedManager].mappingProvider; RKObjectMapping *issueMapping = [Issue mapping]; [omp addObjectMapping:issueMapping]; [omp setObjectMapping:issueMapping forKeyPath:@"issuelist.issue"]; Unfortunately this doesn't work. I get an log output like this: T restkit.object_mapping:RKObjectMappingOperation.m:152 Found transformable value at keyPath 'name'. Transforming from type '__NSArrayI' to 'NSString' W restkit.object_mapping:RKObjectMappingOperation.m:232 Failed transformation of value at keyPath 'name'. No strategy for transforming from '__NSArrayI' to 'NSString' T restkit.object_mapping:RKObjectMappingOperation.m:339 Skipped mapping of attribute value from keyPath 'name to keyPath 'name' -- value is unchanged ((null)) T restkit.object_mapping:RKObjectMappingOperation.m:322 Mapping attribute value keyPath 'beschreibung' to 'beschreibung' T restkit.object_mapping:RKObjectMappingOperation.m:152 Found transformable value at keyPath 'beschreibung'. Transforming from type '__NSArrayI' to 'NSString' W restkit.object_mapping:RKObjectMappingOperation.m:232 Failed transformation of value at keyPath 'beschreibung'. No strategy for transforming from '__NSArrayI' to 'NSString' T restkit.object_mapping:RKObjectMappingOperation.m:339 Skipped mapping of attribute value from keyPath 'beschreibung to keyPath 'beschreibung' -- value is unchanged ((null)) T restkit.object_mapping:RKObjectMappingOperation.m:322 Mapping attribute value keyPath 'id' to 'identifier' T restkit.object_mapping:RKObjectMappingOperation.m:152 Found transformable value at keyPath 'id'. Transforming from type '__NSArrayI' to 'NSString' W restkit.object_mapping:RKObjectMappingOperation.m:232 Failed transformation of value at keyPath 'id'. No strategy for transforming from '__NSArrayI' to 'NSString' T restkit.object_mapping:RKObjectMappingOperation.m:339 Skipped mapping of attribute value from keyPath 'id to keyPath 'identifier' -- value is unchanged ((null)) D restkit.object_mapping:RKObjectMappingOperation.m:624 Finished mapping operation successfully... It seems as if RestKit is trying to map the whole arry in one Issue instead of creating an array of Issues. How do I need to change my mapping to correct this? Thanks for your help! A: Try this: RKObjectMapping* issueMapping = [RKObjectMapping mappingForClass: [Issue class] usingBlock:^(RKObjectMapping *mapping) { [mapping mapAttributes:@"name", @"beschreibung", nil]; [mapping mapKeyPathsToAttributes: @"id", @"identifier", nil]; }]; issueMapping.rootKeyPath = @"issue"; [omp setObjectMaping: issueMapping forKeyPath: @"issuelist"]; This says, when issuelist keypath is encountered use the issueMapping. And then it says for every root issue, create an Issue object.
{ "pile_set_name": "StackExchange" }
Q: Cloning elements [div] [script] in Javascript I'm trying to clone a div in pure Javascript, however, cloneNode leads to duplicate ids (div_0). I would like to increment the id as div_1, div_2... and do the same to somevar = {'elem', 'div_1'}... Thanks <html> <head></head> <body> <div id="mydiv"> <div id="div_0"> <script type="text/javascript"> <!-- somevar = {'elem', 'div_0'}; //--> </script> <p>HELLO</p> </div> </div> <a href="#" onclick="cloning()">CLONE</a> <script type="text/javascript"> function cloning() { var container = document.getElementById('mydiv'); var clone = document.getElementById('div_0').cloneNode(true); container.appendChild (clone); } </script> </body> </html> A: Try this.. ` function cloning() { var container = document.getElementById('mydiv'); var clone = document.getElementById('div_0').cloneNode(true); clone.setAttribute('id','div_'+document.getElementById('mydiv').getElementsByTagName('div').length); container.appendChild (clone); } `
{ "pile_set_name": "StackExchange" }
Q: Can i publish android studio project on iphone app store? I am still a beginner and I really don't know much and am working on my first app on android studio. So is it possible to publish android studio project on iPhone App Store? If not is there any other way to do that? A: You cannot publish a packaged compiled .apk Android Package file to an IOS app store. But an IPA file to IOS store Google Play: - For Google play store you need to register for a Google play dev console account, plus a stock & rooted version of Android latest OS build phone See this Apple Store: - You need to have a Mac, plus an Apple developer license. A code editor like XCode, a know-how of programming language like Swift 3, an SDK toolkit & an iPhone See Link1 and Link2.
{ "pile_set_name": "StackExchange" }
Q: Java Swing: form with text fields I'm doing a form in java. The idea is: When an user insert his name and second name he have to press the "submit" button. Now I would like to listen to this action with the submit button but I don't know how to get what the user put in the text fields: "name" and "second name". I would like to see this data just with the submit button, but i don't know, if it's possible. Or I would like to know in which way I can see all this data when the user clicks on "submit". thanks, this is the code. public class appNegozio extends JFrame { private JPanel contentPane; private JTextField textField; private JTextField textField_1; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { appNegozio frame = new appNegozio(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public appNegozio() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); SpringLayout sl_contentPane = new SpringLayout(); contentPane.setLayout(sl_contentPane); textField = new JTextField(); sl_contentPane.putConstraint(SpringLayout.NORTH, textField, 10, SpringLayout.NORTH, contentPane); sl_contentPane.putConstraint(SpringLayout.WEST, textField, 62, SpringLayout.WEST, contentPane); contentPane.add(textField); textField.setColumns(10); textField_1 = new JTextField(); sl_contentPane.putConstraint(SpringLayout.NORTH, textField_1, 16, SpringLayout.SOUTH, textField); sl_contentPane.putConstraint(SpringLayout.WEST, textField_1, 0, SpringLayout.WEST, textField); contentPane.add(textField_1); textField_1.setColumns(10); JLabel lblNome = new JLabel("Nome"); sl_contentPane.putConstraint(SpringLayout.NORTH, lblNome, 10, SpringLayout.NORTH, contentPane); sl_contentPane.putConstraint(SpringLayout.EAST, lblNome, -7, SpringLayout.WEST, textField); contentPane.add(lblNome); JLabel lblCognome = new JLabel("Cognome"); sl_contentPane.putConstraint(SpringLayout.NORTH, lblCognome, 0, SpringLayout.NORTH, textField_1); sl_contentPane.putConstraint(SpringLayout.EAST, lblCognome, -6, SpringLayout.WEST, textField_1); contentPane.add(lblCognome); JButton btnSubmit = new JButton("Submit"); sl_contentPane.putConstraint(SpringLayout.NORTH, btnSubmit, 24, SpringLayout.SOUTH, textField_1); sl_contentPane.putConstraint(SpringLayout.WEST, btnSubmit, 10, SpringLayout.WEST, contentPane); contentPane.add(btnSubmit); } } A: An easy approach would be to use a final local variable for each JTextField. You can access them from within an ActionListener added to your JButton: final JTextField textField = new JTextField(); btnSubmit.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { System.out.println(textField.getText()); } });
{ "pile_set_name": "StackExchange" }
Q: android.os.NetworkOnMainThreadException Trying to access database from android activity. Android Studio I am getting android.os.NetworkOnMainThreadException in my Login Activity. Basically I am simply trying to check if the user id and password entered by the user are correct i.e., is the user allowed to sign in or not. I have searched for a solution and know that the exception has got something to do with networking on main thread. But I am using AsyncTask. I am still getting this exception. Here is my LoginActivity.java public class LoginActivity extends AppCompatActivity { JSONParser jsonParser = new JSONParser(); // single product url private static final String url_user_check_login = "##########################/android_connect/db_connect.php"; int success=0; String id=""; String password=""; private static final String TAG_SUCCESS = "success"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Defining onClickListener for Login Button Button loginBtn=(Button) findViewById(R.id.login_btn); loginBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Check credentials EditText phone=(EditText)findViewById(R.id.phone_txt); EditText pwd=(EditText)findViewById(R.id.password_txt); id=phone.getText().toString(); password=pwd.getText().toString(); new CheckUserLogin().execute(); if (success == 1) { Intent intent=new Intent(getApplicationContext(), RideDetailsActivity.class); startActivity(intent); }else{ // product with id not found } } }); } class CheckUserLogin extends AsyncTask<String, String, String> { protected String doInBackground(String... params) { // updating UI from Background Thread runOnUiThread(new Runnable() { public void run() { // Check for success tag try { // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("id", id)); // getting product details by making HTTP request // Note that product details url will use GET request JSONObject json = jsonParser.makeHttpRequest( url_user_check_login, "GET", params); // check your log for json response // Log.d("Single Product Details", json.toString()); // json success tag success = json.getInt(TAG_SUCCESS); } catch (JSONException e) { e.printStackTrace(); } } }); return null; } } } I don't know if this is important but I tried debugging and put break points inside the doInBackground method but my debugger just ignores the break points and it just blows past the new CheckUserLogin().execute(); statement. Also here is my exception stack trace. FATAL EXCEPTION: main android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1128) at java.net.InetAddress.lookupHostByName(InetAddress.java:385) at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) at java.net.InetAddress.getAllByName(InetAddress.java:214) at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137) at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:365) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:587) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:511) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:489) at com.heycabs.heycabs.JSONParser.makeHttpRequest(JSONParser.java:65) at com.heycabs.heycabs.LoginActivity$CheckUserLogin$1.run(LoginActivity.java:98)at android.os.Handler.handleCallback(Handler.java:800) at android.os.Handler.dispatchMessage(Handler.java:100) at android.os.Looper.loop(Looper.java:194) at android.app.ActivityThread.main(ActivityThread.java:5409) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:525) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:606) at dalvik.system.NativeStart.main(Native Method) A: You are incorrectly using Asynktask. success == 1 will never excute, since synchronous commands would happen in nanoseconds, and network, would take several milliseconds. Do startActivity(intent) on the Asynk completion.... finally you created a new Thread, and in it, went back to the UI one: runOnUiThread(new Runnable() This is incorrect. Please read documentation on AsynkTask. And read this example
{ "pile_set_name": "StackExchange" }
Q: Can't resolve a simple equation I am stuck with an equation I've been trying to solve for a while in different ways. Tried searching on the internet about the properties of arccosh (or cosh-1) and cosh but still couldn't find the way. I get the feeling the solution to this is going to be easy and stupid, but I feel I've been going in circles here. I need to solve it by hand because I will need to solve this kind of equation in an exam. This is the equation It should be solvable, but in case it's not, I need to say that I've got this after a simplification, in which I don't think I made any mistakes but just in case here is the simplification I made: Here Please note that for U1 and U2 all the variables are unknown but they remain the same for these two cases, except Z. That's why I could simplify it in this way. In case someone is wondering, this is a problem about sea waves. I was given the speed of particles in a given place (at 2 different depths) and I'm using Airy's linear theory to solve it. Thanks in advance! Edit: $$\frac{0.34}{0.44} = \frac{cosh(\frac{90\pi}{x})}{cosh(\frac{110\pi}{x})}$$ Edit2: I suppose I could solve it using iterations, but I will need to do it several times during the exam and I'd rather know if there is a better way to solve it. A: Rewriting the equation, you need to find the zero of $$f(x)=34 \cosh \left(\frac{110 \pi }{x}\right)-44 \cosh \left(\frac{90 \pi }{x}\right)$$ If you try to plot it, you will notice that the fnction varies extremely fast and it is difficult to locate where is more or less the root. So, consider instead $$g(x)=\log \left(34 \cosh \left(\frac{110 \pi }{x}\right)\right)-\log \left(44 \cosh \left(\frac{90 \pi }{x}\right)\right)$$ which is better conditioned (looking more or less like an hyperbola) and, graphing, you will see that there is a root close to $x=200$. At this point, using $x_0=200$, apply Newton method with $$g'(x)=\frac{90 \pi \tanh \left(\frac{90 \pi }{x}\right)}{x^2}-\frac{110 \pi \tanh \left(\frac{110 \pi }{x}\right)}{x^2}$$ You will then get the following iterates : $$\left( \begin{array}{cc} n & x_n \\ 0 & 200.0000000 \\ 1 & 216.3366146 \\ 2 & 217.6456022 \\ 3 & 217.6530075 \\ 4 & 217.6530077 \end{array} \right)$$ which is the solution for ten significant figures. If you want a shortcut, expand $f(x)$ as a Taylor series for large values of $x$. This would give $$f(x)=-10+\frac{27500 \pi ^2}{x^2}+\frac{261387500 \pi ^4}{3 x^4}+O\left(\frac{1}{x^6}\right)$$ and, ignoring the higher order terms, this would give a quadratic in $\frac 1 {x^2}$ for which the solution is $$x^2=\frac{25}{3} \left(165+\sqrt{152691}\right) \pi ^2$$ which makes $x\approx 213.797$
{ "pile_set_name": "StackExchange" }
Q: get date from dateTime in PHP I want to extract date without time from a single value from array result thaht I got. I tried using array_slice but it didn't work. My code.. $dateRows = $this->get('app')->getDates(); $dateRow = json_decode(json_encode($dateRows[0], true)); dump($dateRow[0]);die; And I got result.. "2014-01-01 00:00:00" And I want it to return just "2014-01-01" A: Very Simple, just use date_create() on your date & then format it using date_format() as follows - $date = date_create("2014-01-01 00:00:00"); echo date_format($date,"Y-m-d"); So, in your case, it would be something like - $date1 = date_create($dateRows[0]); echo date_format($date1,"Y-m-d");
{ "pile_set_name": "StackExchange" }
Q: How to use an API from wholesalers to populate inventory on small business website? I've been building some simple websites with django and am somewhat comfortable with it, enough to use models, templates and apps at least. Now, I'm making a website for a friends small business that will have shopping cart functionality, and will display inventory. He doesn't have anything in stock and get's it all from wholesalers, so inventory will be shown directly from wholesalers database who have an API. Everything I could find when searching for a tutorial covered creating an API, not using one. Do I have to have a mode or a database locally? Or is everything taken from the API as a series of get requests? How do I pull say, all cars that are yellow, or all that are yellow made by BMW, and display on my inventory page with pagination? Not asking for a specific set of instructions here, just a very high level overview so I know what to search for to teach myself how to do this. A: consuming an api is not a django related, it 's python related. An easy way to consume an api is python's requests library. Regarding your question on how to handle the data. Both of your ways are possible with some advantages and disadvantages. If you always get the data from the api, they will be always up to date but the load time is longer. If you download all data first to you local database, you need to rebuild their datastructure but loading time it faster and you can use the power of the django orm. A third option might be that you query the product data from the frontend via javascript so that you just have to build views to handle action such as "add to shopping basked" or "checkout".
{ "pile_set_name": "StackExchange" }
Q: Element not visible I'm learning automation with selenium and I'm a bit blocked at the moment with one element. I don't know why it is considered as not visible but elements similar to this one on another part of the website are considered as visible and I don't experience any issue to click on them. To present you the concerned part, this is how it looks: It's a calendar with different shifts, there are three separated parts. When I try to click on the orange shift, I have an error which tells me that this element isn't visible. But on my other scripts which perform the same kind of action but on the other shifts it works well My script is the following one: # Check if the shift is on the schedule or not. if (len(admin.find_elements_by_xpath("//div[@data-shift-date='%s']/div/div[@class='shift-details']" %date))!=0 ): print "The unassigned shift is scheduled, good" else: print "The unassigned shift is not scheduled, issue" sauce_client.jobs.update_job(admin.session_id, passed=False) admin.quit(); sys.exit() # The part above works # Publish the shift # Open the shift element = admin.find_element_by_xpath("//div[@data-shift-date='%s']/div/div[@class='shift-details']" %date) actions.move_to_element(element) actions.click(element) actions.perform() admin.implicitly_wait(10) Even if I try this way it doesn't work: # Publish the shift # Open the shift admin.find_element_by_xpath("//div[@data-shift-date='%s']/div/div[@class='shift-details']" %date).click() admin.implicitly_wait(10) The HTML of the orange element is the following one: The error: Traceback (most recent call last): File ".\Unassigned_shift_basics.py", line 84, in <module> admin.find_element_by_xpath("//div[@data-shift-date='%s']" %date).click() File "C:\Python27\lib\site-packages\selenium-3.0.2-py2.7.egg\selenium\webdriver\remote\webelement.py", line 77, in cli ck self._execute(Command.CLICK_ELEMENT) File "C:\Python27\lib\site-packages\selenium-3.0.2-py2.7.egg\selenium\webdriver\remote\webelement.py", line 494, in _e xecute return self._parent.execute(command, params) File "C:\Python27\lib\site-packages\selenium-3.0.2-py2.7.egg\selenium\webdriver\remote\webdriver.py", line 236, in exe cute self.error_handler.check_response(response) File "C:\Python27\lib\site-packages\selenium-3.0.2-py2.7.egg\selenium\webdriver\remote\errorhandler.py", line 192, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.ElementNotVisibleException: Message: element not visible (Session info: chrome=55.0.2883.75) (Driver info: chromedriver=2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9),platform=Mac OS X 10.11.6 x86_64) A: After some research with the xpath finder on Chrome, I noticed that my xpath was pointing two version of the element, an invisible version and then the visible one. So my script was trying to click on something invisible which explains the error. The way to tackle that was to reach the visible and click on it. To do that I have used find_elements_by_xpath to gather all these elements and then I have performed a click() on the second element which is the visible one.
{ "pile_set_name": "StackExchange" }
Q: Synchronized method ans synchronized blocks in Java I'm just starting with synchronization in Java and I have small question. Is this method: public synchronized void method() { // ... do staff ... } Is equal to: public void method() { synchronize(this) { // ... do staff ... } } PS Recently I watched 2 good confs about Java (and from this comes my question)video 1, video 2. Do you have some relative videos (I'm interested in programming in Java and Android). A: Yes. Also this: public static synchronized void method() { } is equivalent to: public static void method() { synchronized (EnclosingClass.class) { } } Regarding videos, just search "java synchronization" on youtube.
{ "pile_set_name": "StackExchange" }
Q: SKPhysicsContact body, can't change properties I have a SpriteKit physics contact firing in didBegin(contact:). I grab the physics body for the instance of the Dot object that I want to move offscreen, but when I try to change its position like so, nothing happens: First Approach /* In GameScene.swift */ func didBegin(_ contact: SKPhysicsContact) { let dotBody: SKPhysicsBody if contact.bodyA.categoryBitMask == 0b1 { dotBody = contact.bodyB } else { dotBody = contact.bodyA } if let dot = dotBody.node as? Dot { dot.position.x = 10000 } } However, if I instead call a method in my Dot class, passing in that body, the position gets set correctly: Second Approach /* In GameScene.swift */ func didBegin(_ contact: SKPhysicsContact) { let dotBody: SKPhysicsBody if contact.bodyA.categoryBitMask == 0b1 { dotBody = contact.bodyB } else { dotBody = contact.bodyA } if let dot = dotBody.node as? Dot { dot.move() } } Here is the Dot class: import SpriteKit class Dot : SKSpriteNode { let dotTex = SKTexture(imageNamed: "dot") init() { super.init(texture: dotTex, color: .clear, size: dotTex.size()) self.physicsBody = SKPhysicsBody(circleOfRadius: size.width / 2) self.physicsBody?.categoryBitMask = 0b1 << 1 self.physicsBody?.contactTestBitMask = 0b1 } func move() { let reset = SKAction.run { self.position.x = 10000 } self.run(reset) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } Can anyone explain why the position change in the second approach works but it does not work in my first approach? Here's a link to the project on Github. A: func didBegin(_ contact: SKPhysicsContact) { let hitDot = contact.bodyB.node! as! SKSpriteNode let hitDot1 = contact.bodyA.node! as! SKSpriteNode if hitDot.name? == "dot" || hitDot1.name? == "dot" { reset = true } } override func update(_ currentTime: TimeInterval) { if reset { newDot.position.x = 0 reset = false } } There might be small errors in the code coz i just edited here. But hope this gives u the idea. This should work without errors.
{ "pile_set_name": "StackExchange" }
Q: Xamarin AppCenter Crashes.TrackError not showing details I expect in AppCenter I have this code: private async void ChangeTheColours(Object sender, EventArgs e) { try { if ((string)this.ButtonLabel.Text.Substring(0, 1) != " ") { ConfigureColors((Button)sender, "C"); await Task.Delay(200); ConfigureColors((Button)sender, State); } } catch (Exception ex) { Crashes.TrackError(ex, new Dictionary<string, string> { {"ChangeTheColours", "Exception"}, {"Device Name", DeviceInfo.Name }, {"Device Model", DeviceInfo.Model }, }); } } There was an exception and I was expecting to see information such as the ex string (more than a few words), Device Name and Model. But AppCenter only tells me: Stack traces Button.ChangeTheColours (System.Object sender, System.EventArgs e) Templates/Button/Button.xaml.cs:83 and doesn't give any more information about the exception or the Device Name and Model. Is there something I am doing incorrectly with trying to detect crashes like this? Note that I realise a throw would normally be needed but this is a special case for this error. A: Couple things. First, I think that this page might explain why your exception message is cut a little short. I'm not quite sure if the 125 character limit applies to the exception itself. Second, you don't see much data without looking at the individual error report. To view a specific instance - Click "Diagnostics" in the left nav Select the Error you are trying to inspect Near the top, select "Reports", this shows the individual instances with timestamps Select an instance Near the bottom, you will see an area titled "Error Properties" that should show your dictionary data you included in your error.
{ "pile_set_name": "StackExchange" }
Q: map zoom in/out to include all the pins dynamically I have a map that displays pins and infowindow for each pin. The zoom level is 9 and at that zoom level, some pins are not displayed. I need to control the zoom level dynamically as to show all the pins in the map canvas at a time. A: Have a LatLngBounds object. As you're creating each marker, you want to expand the bounds to include each marker's location. Then at the end you call the fitBounds method to resize the map to fit all the markers. function initialize() { var arrPoints = [ { lat: 51.498725, lng: -0.17312, description: "One", price: 1.11 }, { lat: 51.4754091676, lng: -0.186810493469, description: "Two", price: 2.22 }, { lat: 51.4996066187, lng: -0.113682746887, description: "Three", price: 3.33 }, { lat: 51.51531272, lng: -0.176296234131, description: "Four", price: 4.44 } ]; var centerLatLng = new google.maps.LatLng(51.532315,-0.1544); var map = new google.maps.Map(document.getElementById("map"), { zoom: 15, center: centerLatLng, mapTypeId: google.maps.MapTypeId.ROADMAP }); // create the Bounds object var bounds = new google.maps.LatLngBounds(); var homeMarker = new google.maps.Marker({ position: centerLatLng, map: map, icon: "http://maps.google.com/mapfiles/ms/micons/green-dot.png" }); for (var i = 0; i < arrPoints.length; i++) { position = new google.maps.LatLng(arrPoints[i].lat, arrPoints[i].lng); var marker = new google.maps.Marker({ position: position, map: map }); google.maps.event.addListener(marker, 'click', function() { infowindow.open(map, this); }); // extend the bounds to include this marker's position bounds.extend(position); } // make sure we include the original center point bounds.extend(centerLatLng); // resize the map map.fitBounds(bounds); }
{ "pile_set_name": "StackExchange" }
Q: Perl Catalyst: How to re-use applications I did implement a Catalyst authentication application (captchas, password reminders, access logs, etc...). How am I supposed to re-use it in different Catalyst applications? I.e.: Or - more generally - how am I supposed to let two applications talk each other? A: You can abstract common components in your local catalystX namespace and extend your controllers and models from that namespace .
{ "pile_set_name": "StackExchange" }
Q: iPhone - how to put Settings bundle seen through System Settings App into your own App? I want to create a settings page from within my app that looks exactly like the one that I would create in the System Settings Application using a Settings.bundle and Root.plist. Is there an easy way to access the controls like PSMultiValueSpecifier etc. and add them to an actual View? Thanks! A: Here's another solution: http://www.inappsettingskit.com/ InAppSettingsKit is an open source solution to to easily add in-app settings to your iPhone apps. It uses a hybrid approach by maintaining the Settings.app pane. So the user has the choice where to change the settings... To support traditional Settings.app panes, the app must include a Settings.bundle with at least a Root.plist to specify the connection of settings UI elements with NSUserDefaults keys. InAppSettingsKit basically just uses the same Settings.bundle to do its work. This means there's no additional work when you want to include a new settings parameter. It just has to be added to the Settings.bundle and it will appear both in-app and in Settings.app. All settings types like text fields, sliders, toggle elements, child views etc. are supported... A: The topic on whether settings should go in your app or in the preference app is controversial, mainly because there's no way to open the settings from the app (as noted in the answer coob links to) and because there's no way to add interaction to settings -- and there's many reasons you may want to, including validity/consistency/network checks, etc. So should you want to present a UI that's somewhat like the settings UI in your app, I don't know of any easy or ready made code to do it, but Matt Gallagher's code is a great start to roll your own. A: Craig Hockenberry has a project called GenericTableViews that helps you easily make a table view for settings or forms.
{ "pile_set_name": "StackExchange" }
Q: Java SE asynchrous call from client I have the following problem: I have a list of elements on the client side and am supposed to send them to the server one by one, through the same port, but not block the client while waiting for the server to respond. I have been going through various posts on here as well as JAVA SE documentation, but am not sure I have found the answer. I thought I could start a new Callable for each request, but have been unable to find a non-blocking way to send and receive those messages. From what I read, using Sockets and Output/Input streams would result in blocking, please correct me if I'm wrong. I by no means expect a full solution, but any pointers on where to look at would be greatly appreciated. A: You can implement these asynchronous calls using the non-blocking APIs NIO AND NIO.2. Theres is a great article about it on javaworld.com: http://www.javaworld.com/article/2853780/core-java/socket-programming-for-scalable-systems.html I don't know if you have this option, but you can also implement this on a higher level using HTTP services. Once I answered a question like this for web services. You can take a look here: Asynchronous call from java web service to .net application
{ "pile_set_name": "StackExchange" }
Q: Did not immediately see answer I (idealmachine) was answering "Age: 0" HTTP Header and sent in my answer. OK, so someone (driis) beat me by 5 seconds. However, I checked back a couple minutes later and I saw: answered 6 mins ago / Gumbo♦ / 88.2k 7 68 131 answered 5 mins ago / driis / 15.3k 1 21 58 answered 5 mins ago / idealmachine / 384 6 I hadn't seen Gumbo's answer, only driis's, yet the timestamp on his answer was earlier. Why is that? A: I think it is one of the the Fastest Gun Of The West strategies. It's better not to delete the post, it might draw some early upvotes getting you on top unless it is truly nonsense, but does guarantee an Enlightened badge if you get enough. You've got 5 minutes to edit what you banged-in quickly into some resemblance of a real answer. More if you quickly delete but then you'll miss out on early upvotes. And downvotes, which I suppose is the point. I can't really recommend joining that game, a lot of the high rep users that have been around for a year or more are true masters at it and are quite hard to beat. The disappointment I see in the comments from other users that try to get an answer in is rather strong, especially when their answer is just as correct, merely a few minutes late. This can be quite discouraging. Instead of hunting the 'easy questions', focus on questions that you make you research something so you'll actually learn from the effort. Knowledge gained is worth much more than a rep point.
{ "pile_set_name": "StackExchange" }
Q: How does the HMM model in hmmlearn identifies the hidden states I am new to Hidden Markov Models, and to experiment with it I am studying the scenario of sunny/rainy/foggy weather based on the observation of a person carrying or not an umbrella, with the help of the hmmlearn package in Python. The data used in my tests was obtained from this page (the test and output files of "test 1"). I created the simple code presented bellow to fit an unsupervised HMM from the test data, and then compared the prediction to the expected output. The results seem pretty good (7 out of 10 correct predictions). My question is: how am I supposed to know the mapping of the hidden states handled by the model to the real states in the problem domain? (in other words, how do I relate the responses to the desired states of my problem domain?) This might be a very naïve question, but if the model was supervised I would understand that the mapping is given by me when providing the Y values for the fit method... yet I simply can't figure out how it works in this case. Code: import numpy as np from hmmlearn import hmm # Load the data from a CSV file data = np.genfromtxt('training-data.csv', skip_header=1, delimiter=',', dtype=str) # Hot encode the 'yes' and 'no' categories of the observation # (i.e. seeing or not an umbrella) x = np.array([[1, 0] if i == 'yes' else [0, 1] for i in data[:, 1]]) # Fit the HMM from the data expecting 3 hidden states (the weather on the day: # sunny, rainy or foggy) model = hmm.GaussianHMM(n_components=3, n_iter=100, verbose=True) model.fit(x, [len(x)]) # Test the model test = ['no', 'no', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'yes'] x_test = np.array([[1, 0] if i == 'yes' else [0, 1] for i in test]) y_test = ['foggy', 'foggy', 'foggy', 'rainy', 'sunny', 'foggy', 'rainy', 'rainy', 'foggy', 'rainy'] y_pred = model.predict(x_test) mp = {0: 'sunny', 1: 'rainy', 2: 'foggy'} # THIS IS MY ASSUMPTION print('\n\n\n') print('Expected:') print(y_test) print('Predicted:') print([mp[i] for i in y_pred]) Result: Expected: ['foggy', 'foggy', 'foggy', 'rainy', 'sunny', 'foggy', 'rainy', 'rainy', 'foggy', 'rainy'] Predicted: ['foggy', 'foggy', 'sunny', 'rainy', 'foggy', 'sunny', 'rainy', 'rainy', 'foggy', 'rainy'] A: My question is: how am I supposed to know the mapping of the hidden states handled by the model to the real states in the problem domain? (in other words, how do I relate the responses to the desired states of my problem domain?) Basically you cannot. The fact that you were able to hand craft this mapping (or even that it exists in the first place) is just a coincidence coming from extreme simplicity of the problem. HMM (in such learning scenario) tries to find the most probable sequence of (predefined amount of) hidden states, but like any other unsupervised learning that has no guarantee to match whatever is the task at hand. It simply models the reality the best it can, given the constraints (Markov assumption, number of hidden states, observations provided) - it does not magically detect what is the actual question one is asking (like here - sequence of weathers) but simply tries to solve its own, internal optimization problem - which is the most probable sequence of arbitrarly defined hidden states, such that under the Markov assumption (independence from old history), the observations provided are very likely to appear. In general you will not be able to interpret these states so easily,here the problem is so simple, that simply with the assumptions listed above - this (weather state) is pretty much the most probable thing that will be modeled. In other problems - it can capture anything that makes sense. As said before - this is not a HMM property, but any unsupervised learning technique - when you cluster data you just find some data partitioning, which can have some relation to what you are looking for - or have none. Similarly here - HMM will find some model of the dynamics, but it can be completely different from what you are after. If you know what you are looking for - you are supposed to use supervised learning, this is literally its definition. Unsupervised learning is to find some structure (here - dynamics), not a specific one.
{ "pile_set_name": "StackExchange" }
Q: Apache Beam: Cannot find DataflowRunner I am trying to run a pipeline, which I was able to run successfully with DirectRunner, on Google Cloud Dataflow. When I execute this Maven command: mvn compile exec:java \ -Dexec.mainClass=com.example.Pipeline \ -Dexec.args="--project=project-name \ --stagingLocation=gs://bucket-name/staging/ \ ... custom arguments ... --runner=DataflowRunner" I get the following error: No Runner was specified and the DirectRunner was not found on the classpath. [ERROR] Specify a runner by either: [ERROR] Explicitly specifying a runner by providing the 'runner' property [ERROR] Adding the DirectRunner to the classpath [ERROR] Calling 'PipelineOptions.setRunner(PipelineRunner)' directly I intentionally removed DirectRunner from my pom.xml and added this: <dependency> <groupId>org.apache.beam</groupId> <artifactId>beam-runners-google-cloud-dataflow-java</artifactId> <version>2.0.0</version> <scope>runtime</scope> </dependency> I went ahead and removed the <scope> tag, then called options.setRunner(DataflowRunner.class), but it didn't help. Extending my own PipelineOptions interface from DataflowPipelineOptions did not solve the problem as well. Looks like it ignores runner option in a way I am not able to debug. Update: Here is the full pom.xml, in case that helps: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>dataflow</artifactId> <version>0.1</version> <dependencies> <dependency> <groupId>org.apache.beam</groupId> <artifactId>beam-sdks-java-core</artifactId> <version>2.0.0</version> </dependency> <dependency> <groupId>org.apache.beam</groupId> <artifactId>beam-runners-google-cloud-dataflow-java</artifactId> <version>2.0.0</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.apache.beam</groupId> <artifactId>beam-sdks-java-io-jdbc</artifactId> <version>2.0.0</version> </dependency> <dependency> <groupId>org.apache.beam</groupId> <artifactId>beam-sdks-java-io-google-cloud-platform</artifactId> <version>2.0.0</version> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>42.1.4.jre7</version> </dependency> </dependencies> </project> A: Forgetting to pass my PipelineOptions instance as a parameter to Pipeline.create() method was the cause of my problem. PipelineOptionsFactory.register(MyOptions.class); MyOptions options = PipelineOptionsFactory.fromArgs(args).withValidation().as(MyOptions.class); Pipeline pipeline = Pipeline.create(options); // Don't forget the options argument. ... pipeline.run();
{ "pile_set_name": "StackExchange" }
Q: OptionalDataException with no apparent reason I am using following class to serialize and deserialize my classes. import java.io.*; public final class Serialization { public static void writeObject(Object obj, String path){ try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path))) { oos.writeObject(obj); //System.out.println("Done"); } catch (Exception ex) { ex.printStackTrace(); } } public static Object readObject(String path){ Object obj = null; FileInputStream fin = null; ObjectInputStream ois = null; try { fin = new FileInputStream(path); ois = new ObjectInputStream(fin); obj = ois.readObject(); } catch (Exception ex) { ex.printStackTrace(); } finally { if (fin != null) { try { fin.close(); } catch (IOException e) { e.printStackTrace(); } } if (ois != null) { try { ois.close(); } catch (IOException e) { e.printStackTrace(); } } } return obj; } } I have a class that implements the Serializable interface: TextCategorizator. I am trying to use this class as a classification model. So, to serialize this class' object, I use TextCategorizator tc = new TextCategorizator(trainingFiles, vecFile); Serialization.writeObject(tc, MODEL_PATH); And then when I try to read this serialized object with TextCategorizator model = (TextCategorizator) Serialization.readObject(MODEL_PATH); I got the following exception trace: java.io.OptionalDataException at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1373) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:373) at java.util.HashMap.readObject(HashMap.java:1402) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1058) at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1909) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1808) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1353) at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2018) at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1942) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1808) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1353) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:373) at utils.Serialization.readObject(Serialization.java:27) at Main.main(Main.java:33) The part that raises the exception is: obj = ois.readObject(); When I look at reference page of this exception, it says there are two options which indicated with the eof flag and length variable in this exception. I printed them to see. eof is true, length is 0. This means, according to reference page, An attempt was made to read past the end of data consumable by a class-defined readObject or readExternal method. In this case, the OptionalDataException's eof field is set to true, and the length field is set to 0. I used these methods before and I did not face with this exception. What's wrong and what exactly the "read past" means? EDIT : TextCategorizator class is here: import utils.FileUtils; import java.io.File; import java.io.Serializable; import java.util.*; import java.util.stream.Collectors; public class TextCategorizator implements Serializable { private Map<String, String> wordVectors; private Map<File, List<List<Double>>> docVectors; private Map<File, String> trainingFiles; private Set<String> classes; public TextCategorizator(Map<File, String> trainingFiles, String trainedVectors) { wordVectors = new HashMap<>(); docVectors = new HashMap<>(); classes = new HashSet<>(); this.trainingFiles = trainingFiles; List<String> lines = FileUtils.readFileAsList(new File(trainedVectors)); System.out.println("> Reading word vector file."); lines.parallelStream().forEach(line -> { String name = line.substring(0, line.indexOf(' ')); wordVectors.put(name, line); }); train(trainingFiles); } private void train(Map<File, String> trainingFiles) { System.out.println("> Starting training parallel."); trainingFiles.entrySet().parallelStream().forEach(entry -> { docVectors.put(entry.getKey(), getVectorsOfDoc(entry.getKey())); classes.add(entry.getValue()); }); } private List<List<Double>> getVectorsOfDoc(File doc) { List<List<Double>> lists = new ArrayList<>(); List<Double> resultVecAvg = new ArrayList<>(); List<Double> resultVecMax = new ArrayList<>(); List<Double> resultVecMin = new ArrayList<>(); int vecSize = 100; for (int i = 0; i < vecSize; i++) { resultVecAvg.add(0.0); resultVecMax.add(0.0); resultVecMin.add(0.0); } String[] words = FileUtils.readWords(doc); for (String word : words) { String line = wordVectors.get(word); if (line != null) { List<Double> vec = new ArrayList<>(); String[] tokens = line.split(" "); for (int i = 1; i < tokens.length; i++) { vec.add(Double.parseDouble(tokens[i])); } for (int i = 0; i < vec.size(); i++) { resultVecAvg.set(i, resultVecAvg.get(i) + (vec.get(i) / vecSize)); resultVecMax.set(i, Math.max(resultVecMax.get(i), vec.get(i))); resultVecMin.set(i, Math.min(resultVecMin.get(i), vec.get(i))); } } } lists.add(resultVecAvg); lists.add(resultVecMax); lists.add(resultVecMin); return lists; } private void getCosineSimilarities(List<Double> givenVec, int option, Map<File, Double> distances) { for (Map.Entry<File, List<List<Double>>> entry : docVectors.entrySet()) { List<Double> vec = null; if (option == 1) // AVG vec = entry.getValue().get(0); else if (option == 2) // MAX vec = entry.getValue().get(1); else if (option == 3) // MIN vec = entry.getValue().get(2); distances.put(entry.getKey(), cosSimilarity(givenVec, vec)); } } private double cosSimilarity(List<Double> vec1, List<Double> vec2) { double norm1 = 0.0; double norm2 = 0.0; double dotProduct = 0.0; for (int i = 0; i < vec1.size(); i++) { norm1 += Math.pow(vec1.get(i), 2); norm2 += Math.pow(vec2.get(i), 2); dotProduct += vec1.get(i) * vec2.get(i); } return dotProduct / (Math.sqrt(norm1) * Math.sqrt(norm2)); } // from http://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values-java private <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map, boolean reverse) { return map.entrySet() .stream() .sorted((reverse ? Map.Entry.comparingByValue(Collections.reverseOrder()) : Map.Entry.comparingByValue())) .collect(Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new )); } private int countClass(List<File> files, String c) { int counter = 0; for (File file : files) { if (trainingFiles.get(file).equals(c)) ++counter; } return counter; } public Map.Entry<String, Integer> classifyKnn(File file, int k, int option) { List<List<Double>> vecs = getVectorsOfDoc(file); List<Double> vec = getProperVector(vecs, option); Map<File, Double> distances = new HashMap<>(); getCosineSimilarities(vec, option, distances); distances = sortByValue(distances, true); List<File> sortedFiles = new ArrayList<>(distances.keySet()); sortedFiles = sortedFiles.subList(0, k); Map<String, Integer> counts = new HashMap<>(); for (String category : classes) { counts.put(category, countClass(sortedFiles, category)); } ArrayList<Map.Entry<String, Integer>> resultList = new ArrayList(sortByValue(counts, true).entrySet()); return resultList.get(0); } private List<Double> getProperVector(List<List<Double>> lists, int option) { List<Double> vec = null; if (option == 1) // AVG vec = lists.get(0); else if (option == 2) // MAX vec = lists.get(1); else if (option == 3) // MIN vec = lists.get(2); return vec; } public Map.Entry<String, Double> classifyRocchio(File file, int option) { List<List<Double>> vecs = getVectorsOfDoc(file); List<Double> vec = getProperVector(vecs, option); Map<File, Double> distances = new HashMap<>(); getCosineSimilarities(vec, option, distances); distances = sortByValue(distances, true); List<Map.Entry<File, Double>> sortedFiles = new ArrayList<>(distances.entrySet()); return new AbstractMap.SimpleEntry<> (trainingFiles.get(sortedFiles.get(0).getKey()), sortedFiles.get(0).getValue()); } } A: Finally I got this working. The problem was the size of the objects that I was trying to serialize and deserialize (i.e wordVectors is 480 MB). To fix this, I used synchronized map. So wordVectors = new HashMap<>(); is changed to wordVectors = Collections.synchronizedMap(new HashMap<>()); I got the idea from here.
{ "pile_set_name": "StackExchange" }
Q: Form of Reaction-Advection-Diffusion Equation My textbook (Essential Partial Differential Equations by Griffiths, Dold, and Silvester) says the following: $$u'' = a(x)u' + b(x)u - f(x)$$ This is called a reaction-advection-diffusion equation since the second derivative term represents "diffusion", the term $a(x)u''$ represents "advection" (if $a > 0$ then there is a "wind" blowing from left to right with strength $a$) and the term $b(x)u$ represents "reaction". The term $f$ is often called the "source" term. I'm guessing that should be $a(x)u'$ instead of $a(x)u''$? I tried researching this, but every time I found an equation that was described in a similar way to the above one, it was in a wildly different form. Thanks for the clarification. A: I believe that the book should speak of the stationnary version of such an equation. Indeed, if we consider the following reaction-advection-diffusion equation $$ \partial_t u + a(x) \partial_x u = \partial_{xx} u - b(x) u + f(x) $$ and seek for its steady-state solutions ($\partial_t u=0$), we obtain the above differential equation. Now, let us consider the convection-diffusion equation from the Wikipedia article: $$ \partial_t c + \nabla\cdot (\vec v c) = \nabla\cdot(D\nabla c) + R \, . $$ The use of the words convection and advection is the same in this context, so that the previous equation could be called an advection-diffusion equation. Under the assumption of incompressible flow ($\nabla\cdot \vec v = 0$), the convection term becomes \begin{aligned} \nabla\cdot (\vec v c) &= \vec v\cdot\nabla c + c\nabla\cdot \vec v\\ &= \vec v\cdot\nabla c \, . \end{aligned} For a constant diffusion coefficient $D=1$, the diffusion term becomes $\nabla\cdot(D\nabla c) = \nabla^2 c$. In the case of one-dimensional flow with velocity $\vec v = v \vec x$, we therefore have $$ \partial_t c + v \partial_x c = \partial_{xx} c + R \, , $$ which corresponds to the previous reaction-advection-diffusion equation, where the reaction coefficient is $b(x) = 0$.
{ "pile_set_name": "StackExchange" }
Q: How to make sql foreach loop by Laravel Query builder? I have an array. Can I send the values ​​in an array with one query and get a separate response for all arrays ...? $regions: array; $result is laravel query result ['index'] is index from SQL $data['persons'] = $reslut['index']['persons']; $data['companies'] = $reslut['index']['companies']; If I am sending an array to sql and can it return a separate value for each value? That is, the foreach loop should use sql and return the results to individual variables. Can I write in any of the indexes? A: You can query array data with a whereIn statement: $results = Model::whereIn('your_field', $array)->get() This will respond with a collection that contains multiple results. You can loop over them with for($results as $result){} or count them with $results->count() .. But i'm not complete sure I did understand your question correct ;)
{ "pile_set_name": "StackExchange" }
Q: Difference between @Max and @DecimalMax (and @Min and @DecimalMin) What's the difference between @Max and @DecimalMax, and @Min and @DecimalMin in Hibernate Validator? Looking at the Javadocs, they seem to be enforcing the same constraint. A: If you take a look at the reference documentation, you'll see that the @Min & @Max annotations both have an impact on the Hibernate metadata while @DecimalMin & @DecimalMax don't. Namely, they add check constraints (which effectively improves your relational mapping). Also @Max & @Min accept a long value, while @DecimalMax & @DecimalMin accept the String representation of a BigDecimal (which makes these the only possible choice if you're dealing with big numbers that exceed Long.MAX_VALUE or are under Long.MIN_VALUE.
{ "pile_set_name": "StackExchange" }
Q: return true after jQuery validation wont submit my form I have a form that I am validating with jQuery, once validation is passed I want to submit the form: $(document).ready(function(){ $('[name="form"]').submit(function(e){ e.preventDefault(); var one = $('[name="one"]'); var two = $('[name="two"]'); var three = $('[name="three"]'); var errors = []; if(!one.val()){ errors.push(one); } if(!two.val()){ errors.push(two); } if(!three.val()){ errors.push(three); } if(errors.length > 0){ $.each(errors, function(i, v){ $(v).css('border', '1px solid red'); }); } else { console.log('true'); $('#bmi-form').submit(); } }); }); My idea was that the return true at the end would submit the form but it does nothing.. In the console I see the console.log('true'); So how can I submit the form on validation success... I dont want to use any plugins as it is a very small app and there is no need to bloat it. Regards A: As you are using e.preventDefault(); which stops the form to get submitted. Now you can .submit() the form instead of return true;: } else { console.log('true'); this.submit(); // return true; } or remove the e.preventDefault() and change to this code to submit only when there are no errors: if(errors.length > 0){ $.each(errors, function(i, v){ $(v).css('border', '1px solid red'); }); e.preventDefault(); // put e.preventDefault(); stop to submit incase of errors } else { console.log('true'); // just remove the return true; from here because if everything is } // fine form will submit. Or you can just remove the else block.
{ "pile_set_name": "StackExchange" }
Q: How to get into BIOS when USB keyboard is not powered and have no PS/2 ports? Just got a new Windows 7 PC (64-bit) with an Intel DH67CL motherboard. It's been working fine but I decided I wanted to try to get into the BIOS. Unfortunately I can't do it because my USB keyboard isn't powered up on boot. I've tried 3 different keyboards and almost all of the USB ports with no luck. Any idea how to get into the BIOS? A: Well as soon as I got my question typed in I figured it out, at least for this Intel motherboard. I found another computer with the same motherboard and browsed the BIOS settings. Under Boot/Fast Boot/USB Optimization I found this descriptive text (nowhere in the manual by the way): "If Enabled, USB devices (keyboards and drives) will not be available until after OS boot, but BIOS will boot faster. If Disabled, USB devices will be available before OS boot, but BIOS will boot slower. This question does not affect USB capabilities after OS boot. This question cannot be enabled while a User Password or Hard Drive Password is installed. In order to disable Fast Boot without entering BIOS Setup: Power down the system, then hold down the power button until the system beeps." I tried it, heard 3 beeps, then it booted to a screen saying that the Fast-boot trigger had been detected, would I like to enable fast-boot on the next boot. No!! Noticed that my keyboard light was on and hit 'N'. It rebooted again and I was able to hit F2 to get into the BIOS. A: Don't forget the oldest trick in the book: Take out the lithium battery for a few minutes, and then turn on the system.
{ "pile_set_name": "StackExchange" }
Q: Оптимальный размер сайта Как вы считаете, какой размер страницы в КБ веб-сайта будет оптимален для мобильных платформ? A: Хм не более 150КБ я в общем о сайтах напишу, не о wap А если у тебя будет 2-5 баннеров на сайте, как тогда? (по 15-100КБ) Картинки, фотки в кол-ве от 10 до 30 штук, это если фото сайт допустим (по N Кб) Подгружаемые картинки Скрипты CSS Считаю тут упор не на размер сайта нужно делать, а на оптимизацию отдачи контента пользователю. Мне вот если чесно, без разницы как откроется мой блог в деревне "НОВОПУПИНСК", 1Кб/сек пусть сидят и ждут. Я уверен что не буду оптимизировать под них. В большинстве случаем инет сейчас с широким каналом предоставляется, так что либо пользователи со 128Кб сидят и ждут, другие платят за инет на 100р больше и не ждут. Собственно для web платформ тут тоже идет оптимизация своя, и нужно будет думать. Я вот честно не люблю wap.site.domen мне голая информация текстовая не нравится, всегда смотрю сайты целиком. Интересно сделать минимально сделай, те кто смотрят только текстовые сайты ну не знаю, 21 век, читать тексты когда, даже, мобильный инет всем по карману. для мобильных платформ Тут конкретика нужна. я на планшете смотрю все целиком. Если это wap версия сайта то и написать нужно что wap.
{ "pile_set_name": "StackExchange" }
Q: Conversion error while using ',' in STUFF - SQL I have the below query: select STUFF((SELECT ',' + rr1._cv_id FROM #reportrows rr1 WHERE rr1._c_id=rr._c_id FOR XML PATH('')),1, 1,null)FROM #reportrows rr In this query, _cv_id is integer type. Upon running this query I get to see below error: Conversion failed when converting the varchar value ',' to data type int. Any help?! A: The id is not a string, so convert it: SELECT STUFF( (SELECT ',' + CONVERT(VARCHAR(MAX), rr1._cv_id) . . . A: looks like the column cv_id is of numeric data type. therefore you need to convert to string before concatenate with comma select STUFF((SELECT ',' + convert(varchar(10), rr1._cv_id) FROM #reportrows rr1 WHERE rr1._c_id=rr._c_id FOR XML PATH('')),1, 1,null) FROM #reportrows rr A: You need to convert rr1._cv_id to string select STUFF((SELECT ',' + CAST(rr1._cv_id AS VARCHAR(20)) FROM #reportrows rr1 WHERE rr1._c_id=rr._c_id FOR XML PATH('')),1, 1,null)FROM #reportrows rr
{ "pile_set_name": "StackExchange" }
Q: Failure to install ADT plugin to Eclipse - 'violates contract' error message Yesterday I had a problem about required items not being found when installing the ADT plugin in Eclipse. I got around that by opening up the download sites list and ticking the two bottom ones on the list, which for some reason were not selected. One of these addresses contained the word "mylyn". Now, when "fetchingjavax.xml_1.3.4. ........ /mylyn/drops......" (dots indicate other address parts), I had an error message: An internal error occurred during: "Install download0". Comparison method violates its general contract! which can be dismissed, but the installation appears to have stopped. What to do next? A: I had the same problem with Indigo running on a Java 7 VM and found out that eclipse has a problem to select the download mirror when using a Java 7 VM. This Bug was fixed in eclipse milestone 3.7.1 (https://bugs.eclipse.org/bugs/show_bug.cgi?id=352089) Here is my solution: Add the new vmargs configuration property "-Djava.util.Arrays.useLegacyMergeSort=true" to eclipse.ini Start and update eclipse to at least Indigo Service Release 1 (3.7.1). Remove the configuration property listed on step one A: I guess, you have JRE 7 installed and that's the problem. I tried the same thing, but always received this error message. On the eclipse-bugzilla, I found the advice, to downgrade JRE to version 6. So first uninstall JRE 7, than install JRE 6: Java 6u27 Download
{ "pile_set_name": "StackExchange" }
Q: DatePicker/Timepicker is Visible all the time I have a fields with a datepicker & timepicker. Whenever I move to that page last used datepicker or timepicker is visible all the time. For example if I had used timepicker on that page, then whenever I am going to that page timepicker is open. My requirement is that when I will click on TextBox then the datepicker or timepicker should visible. JavaScript Function: $(document).ready(function () { $("[id$=TextBox1]").pickadate({format: 'dd/mm/yyyy'}); $("[id$=TextBox3]").pickatime({ interval: 10 }); $("[id$=TextBox4]").pickatime({ interval: 10 }); }); Where should I change my code? Please help me to do so. Thanks Update Code: For TextBox1 <tr> <td class="style10"> <strong> Today </strong> </td> <td class="style13"> <strong> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> </strong> </td> </tr> For TextBox3 <tr> <td class="style10"> <strong> In Time:</strong></td> <td class="style13"> <strong> <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox> </strong> </td> </tr> For TextBox4 <tr> <td class="style10"> <strong> OutTime:</strong></td> <td class="style13"> <strong> <asp:TextBox ID="TextBox4" runat="server" onkeyup="sum"></asp:TextBox> </strong> </td> </tr> <tr> A: You can instantiate the picker in a var var picker = $input.pickadate('picker') And open or close it when you want: picker.open() picker.close() In this way you can do something like this for each picker: $(document).ready(function () { var picker = $("[id$=TextBox1]").pickadate({format: 'dd/mm/yyyy'}); }); And add two event handlers for each input: $('#TextBox1').focus(function() { picker.open() }); $('#TextBox1').focusout(function() { picker.close() }); If you dont want declarate a handler manually for each input (can be little toilsome), you can create a function for parametrize this: function parametrizeHandlers(inputId, picker) { $('#'+inputId).focus(function() { picker.open() }); $('#'+inputId).focusout(function() { picker.close() }); } IMPORTANT: Im supose that you are using this API, full specification here: API- pickadate.js If you're not using this API sure you can do something like this.
{ "pile_set_name": "StackExchange" }
Q: How to reuse input value public double getInput() { System.out.print("Percentage of attacks that will be aimed low: "); Scanner data = new Scanner(System.in); double low = data.nextDouble(); return(low); } public static void main(String[] args) { for ( int i = 0 ; i < round ; i++) { xxxx.getInput(); } I didn't include all of it, but I hope you get what I mean. A: You don't need to put final in front of it, it will get the first int specified, and as it's not in a for loop, the value will never change unless you change it yourself. However, you haven't declared the type of low. So do it like this: int low = data.nextInt(); From your new code, you could try this: public static void main(String[] args) { Scanner data = new Scanner(System.in); double low = data.nextDouble(); // you have low now for ( int i = 0 ; i < round ; i++) { System.out.print("Percentage of attacks that will be aimed low: "); // do what you want with low } A: If you want use final, you must write the type of variable like this final int or final double. In your program you should have: final int low = data.nextInt(); from your new code i think you want to reuse the first entered value without asking the user input again this is the method public static double getInput(int i) { if(i==0) { System.out.print("Percentage of attacks that will be aimed low: ");} Scanner data = new Scanner(System.in); double low = data.nextDouble(); return(low); } and this is the main public static void main(String[] args) { for ( int i = 0 ; i < round ; i++) { getInput(i); } }
{ "pile_set_name": "StackExchange" }
Q: a Pythonic implementation of string contraction which lists characters as they appear and their counts? I implemented string contraction which lists the characters of a string with their respective counts. So, for example, the string "aadddza" becomes "a2d3z1a1". Can you offer suggestions on making what I have Pythonic? def string_contraction(input_string): if type(input_string) != str: print("Not a string") return input_string = str.lower(input_string) prev = input_string[0] s = "" i = 0 for lett in input_string: if lett == prev: i += 1 else: s += prev+str(i) prev = lett i = 1 s += lett+str(i) return(s) A: The itertools.groupby function can do the "hard part" for you. Here's an example ("rle" is short for "run length encoding"): def rle(s): from itertools import groupby return "".join(letter + str(len(list(group))) for letter, group in groupby(s)) Then: >>> rle("aadddza") 'a2d3z1a1' It may take a while staring at the docs to figure out how this works - groupby() is quite logical, but not simple. In particular, the second element of each two-tuple it generates is not a list of matching elements from the original iterable, but is itself an iterable that generates a sequence of matching elements from the original iterable. Your application only cares about the number of matching elements. So the code uses list(group) to turn the iterable into a list, and then applies len() to that to get the number.
{ "pile_set_name": "StackExchange" }
Q: Terraform not finding third party plugin in directory specified for plugins Attempting to get Terraform to work on windows 10 64 bit, using the Virtualbox provider plugin listed here (https://github.com/terra-farm/terraform-provider-virtualbox). I've verified that the plugin exists in %APPData%/terraform.d/plugins/windows_amd64 but it says it's not there. Have tried the following with no luck Tried copying terraform.d to local instead of roaming for %APPData%. Tried in the root directory where the terraform executible exists Tried just the virtualbox folder instead of the entire plugin in both %APPData% locations Tried in the folder where the terraform files exists None have worked. It acts as if the folder it says to place the plugin, and where it's looking are mismatched, but I doubt something like that would have made it to release, so I'm at a loss as to why it's not seeing the plugin. Terraform is the latest version. Using the following in my example.tf (the only tf file in the directory that i execute terraform form) resource "virtualbox_vm" "node" { count = 2 name = format("node-%02d", count.index + 1) image = "https://app.vagrantup.com/ubuntu/boxes/bionic64/versions/20180903.0.0/providers/virtualbox.box" cpus = 2 memory = "512 mib" user_data = file("user_data") network_adapter { type = "hostonly" host_interface = "vboxnet1" } } output "IPAddr" { value = element(virtualbox_vm.node.*.network_adapter.0.ipv4_address, 1) } output "IPAddr_2" { value = element(virtualbox_vm.node.*.network_adapter.0.ipv4_address, 2) } A: Terraform looks for plugins in a number of locations, but the primary place for manually-installed plugins is in the "User Plugins Directory", which is either ~/.terraform.d/plugins on Unix systems or %APPDATA%\terraform.d\plugins on Windows. The .terraform/plugins directory is not the place to put plugins you're installing manually. That directory is managed by Terraform itself and is the location for automatically-installed plugins. If you place plugins in that directory manually, terraform init may delete them as part of plugin installation. Terraform also requires the provider executable to follow a particular naming scheme: terraform-provider-providername_vX.Y.Z, where the _vX.Y.Z part is technically optional but strongly recommended in order for version constraints to operate correctly. On Windows in particular, the file must also have the suffix .exe, because Terraform plugins are separate programs that Terraform will launch. To debug Terraform's plugin discovery process, you can set the environment variable TF_LOG=debug before you run terraform init. In that output there will be lines like this: 2019/09/03 10:36:26 [DEBUG] checking for provider in "/home/username/.terraform.d/plugins" If it finds any plugins in the various search paths, it will additionally produce lines like this: 2019/09/03 10:36:26 [DEBUG] found valid plugin: "example", "1.2.0", "/home/username/.terraform.d/plugins/terraform-provider-test_v1.2.0" If there are any provider version constraints in the configuration than they must include whatever provider version you've installed. For example, with the above discovered provider that is example v1.2.0, a version constraint like ~> 2.0.0 would exclude it from consideration, even though Terraform discovered it. To see how provider versions are constrained by your configuration, run terraform providers. If there are no constraints then it will just list the provider names, but if any constraints are present then they will be included in the output.
{ "pile_set_name": "StackExchange" }
Q: jQuery selector doesn't register the added class Can anyone please explain me why this code does what it does. What I would like to achieve is that when the first button gets clicked javascript adds a disabled class to the second button and when the second button gets pressed with disabled class the javascript won't run. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>jQuery question</title> <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script> <style> a.success { background: green } </style> </head> <body> <div id="holder"> <a href="#" class="button">Button 1</a> <a href="#" class="button">Button 2</a> </div> </body> <script> $(function(){ $('#holder a.button:not(.disabled)').on('click', function() { // Toggle success class if($(this).hasClass('success')) { $(this).removeClass('success'); } else { $(this).addClass('success'); } // Add disabled class to the not so lucky button $('#holder a.button:not(.success)').each(function() { $(this).addClass('disabled'); }); }); }); </script> </html> Looking at the console this is not the case. Even though the second button gets the disabled class. Pressing the disabled button still runs javascript despite the :not(.disabled) selector. It behaves as expected when I change it like this $('#holder a.button').on('click', function() { if($(this).hasClass('disabled')) { return false; } But could someone please explain why it's acting like that? A: The selector is not going to dynamically re-evaluate itself every time an event is fired. The best way to solve this problem would be to use event delegation: $('#holder').on('click', '.button:not(.disabled)', function() { // snip... });
{ "pile_set_name": "StackExchange" }
Q: Update Table with DISTINCT SELECTed values from same TABLE I have this table What I want to do is that Select the attr_id WHERE a DISTINCT name_en-GB appears and then SET that selected attr_id for that name_en-GB I can do this by writing individual queries but I want to know is there any way I can do this in one query? I have tried this UPDATE sc_product_phrase SET attr_id = ( SELECT DISTINCT sc_product_phrase.caption, sc_product_phrase.design_phrase_id FROM `sc_product_phrase` as x GROUP BY sc_product_phrase.caption ) but this show error [Err] 1093 - You can't specify target table 'sc_product_phrase' for update in FROM clause EDITED I want my TABLE to look like the following http://sqlfiddle.com/#!2/d65eb/1 NOTE:- I dont want to use that query in that fiddle A: Your SQL Fiddle makes the question much clearer. You want the minimum attribute id on all rows with the same value in the last column. You can do this with an update/join like this: UPDATE table1 JOIN (SELECT `name_en-GB`, min(Attr_Id) as minai from table1 GROUP BY `name_en-GB` ) tt on table1.`name_en-GB` = tt.`name_en-GB` SET attr_id = tt.minai WHERE table1.`name_en-GB` IN ('Bride Name', 'Child Grade') AND table1.attr_id <> tt.minai; I'm not sure if you need the in part. You can update all of them by removing that clause.
{ "pile_set_name": "StackExchange" }
Q: iText LocationTextExtractionStrategy/HorizontalTextExtractionStrategy splits text into single characters I used a extended version of LocationTextExtractionStrategy to extract connected texts of a pdf and their positions/sizes. I did this by using the locationalResult. This worked well until I tested a pdf containing texts with a different font (ttf). Suddenly these texts are splitted into single characters or small fragments. For example "Detail" is not any more one object within the locationalResult list but splitted into six items (D, e, t, a, i, l) I tried using the HorizontalTextExtractionStrategy by making the getLocationalResult method public: public List<TextChunk> GetLocationalResult() { return (List<TextChunk>)locationalResultField.GetValue(this); } and using the PdfReaderContentParser to extract the texts: reader = new PdfReader("some_pdf"); PdfReaderContentParser parser = new PdfReaderContentParser(reader); var strategy = parser.ProcessContent(i, HorizontalTextExtractionStrategy()); foreach (HorizontalTextExtractionStrategy.HorizontalTextChunk chunk in strategy.GetLocationalResult()) { // Do something with the chunk } but this also returns the same result. Is there any other way to extract connected texts from a pdf? A: After debugging deep into the iTextSharp library I figured out that my texts are drawn with the TJ operator as mkl also mentioned. [<0027> -0.2<00280037> 0.2<0024002c> 0.2<002f> -0.2<0003>] TJ iText processes these texts not as a single PdfString but as an array of PdfObjects which ends up in calling renderListener.RenderText(renderInfo) for each PdfString item in it (see ShowTextArray class and DisplayPdfString method). In the RenderText method however the information about the relation of the pdf strings within the array got lost and every item is added to locationalResult as an independent object. As my goal is to extract the "argument of a single text drawing instruction" I extended the PdfContentStreamProcessor class about a new method ProcessTexts which returns a list of these atomic strings. My workaround is not very pretty as I had to copy paste some private fields and methods from the original source but it works for me. class PdfContentStreamProcessorEx : PdfContentStreamProcessor { private IDictionary<int, CMapAwareDocumentFont> cachedFonts = new Dictionary<int, CMapAwareDocumentFont>(); private ResourceDictionary resources = new ResourceDictionary(); private CMapAwareDocumentFont font = null; public PdfContentStreamProcessorEx(IRenderListener renderListener) : base(renderListener) { } public List<string> ProcessTexts(byte[] contentBytes, PdfDictionary resources) { this.resources.Push(resources); var texts = new List<string>(); PRTokeniser tokeniser = new PRTokeniser(new RandomAccessFileOrArray(new RandomAccessSourceFactory().CreateSource(contentBytes))); PdfContentParser ps = new PdfContentParser(tokeniser); List<PdfObject> operands = new List<PdfObject>(); while (ps.Parse(operands).Count > 0) { PdfLiteral oper = (PdfLiteral)operands[operands.Count - 1]; if ("Tj".Equals(oper.ToString())) { texts.Add(getText((PdfString)operands[0])); } else if ("TJ".Equals(oper.ToString())) { string text = string.Empty; foreach (PdfObject entryObj in (PdfArray)operands[0]) { if (entryObj is PdfString) { text += getText((PdfString)entryObj); } } texts.Add(text); } else if ("Tf".Equals(oper.ToString())) { PdfName fontResourceName = (PdfName)operands[0]; float size = ((PdfNumber)operands[1]).FloatValue; PdfDictionary fontsDictionary = resources.GetAsDict(PdfName.FONT); CMapAwareDocumentFont _font; PdfObject fontObject = fontsDictionary.Get(fontResourceName); if (fontObject is PdfDictionary) _font = GetFont((PdfDictionary)fontObject); else _font = GetFont((PRIndirectReference)fontObject); font = _font; } } this.resources.Pop(); return texts; } string getText(PdfString @in) { byte[] bytes = @in.GetBytes(); return font.Decode(bytes, 0, bytes.Length); } private CMapAwareDocumentFont GetFont(PRIndirectReference ind) { CMapAwareDocumentFont font; cachedFonts.TryGetValue(ind.Number, out font); if (font == null) { font = new CMapAwareDocumentFont(ind); cachedFonts[ind.Number] = font; } return font; } private CMapAwareDocumentFont GetFont(PdfDictionary fontResource) { return new CMapAwareDocumentFont(fontResource); } private class ResourceDictionary : PdfDictionary { private IList<PdfDictionary> resourcesStack = new List<PdfDictionary>(); virtual public void Push(PdfDictionary resources) { resourcesStack.Add(resources); } virtual public void Pop() { resourcesStack.RemoveAt(resourcesStack.Count - 1); } public override PdfObject GetDirectObject(PdfName key) { for (int i = resourcesStack.Count - 1; i >= 0; i--) { PdfDictionary subResource = resourcesStack[i]; if (subResource != null) { PdfObject obj = subResource.GetDirectObject(key); if (obj != null) return obj; } } return base.GetDirectObject(key); // shouldn't be necessary, but just in case we've done something crazy } } }
{ "pile_set_name": "StackExchange" }
Q: measuring print job time programmatically I need to measure print job time, which means time between 'send print command' and 'print job disappear from the print queue' so I am trying to do these things by script search all pdf files print a file get the print time (as above) go to next file and do all above for all files this is my work so far(i omit some parts) For Each file In objFolder.Items ' check for the extension if objFSO.GetExtensionName(file.name) = "pdf" then ' invoke to print file.InvokeVerbEx( "Print" ) ' select print jobs Set Printers = objWMIService.ExecQuery _ ("Select * from Win32_PrintJob") For Each objPrinter in Printers DateTime.Value = objPrinter.TimeSubmitted TimeinQueue = DateDiff("n", actualTime, Now) Wscript.Echo TimeinQueue Next end if next mainly i need to ask how can i get the time when print job disappear from the print queue. And I need to keep next job till one print job ends. any ideas ? A: I was looking for exact thing and I simply summurized ansgar's script to get what I want. its take every pdf files and print 5 times each(so i can get a avarage which better) while getting the time.finally print them in to a csv file. and untill one going to desapear from the print queue others wait waits. Not 100% acuurate but enough for the perfomance comparision may be it may usefull (please correct my mistakes if any) Dim objFSO, outFile const forAppending = 8 const useDefault = -2 'Output File name fileName = ".\output.csv" Set objFSO = CreateObject("Scripting.FileSystemObject") set outFile = objFSO.OpenTextFile(fileName, forAppending, true, useDefault) 'write heading to output file outFile.WriteLine("Filename,1,2,3,4,5") 'get current Folder strFolder = Replace(wscript.scriptfullname,wscript.scriptname,".\") strFolder = objFSO.getFolder(strFolder) 'Open the Shell Folders object Set objShell = CreateObject( "Shell.Application" ) 'Create an object for the specified file's parent folder Set objFolder = objShell.Namespace( strFolder ) strComputer = "." Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") For Each file In objFolder.Items If objFSO.GetExtensionName(file.name) = "pdf" Then 'write in to out file outFile.write(file.name) outFile.writeLine "" 'outer loop for 5 times per each file index = 0 do while index < 5 'if already doing a printing do not start a new one if CheckPrintQueue() = 0 then file.InvokeVerbEx "Print" startTime = timer waitTostart 'if first time on outer loop it should be empty queue else if index = 0 then wscript.echo "queue doesnt empty" finish end if end if 'wait until all jobs finished printing waitToEnd 'count time ellapsTime = timer - startTime 'write in to out file outFile.write(",") outFile.Write(ellapsTime) index = index + 1 loop End If Next outFile.Close '----------------function CheckPrintQueue----------------------- Function CheckPrintQueue() Set printJobs = objWMIService.ExecQuery("SELECT * FROM Win32_PrintJob") Set currentDocs = CreateObject("Scripting.Dictionary") CheckPrintQueue = printJobs.Count End Function '----------------end of function----------------- sub waitTostart Do WScript.Sleep 100 'check print queue printJobCount = CheckPrintQueue() Loop until printJobCount > 0 end sub sub waitToEnd Do WScript.Sleep 100 'check print queue printJobCount = CheckPrintQueue() Loop until printJobCount = 0 end sub sub finish outFile.Close objFSO = nothing objFolder = nothing objShell = nothing objWMIService = nothing wscript.quit 1 end sub
{ "pile_set_name": "StackExchange" }
Q: How to get ssl on a kubernetes application? I have a simple meteor app deployed on kubernetes. I associated an external IP address with the server, so that it's accessible from within the cluster. Now, I am up to exposing it to the internet and securing it (using HTTPS protocol). Can anyone give simple instructions for this section? A: In my opinion kube-lego is the best solution for GKE. See why: Uses Let's Encrypt as a CA Fully automated enrollment and renewals Minimal configuration in a single ConfigMap object Works with nginx-ingress-controller (see example) Works with GKE's HTTP Load Balancer (see example) Multiple domains fully supported, including virtual hosting multiple https sites on one IP (with nginx-ingress-controller's SNI support) Example configuration (that's it!): kind: ConfigMap apiVersion: v1 metadata: name: kube-lego namespace: kube-lego data: lego.email: "your@email" lego.url: "https://acme-v01.api.letsencrypt.org/directory" Example Ingress (you can create more of these): apiVersion: extensions/v1beta1 kind: Ingress metadata: name: site1 annotations: # remove next line if not using nginx-ingress-controller kubernetes.io/ingress.class: "nginx" # next line enable kube-lego for this Ingress kubernetes.io/tls-acme: "true" spec: tls: - hosts: - site1.com - www.site1.com - site2.com - www.site2.com secretName: site12-tls rules: ... A: There are several ways to setup a ssl endpoint, but your solution needs to solve 2 issues: First, you need to get a valid cert and key. Second, you would need to setup a ssl endpoint in your infrastructure. Have a look at k8s ingress controller. You can provide an ingress controller with a certificate/key secret from the k8s secret store to setup a ssl endpoint. Of course, this requires you to already have a valid certificate and key. You could have a look at k8s specific solutions for issuing and using certificates like the Kubernetes Letsencrypt Controller, but I have never used them and cannot say how well they work. Here are some general ideas to issue and use ssl certificates: 1. Getting a valid ssl certificate and key AWS If you are running on AWS, the easiest way I can think of is by setting up an ELB, which can issue the ssl cert automatically for you. LetsEncrypt You could also have a look at LetsEncrypt to issue free certificates for your domain. Nice thing about it is that you can automate your cert issuing process. CA Of course, you could always go the old-fashion way and issue a certificate from a provider that you trust. 2. Setting up the ssl endpoint AWS Again, if you have an ELB then it already acts as an endpoint and you are done. Of course your client <-> ELB connection is encrypted, but ELB <-> k8s-cluster is unencrypted. k8s ingress controller As mentioned above, depending on the k8s version you use you could also setup a TLS ingress controller. k8s proxy service Another option is to setup a service inside your k8s cluster, which terminates the ssl connection and proxies the traffic to your meteor application unencrypted. You could use nginx as a proxy for this. In this case I suggest you store your certificate's key inside k8s secret store and mount it inside the nginx container. NEVER ship a container which has secrets such as certificate keys stored inside! Of course you still somehow need to send your encrypted traffic to a k8s node - again, there several ways to achieve this... Easiest would be to modify your DNS entry to point to the k8s nodes, but ideally you would use a TCP LB.
{ "pile_set_name": "StackExchange" }
Q: Map form values to a link I have a particular form on my page with multiple input values and a button. Example: <form id="myForm" method="get"> <input type="text" id="blah1" value="blah" /> <input type="hidden" id="blah2" value="blah2" /> </form> <button type="button" id="awesomeButton">Click for Link</button> <div id="link">http://mysite.com/?blah1=blah&blah2=blah2</div> I want to find an easy way to make it so when someone clicks the button on my website, it looks at all the form values and generates a link which is exactly the same as if the form was set to use method="get" and submitted. So if they click "awesomeButton", then it'll generate a link and show it to the person, such as http://mysite.com/?blah1=blah&blah2=blah2 Does anybody know an easy way to grab the values from the form and make a link? Something like... $('button#awesomeButton').click(function() { //Grab all form elements, maybe something like var blah = $('#myForm :input'); ?? var link = ???;//Generate a link somehow $('div#link').html(link); }); Thanks A: The easy way is to use a library like jQuery or dojo that will do the job for you. In jQuery for example: $("#myForm").serialize(); The documentation is here. In dojo: dijit.byId('myForm').get('value'); Follow this link for the documentation.
{ "pile_set_name": "StackExchange" }
Q: Change the color of arrows using Slick on Github pages I'm using Slick to add a carousel on my Github pages, but I have trouble setting the color of arrows. By default the arrows are white and since my background is white, I try to make the arrows visible and yellow by .slick-prev:before, .slick-next:before { color: yellow; } I only get a yellow arrow, but what I expected is a yellow circle with a white arrow in it. I don't know where went wrong. Really appreciate your help. A: Edit: I just saw the fiddle above. If you set the font-family to initial!important and add color:yellow; then your yellow background will work: .slick-prev:before, .slick-next:before { font-family:initial!important; color:yellow; } (or you could pick a yellow variant) my fiddle Hope this helps
{ "pile_set_name": "StackExchange" }
Q: What application does google use to show PDF attachments in gmail I watched the traffic when google displays PDF attachments in gmail in a new window. The content is served as PNG images for each PDF page. And its text can be selected. What does google use on server side to generate a PNG file for a particular page in a pdf file? How does the selection of text on a png file work? Any ideas? A: By default attachments are viewed securely using https://docs.google.com/gview, however it turns out you are allowed to request files over plain HTTP. This makes it a little bit easier to figure out what is going on using Wireshark. As you indicated it was already clear that the PDF is converted on the server side to a PNG (ImageMagick is indeed a reasonable solution for this purpose), the obvious reason for this is to preserve the exact layout while still being able to view the file without requiring a PDF viewer. However, from looking at the traffic I found out that the entire PDF is also converted to a custom XML format when calling /gview?a=gt&docid=&chan=&thid= (this is done as soon as you request the document). As I couldn't use Wireshark to copy the XML I resorted to the Firefox extension Live HTTP Headers. Here's an excerpt: <pdf2xml> <meta name="Author" content="Bruce van der Kooij"/> <meta name="Creator" content="Writer"/> <meta name="Producer" content="OpenOffice.org 3.0"/> <meta name="CreationDate" content="20090218171300+01'00'"/> <page t="0" l="0" w="595" h="842"> <text l="188" t="99" w="213" h="27" p="188,213">Programmabureau</text> <text l="85" t="127" w="425" h="27" p="85,117,209,61,277,21,305,124,436,75">Nederland Open in Verbinding (NOiV)</text> </page> </pdf2xml> I'm not quite sure yet what all the attributes on the text element stand for (with the exception of w and h) but they're obviously the coordinates of the text and possibly length. As the JavaScript Google uses is minimized (or possibly obsfuscated, but this is not likely) figuring out precisely how the client-side selection function works is not quite that easy. But most likely it uses this XML file to figure out what text the user is looking at and then copies that to the user's clipboard. Note that there is an open source (GPL licensed) tool called pdf2xml which has similar but not quite the same output. Here's the example from their homepage: <?xml version="1.0" encoding="utf-8" ?> <pdf2xml pages="3"> <title>My Title</title> <page width="780" height="1152"> <font size="10" face="MHCJMH+FuturaT-Bold" color="#FF0000"> <text x="324" y="37" width="132" height="10">Friday, September 27, 2002</text> <img x="324" y="232" width="277" height="340" src="text_pic0001.png"/> <link x="324" y="232" width="277" height="340" dest_page="2" dest_x="141" dest_y="187"/> </font> <font size="12" face="AGaramond-Regular" italic="true" bold="true"> <text x="509" y="68" width="121" height="12">This is a test PDF file</text> <link x="509" y="68" width="121" height="12" href="www.mobipocket.com"/> </font> </page> </pdf2xml> Hope this information is in any way useful, however like one of the other posters mentioned the only way to be sure what Google does is by asking them. It's a shame Google doesn't have an official IRC channel but they do have a forum for Google Docs support questions. Good luck.
{ "pile_set_name": "StackExchange" }
Q: Figures in html have a spot next to them I am trying to organize a gallery using figures, but I keep getting this annoying dot or bullet next to them. Are there any solutions like "list-style-type:none" for figures? Thanks (had to post a link to picture because I'm not allowed yet) A: I suspect that your images are contained in a list and you need to change the list style to none for the relevant list.
{ "pile_set_name": "StackExchange" }
Q: Timing of document.write injected javascripts It looks like this code is causing a timing problem. At what point after the execution of this script will ga.js run? How can we be sure that ga.js has executed if it's injected in this manner? (Another component depends on it) <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> A: I know this doesn't strictly answer your question about document.write but it should solve your problem. ga.js is designed to be used asynchronously. You should be able to do something like this: var _gaq = _gaq || []; _gaq.push(function(){ // Use _gat here freely }); The function pushed into _gaq will be processed once ga.js is loaded. Also it seems like you are using a fairly old version of this code. The newer version doesn't use document.write. (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); If you decide to update your analytics tracking code, I'd recommend you jumping straight to Universal Analytics, that uses a different file called analytics.js instead.
{ "pile_set_name": "StackExchange" }
Q: Create one-way relationship without foreign key I've got a problem with relationships I'm trying to form between some models. I have a Node which has many NodeTasks. This is modelled so that NodeTask belongs_to :node, which works as expected. I would also like to add a reference to an arbitrary NodeTask on Node - let's say first_node_task, as an optional attribute. This is where I'm having trouble. I was able to hack it together so that node.first_node_task could be set and worked as expected with the following migration: add_reference :nodes, :first_node_task, { type: :uuid, foreign_key: { to_table: :node_tasks } } And model: class Node belongs_to :first_node_task, class_name: 'NodeTask', foreign_key: 'first_node_task_id', optional: true end However, I found that I could no longer delete those Nodes, because of the reference to NodeTask. There was some weird reverse relationship going on with the foreign key constraint: ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR: update or delete on table "nodes" violates foreign key constraint "fk_rails_696709283b" on table "node_tasks" How can I model my references so that Node can have a first_node_task set, which is a reference to an arbitrary NodeTask, without affecting the related NodeTask? A: It turns out what I'm trying to do doesn't make sense. Irrelevant to my first_node_task attribute, Nodes have a set of NodeTasks, so something needs to happen to those NodeTasks on Node deletion. Whatever happens to child NodeTasks will happen to the first_node_task, because it is one of them. I realised that I do actually want NodeTasks to be deleted, which mean that if first_node_task is set, it would be deleted also. I solved this by adding a migration to change the foreign key between NodeTask and Node to cascade on deletion, as so: remove_foreign_key :node_tasks, :nodes add_foreign_key :node_tasks, :nodes, on_delete: :cascade
{ "pile_set_name": "StackExchange" }
Q: Laravel 5 Command Scheduler, How to Pass in Options I have a command that takes in a number of days as an option. I did not see anywhere in the scheduler docs how to pass in options. Is it possible to pass options in to the command scheduler? Here is my command with a days option: php artisan users:daysInactiveInvitation --days=30 Scheduled it would be: $schedule->command('users:daysInactiveInvitation')->daily(); Preferably I could pass in the option something along the lines of: $schedule->command('users:daysInactiveInvitation')->daily()->options(['days'=>30]); A: You can just supply them in the command() function. The string given is literally just run through artisan as you would normally run a command in the terminal yourself. $schedule->command('users:daysInactiveInvitation --days=30')->daily(); See https://github.com/laravel/framework/blob/5.0/src/Illuminate/Console/Scheduling/Schedule.php#L36 A: You could also try this as an alternative: namespace App\Console\Commands; use Illuminate\Console\Command; use Mail; class WeeklySchemeofWorkSender extends Command { protected $signature = 'WeeklySchemeofWorkSender:sender {email} {name}'; public function handle() { $email = $this->argument('email'); $name = $this->argument('name'); Mail::send([],[],function($message) use($email,$name) { $message->to($email)->subject('You have a reminder')->setBody('hi ' . $name . ', Remember to submit your work my friend!'); }); } } And in your Kernel.php protected function schedule(Schedule $schedule) { /** Run a loop here to retrieve values for name and email **/ $name = 'Dio'; $email = '[email protected]'; /** pass the variables as an array **/ $schedule->command('WeeklySchemeofWorkSender:sender',[$email,$name]) ->everyMinute(); }
{ "pile_set_name": "StackExchange" }
Q: I need to be able to 'rotate' a list thats in a 'square' looking formation into a diamond shape python I am creating a word search solver and need a way to rotate the word search, which is in a list, so the left corner is the 'top' and the bottom right is at the 'bottom' I have this: Puzzle = ["FUNCTIONRRIRAI", "RAIOONFRCCPWON", "PTCSNOBEUITOLO", "BNCACIANTOSLIH", "RBYOLILYNREFBT", "HYYNOGESTIBRIY", "AATTSIONCMCENP", "UORTENRRCBFVAU", "CEBEECVWIERORI", "PROCESSORTOPYF", "OHCOMPUTERHSOS", "YCYPRESREOSMRW", "OATHBRMVTHHCTR", "PGORWOOUIPSCHP"] I need it in the formation of: Puzzle = ["F","RU","PAN","BTIC",...] so it appears that the word search has been rotated 45 degrees any suggestions/help would be appreciated Code for find_horizontal and words to find: def load_words_to_find(file_name): word_list = [] file = open(file_name, "r") for line in file.readlines(): word_list.append(line) word_list = list(map(lambda s: s.strip(), word_list)) return word_list def find_horizontal(Puzzle, Words, ReplaceWith, Found): # Parameters :- List:Puzzle, List:Words, Character:ReplaceWith, List:Found # Return :- List:Outpuz, List:Found # Find all words which are horizontally in place (left to right and right to left), return the puzzle and list of found words rev = '' Outpuz = Puzzle for line in Puzzle: rev = line[::-1] for word in Words: if word in line: Found.append(word) Puzzle[Puzzle.index(line)] = line.replace(word, ReplaceWith * len(word)) if word in rev: Found.append(word) Puzzle[Puzzle.index(line)] = line.replace(word[::-1], ReplaceWith * len(word)) else: pass print("Found: ", Found) print(Outpuz) return Outpuz, Found find_horizontal(Puzzle, load_words_to_find("words.txt"), ".", []) A: Kind of silly, but you could insert string iterators to the front of a list, and then join and yield the next character from each iterator. rows = [ "FUNCTIONRRIRAI", "RAIOONFRCCPWON", "PTCSNOBEUITOLO", "BNCACIANTOSLIH", "RBYOLILYNREFBT", "HYYNOGESTIBRIY", "AATTSIONCMCENP", "UORTENRRCBFVAU", "CEBEECVWIERORI", "PROCESSORTOPYF", "OHCOMPUTERHSOS", "YCYPRESREOSMRW", "OATHBRMVTHHCTR", "PGORWOOUIPSCHP" ] def get_next_diagonal(rows): iters = [] for row in rows: iters.insert(0, iter(row)) yield "".join(next(it, "") for it in iters) while iters[0].__length_hint__(): yield "".join(next(it, "") for it in iters) for diagonal in get_next_diagonal(rows): print(diagonal) Output: F RU PAN BTIC RNCOT HBCSOI AYYANNO UAYOCOFN COTNLIBRR PERTOIAECR ORBTSGLNUCI YHOEEIEYTIPR OCCCENOSNOTWA PAYOECRNTRSOOI GTPMSVRCIELLN OHRPSWCMBFIO RBEUOIBCRBH WRSTREFEIT OMRETRVNY OVEROOAP UTOHPRU IHSSYI PHMOF SCRS CTW HR P
{ "pile_set_name": "StackExchange" }
Q: Perl module prerequisite not found End goal is to install Excel::Writer::XLSX on a server without internet access. I want to install SUPER as its a prerequisite. Sub::Identify is a prerequisite of SUPER. I believe I installed Sub:Identify successfully. But when I attempt to install SUPER I am prompted that the prerequisite is not installed. Here are the commands I entered on command prompt and the output: cd Sub-Identify-0.14 perl MakeFile.pl perldoc -l Sub::Identify Output: lib\Sub\Identify.pm\ cd SUPER-1.20141117 perl Build.PL Output: Sub::Identify is not installed perl Makefile.PL Output: Warning: prerequisite Sub::Identify 0 not found. A: You didn't install Sub::Identify. tar zvzf Sub-Identify-0.14.tar.gz cd Sub-Identify-0.14 perl MakeFile.pl make test # missing make install # missing cd .. tar zvzf SUPER-1.20141117.tar.gz cd SUPER-1.20141117 perl Build.PL ./Build.PL test ./Build.PL install cd .. By the way, you could create a mirror of CPAN using CPAN::Mini. If you copy this mirror to your offline machine, you could use cpan to install modules despite not being online.
{ "pile_set_name": "StackExchange" }
Q: how to add different base templates for different languages of same page in django cms How can i add different base templates for different languages of same page in django cms? I am trying to set a page and show it in different languages. And for all the languages, i need to use a different base template. I am completely new django cms. Please help. A: You need to create different page trees per language. Every page has only one template. Use {% trans %} and {% blocktrans %} for translating string in it. Or {% if request.LANGUAGE == "en" %}. If the templates really differ that much: don't add other languages to pages... but create different page trees with only one language.
{ "pile_set_name": "StackExchange" }
Q: replace zeroes in numpy array with the median value I have a numpy array like this: foo_array = [38,26,14,55,31,0,15,8,0,0,0,18,40,27,3,19,0,49,29,21,5,38,29,17,16] I want to replace all the zeros with the median value of the whole array (where the zero values are not to be included in the calculation of the median) So far I have this going on: foo_array = [38,26,14,55,31,0,15,8,0,0,0,18,40,27,3,19,0,49,29,21,5,38,29,17,16] foo = np.array(foo_array) foo = np.sort(foo) print "foo sorted:",foo #foo sorted: [ 0 0 0 0 0 3 5 8 14 15 16 17 18 19 21 26 27 29 29 31 38 38 40 49 55] nonzero_values = foo[0::] > 0 nz_values = foo[nonzero_values] print "nonzero_values?:",nz_values #nonzero_values?: [ 3 5 8 14 15 16 17 18 19 21 26 27 29 29 31 38 38 40 49 55] size = np.size(nz_values) middle = size / 2 print "median is:",nz_values[middle] #median is: 26 Is there a clever way to achieve this with numpy syntax? Thank you A: This solution takes advantage of numpy.median: import numpy as np foo_array = [38,26,14,55,31,0,15,8,0,0,0,18,40,27,3,19,0,49,29,21,5,38,29,17,16] foo = np.array(foo_array) # Compute the median of the non-zero elements m = np.median(foo[foo > 0]) # Assign the median to the zero elements foo[foo == 0] = m Just a note of caution, the median for your array (with no zeroes) is 23.5 but as written this sticks in 23. A: foo2 = foo[:] foo2[foo2 == 0] = nz_values[middle] Instead of foo2, you could just update foo if you want. Numpy's smart array syntax can combine a few lines of the code you made. For example, instead of, nonzero_values = foo[0::] > 0 nz_values = foo[nonzero_values] You can just do nz_values = foo[foo > 0] You can find out more about "fancy indexing" in the documentation.
{ "pile_set_name": "StackExchange" }
Q: A Color Puzzle for the Occasion! I know this is a bit late, but puzzling SE's birthday is today or yesterday or really near right now, so I wrote out a birthday message for the site. However, I accidentally spilled my unicorn frappuccino all over my computer screen, and the magicalness (Disclaimer: This is probably not a word.) of the unicorn bled into my screen, scrambling up all of my messages in meaningless letters and blobs of color. Also, the unicorny (this one isn't either) powers of the unicorn frappuccino seemed to have boggled my brain a bit, making me forget what I was writing originally. Can you help me retrieve the message? https://docs.google.com/spreadsheets/d/1e8Ha5YOYnLkhGLolxQN4fZSN14OgFaj--0ZhfgdxLPE/edit?usp=sharing I've put the puzzle up as link form, for I do believe that the StackExchange uploading process does slightly distort the colors, so for maximum accuracy, I've decided to just provide a link to a spreadsheet. Here, just in case, I'd like to note that the unicorn stuff isn't actually a part of the puzzle. Also, not sure what tags to add to this puzzle. A: I apologize as to how I first posted my answer. This is a new account so it wouldn't let me post a comment instead. I realize you're probably only supposed to post full answers but this has been up for a year so I didn't think it would matter much. Putting the colors in the proper order (nothing to do with hex codes as the OP was concerned the the colors displaying correctly gives you the following text string: 1ptupQ2kxCLMwquMEEMrXF_bVRYwVSuVYbfd4s_xbYS0 https://docs.google.com/spreadsheets/d/1J5ylM3WO1Gqcq9HdcFw5xvT4wpNz9d2uBFxVywq_93w/edit?usp=sharing Placing this into the URL gives us Step 2: https://docs.google.com/spreadsheets/d/1ptupQ2kxCLMwquMEEMrXF_bVRYwVSuVYbfd4s_xbYS0/ All I got so far. Really need to get some sleep. Will post the rest later hopefully. ETA: So annoying that I can't comment. Got my first edit all typed up and them saw Fifth_H0r5eman's comment. I wasn't sure too how formal this site was, so after my first post I was second-guessing myself with my chattiness and rambling. Thought maybe I should have stuck to the answer only so I went back and made the edit (plus I had actually figured out the first part!)
{ "pile_set_name": "StackExchange" }
Q: RuntimeError: There's no handler for [insert_filed_name] in the 'validate' domain I am using cerberus v1.3.2 with python-3.8 stable to validate json data that will be used to send http requests. I am having an issue using the dependencies rule. My objects have a field request_type and an optional field payload that contains more data. Only objects that have a request_type in ['CREATE', 'AMEND'] have a payload. When I run the validation, I get an error related to one of the fields in payload. Here is the code I'm running: from cerberus import Validator request = { "request_type": "CREATE", "other_field_1": "whatever", "other_field_2": "whatever", "payload": { "id": "123456", "jobs": [ { "duration": 1800, "other_field_1": "whatever", "other_field_2": "whatever" } ] } } schema = { 'request_type': { 'type': 'string', 'allowed': ['CREATE', 'CANCEL', 'AMEND'], 'required': True, 'empty': False }, 'other_field_1': {'type': 'string', }, 'other_field_2': {'type': 'string', }, 'payload': { 'required': False, 'schema': { 'id': { 'type': 'string', 'regex': r'[A-Za-z0-9_-]`', 'minlength': 1, 'maxlength': 32, 'coerce': str }, 'jobs': { 'type': 'list', 'schema': { 'duration': { 'type': 'integer', 'min': 0, 'required': True, 'empty': False, }, 'other_field_1': {'type': 'string', }, 'other_field_2': {'type': 'string', }, } } }, 'dependencies': {'request_type': ['CREATE', 'AMEND']}, } } validator = Validator(schema, purge_unknown=True) if validator.validate(request): print('The request is valid.') else: print(f'The request failed validation: {validator.errors}') And this is the error I'm getting: "RuntimeError: There's no handler for 'duration' in the 'validate' domain." Is there something I'm doing wrong? For context, I managed to make the validation work by using the exact same rules, but instead of using dependencies, I have two separate schemas named payload_schema and no_payload_schema. In payload_schema I set the allowed values for request_type to ['CREATE', 'AMEND'], and in no_payload_schema I set the allowed values to ['CANCEL']. I run the validation on both schemas and if neither of them passes, I raise an error. This sounds a bit hacky and I'd like to understand how I could use the dependencies rule to do that. A: Mind the difference between schema being used for mappings and sequences. The jobs field's value won't be checked as mapping since you require it to be of list type. You'll need this pattern: {"jobs": { {"type": "list", "schema": { "type": "dict", "schema": {"duration": ...} } } } } This ambiguity of the schema rule will be addressed in the next major release of Cerberus. For the sake of readability one may use schema- and rule set-registries with complex validation schemas. It is generally advisable to ask with minimum examples for support.
{ "pile_set_name": "StackExchange" }
Q: Flex 3: is md5 possible? Is there a way to use some kind of encryption (md5, hash, etc...) to determine if two arraycollections are the same or not? A: It looks like there are a couple libraries for generating a hash. http://code.google.com/p/as3corelib/ Edit: Answered already ActionScript Comparing Arrays
{ "pile_set_name": "StackExchange" }
Q: How to align texts inside of an input? For all default inputs, the text you fill starts on the left. How do you make it start on the right? A: Use the text-align property in your CSS: input { text-align: right; } This will take effect in all the inputs of the page. Otherwise, if you want to align the text of just one input, set the style inline: <input type="text" style="text-align:right;"/> A: Try this in your CSS: input { text-align: right; } To align the text in the center: input { text-align: center; } But, it should be left-aligned, as that is the default - and appears to be the most user friendly. A: The accepted answer here is correct but I'd like to add a little info. If you are using a library / framework like bootstrap there may be built in classes for this. For example bootstrap uses the text-right class. Use it like this: <input type="text" class="text-right"/> <input type="number" class="text-right"/> As a note this works on other input types as well, like numeric as shown above. If you aren't using a nice framework like bootstrap then you can make your own version of this helper class. Similar to other answers but we are not going to add it directly to the input class so it won't apply to every single input on your site or page, this might not be desired behavior. So this would create a nice easy css class to align things right without needing inline styling or affecting every single input box. .text-right{ text-align: right; } Now you can use this class exactly the same as the inputs above with class="text-right". I know it isn't saving that many key strokes but it makes your code cleaner.
{ "pile_set_name": "StackExchange" }
Q: Keep selected fields order with HYDRATE_ARRAY in Doctrine 1.2 My question is quite simple but I can't manage to find an answer. When I execute a query like: $query->select('t2.name as t2_name, t1.name as t1_name') ->from('table1 t1') ->leftJoin('t1.table2 t2') ->execute(array(), Doctrine_Core::HYDRATE_ARRAY); Doctrine returns me an array like: array( [0] => array( 't1_name' => 'foo', 't2_name' => 'bar' ) ) Where i expected to get field t2_name to be set in the array before t1_name. Is there anyway to keep the order of these selected fields in Doctrine ? A: Doctrine will automatically include the primary (root) table's key field and automatically make it the first column in any query, in almost all hydration types. Since table1 is the root table in your query, it moves that to the beginning for its own internal processing benefits. I find this behavior annoying and somewhat unpredictable at times also, but have found great relief by creating custom hydrators. There's a good example of creating a key/value hydrator which I have used beneficially many times in our code. You could do something similar to rearrange the fields in the order you want. Also I have posted an explanation to a very similar question here which may be beneficial.
{ "pile_set_name": "StackExchange" }
Q: Selecting tags by content in Jsoup and getting nth tag after the given tag I have an HTML document I want to scrape data from. The tag of the data has no unique identifier except that it is the 13th <td> tag from the <td> tag containing the given string. So, for example, the 10th <td> tag in the document contains the word "dog" ( ie <td>dog</td>. Also no other <td> tag in the document contains identical data.). Given only the word "dog", is it possible for me to extract the content inside the 23rd <td> tag in the document using Jsoup methods, and if so how? Edit: <td>Cat</td> <td align="center">40</td> <td align="center">67</td> <td align="center">58<br>0</td> <td align="center">32</td> <td>Dog</td> <td align="center">0</td> <td align="center">0</td> <td align="center">58<br>0</td> <td align="center">99</td> <td>Snake</td> <td align="center">7</td> <td align="center">85</td> <td align="center">58<br>0</td> <td align="center">13</td> In a document like this, given only the animal's name, I would like to be able to extract the number in the n'th tag from it, let's say 4. So given "Cat" I would like to find 32. Given "Dog", 99. And for snake 13. Assume there are hundreds of animals in the document. A: You can use structural pseudo selectors to target the nth element. doc.select("td:nth-child(23)"); Since you are looking for the row with Dog, you could select that row first. Element dogRow = doc.select("tr:has(td:contains(dog))").first(); and then select the 23rd child String cellValue = dogRow.select("td:nth-child(23)").first().ownText(); or combine them String cellValue = doc .select("tr:has(td:contains(dog)) > td:nth-child(23)") .first() .ownText(); Edit I reread your question and seems like you want to find Dog within a row and then find the nth sibling. You could use the elementSiblingIndex and getElementsByIndexEquals for this: Element dogRow = doc.select("tr:has(td:contains(dog))").first(); int dogCellIndex = dogRow .select("td:contains(dog)") .first() .elementSiblingIndex(); int otherCellIndex = dogCellIndex + 10; String cellValue = dogRow .getElementsByIndexEquals(otherCellIndex) .text();
{ "pile_set_name": "StackExchange" }
Q: How to figure out why ssh session does not exit sometimes? I have a C++ application that uses ssh to summon a connection to the server. I find that sometimes the ssh session is left lying around long after the command to summon the server has exited. Looking at the Centos4 man page for ssh I see the following: The session terminates when the command or shell on the remote machine exits and all X11 and TCP/IP connections have been closed. The exit status of the remote program is returned as the exit status of ssh. I see that the command has exited, so I imagine not all the X11 and TCP/IP connections have been closed. How can I figure out which of these ssh is waiting for so that I can fix my summon command's C++ application to clean up whatever is being left behind that keeps the ssh open. I wonder why this failure only occurs some of the time and not on every invocation? It seems to occur approximately 50% of the time. What could my C++ application be leaving around to trigger this? More background: The server is a daemon, when launched, it forks and the parent exits, leaving the child running. The client summons by using: popen("ssh -n -o ConnectTimeout=300 user@host \"sererApp argsHere\"" " 2>&1 < /dev/null", "r") A: Use libssh or libssh2, rather than calling popen(3) from C only to invoke ssh(1) which itself is another C program. If you want my personal experience, I'd say try libssh2 - I've used it in a C++ program and it works.
{ "pile_set_name": "StackExchange" }
Q: CellForRow is called with delay I try to load data from a web server whenever the user location has significantly changed. My problem is, that with any location change the tableview calls "numberOfRows" but it waits like 30 seconds until "cellForRowAtIndexPath" is called. Or until the user has moved the table. I also sometimes experienced random warnings that auto layout was influenced from not the main queue thread (which might be related to this problem) Where is my Problem? Maybe I doing things 2 times async is not good? Here is my code: import UIKit import MapKit class GroundListTVCTEST: UITableViewController,CLLocationManagerDelegate, UISearchBarDelegate, UISearchControllerDelegate { var locationManager = CLLocationManager() var searchController :TKSearchController! var localSearchRequest :MKLocalSearchRequest! var localSearch :MKLocalSearch! var localSearchResponse :MKLocalSearchResponse! var grounds:[Ground]? { didSet { self.tableView.reloadData() } } override func viewDidLoad() { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters locationManager.startMonitoringSignificantLocationChanges() let distance:CLLocationDistance = 1000.0 locationManager.distanceFilter = distance } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.locationManager.startUpdatingLocation() print("Location Manager started.") } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) locationManager.stopUpdatingLocation() print("Location Manager stopped.") } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { print("cellForRow called") let cell = tableView.dequeueReusableCellWithIdentifier("Cell") cell?.textLabel?.text = grounds?[indexPath.row].name return cell! } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { print("number of rows called") return grounds?.count ?? 0 } // MARK: - Delegate Methods func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { print("Location Manager updated location.") if let location = manager.location { self.locationUpdateWithNewLocation(location) } } func locationUpdateWithNewLocation(location: CLLocation) { GroundHelper.getAllGroundLocations(location, completionHandler: { (grounds: [Ground]?) -> Void in self.grounds = grounds?.sort({$0.distance < $1.distance}) }) } } A: Looks like that's because GroundHelper.getAllGroundLocations returns value in background queue. Try to dispatch it in main queue: GroundHelper.getAllGroundLocations(location, completionHandler: { (grounds: [Ground]?) -> Void in dispatch_async(dispatch_get_main_queue(),{ self.grounds = grounds?.sort({$0.distance < $1.distance}) }) })
{ "pile_set_name": "StackExchange" }
Q: Managing application settings in an Electron application I'm curious to know how can one manage application settings in an Electron application? I have found some excellent resources here (Where to store user settings in Electron (Atom Shell) Application?, for example) and elsewhere when it comes to managing user settings but couldn't find anything related to managing application settings. To me, the difference between the two is that application settings could vary from environment to environment (dev/test/production) but would remain the same for all users of the application. They would contain things like API endpoints etc. User settings on the other hand would change from user to user based on their preferences like window width/height etc. What I have done so far? I have found this excellent package called config and start using it in my project. Based on the instructions, I have created a config folder and a default configuration file (I will create environment specific configuration files later). It is working fine as long as I am developing the application. The application is picking up the default.json file properly from the config folder and is applying those settings correctly. The problem comes when I package the application (MSI, DMG etc.). I am using electron-builder package for that purpose. The problem with config package is that it looks for config folder inside the application's current working directory and because it doesn't find it in the folder where the application is installed, it simply throws an error. I even tried to manually copy this folder in my app folder (which is where electron-builder makes the packages) but that didn't help either. Ideally I would like to bundle the app settings in application's ASAR file so that it can't be decompiled. My questions are: How are people managing application settings for an Electron application? Can config NPM package be used for that? Or is there an alternative to that package specifically for Electron applications? A: I am not using an npm package but my approach is similar to what you have mentioned. I have a config directory with different config files for different environments: dev, test, prod. Then in my package.json I have added environment specific build commands. e.g. For prod: "build-prod-config": "config/buildProdConfig.sh", "build-renderer-prod": "webpack --config=webpack.config.renderer.prod.js", "build-main-prod": "webpack --config=webpack.config.main.prod.js", "build-prod": "npm run build-prod-config && npm run build-main-prod & npm run build-renderer-prod", buildProdConfig.sh #!/usr/bin/env bash cp config/app.config.prod.js config/app.config.js echo "Copied ProdConfig to Config" //This is what a config file looks like const Config = { suppDataDirectoryPath: '/suppData/', builtFor: 'prod', } module.exports = Config; I then require Config whereever I need in my application and use the values. This is a simple thing for now, and perhaps doesn't have the flexibility of the config package you linked to, but it works. Also, another important thing is that I am not packing my application into an ASAR archive, but I think my approach would still work because I am packing everything into a bundle using webpack.
{ "pile_set_name": "StackExchange" }
Q: Setting UIImageView image affects layout constraints I am creation a simple UIImageView with the following constraints: self.view.addConstraint(imageView.topAnchor.constraint(equalTo: contentLayoutGuide.topAnchor)) self.view.addConstraint(imageView.centerXAnchor.constraint(equalTo: contentLayoutGuide.centerXAnchor)) self.view.addConstraint(imageView.heightAnchor.constraint(equalTo: contentLayoutGuide.heightAnchor)) self.view.addConstraint(imageView.widthAnchor.constraint(equalTo: contentLayoutGuide.heightAnchor)) The important one is the last one, which sets the width equal to the height of the image view and the height of the image view is being defined by top and bottom anchor. Now this looks perfectly fine (see image below) However when setting imageView.image the image is all over the screen and way too big. This debugging process fixes it: po for cn in self.imageView!.constraints { cn.isActive = false } po CATransaction.flush() This makes the image fit inside the imageView as it is intended but up until this point, the imageView is messed up. What is interesting, before setting the image, the imageView itself does not have any constraints and then setting the image creates those two: - 0 : <NSContentSizeLayoutConstraint:0x6040002b2120 UIImageView:0x7fa98f757b90.width == 488 Hug:250 CompressionResistance:750 (active)> - 1 : <NSContentSizeLayoutConstraint:0x6040002b2180 UIImageView:0x7fa98f757b90.height == 487 Hug:250 CompressionResistance:750 (active)> Those constraints seem to break it, because disabling them fixes the problem. They are only added when setting an image A: Try to lower the content compression/hugging. I think (correct me if I am wrong) the UIImageView has by default a higher compression/hugging resistance than a UIView (251 to 250). You could try the code below: someImage.setContentHuggingPriority(UILayoutPriority(rawValue: 249), for: .horizontal) someImage.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 249), for: .horizontal) someImage.setContentHuggingPriority(UILayoutPriority(rawValue: 249), for: .vertical) someImage.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 249), for: .vertical)
{ "pile_set_name": "StackExchange" }
Q: How does a human classify or cluster data? Here, what I mean by DATA are text documents. I am going to do a research on text clustering algorithms by the help of artificial neural networks (ANNs). But first of all I need to know how our brain (neural system) cluster (or classify) text data while we are reading a document. Imagine we are reading some uncategorized and scattered news articles around the internet (For example on a weblog). Here, when we read an article, we'll easily find out that what it is about or what group it goes under: Politics, Sports, Economic, etc. We'll know it by the help of words inside the article, I know. How does our brain cluster these data inside itself. How do we make clusters/categories inside our brain, and then assign data to them? A: Here is an article written on a study on the measured effects of blood flow in the brain from "two hours of movie trailers that contained over 1,700 categories of actions and objects". A video (attached in the article) describes the methods used and the results of the study. They found that the brain tended to categorize things that shared similar functions or is-a relationships. This can be seen in the resulting chart, where the nodes representing "mammals", "people" and "communication verbs" are closely related. The brain also seemed to separate things that moved or were considered to be alive and inanimate objects. This study was done using only 5 participants so it's fair to say that more research needs to be done before we can uncover more of the truth concerning this topic. To answer your second question, regarding how information is stored in the brain, we need to understand a process called "encoding". I don't fully understand how this process works on a biological level, but as a gross explanation the brain stores sensory information it deems important and then goes through a secondary process called "consolidation". This process aims to stabilize the trace of a memory after it is initially encoded. The final process, "retrieval" is the act of remembering the information. During this stage the brain reconstructs the memory or information and thereby strengthens the neural pathway that makes up that memory. So in short, the brain stores information through complex neural connections. These neural connections are tied to the sensory information that was initially perceived, which is reconstructed when you remember it. Hope I was able to clear up some of your questions :)
{ "pile_set_name": "StackExchange" }
Q: Line continuation in XML I am working with the Firefox localstore.rdf file. Although it is an RDF file the syntax is essentially XML. I am dealing with long lines. <NC:persist RDF:resource="#nav-bar" currentset="unified-back-forward-button,history-button,feed-button,abp-toolbarbutton,widget:jid0-HFFmJoceGjTSKDBEWPpzfX9By7I@jetpack-hds-link-detector,firebug-button,personal-bookmarks"/> I would like to break these lines to fit 80 character if possible. A: You can try if Firefox trims whitespace per each element in the currentset: <NC:persist RDF:resource="chrome://browser/content/browser.xul#nav-bar" currentset="unified-back-forward-button,history-button,feed-button, abp-toolbarbutton, widget:jid0-HFFmJoceGjTSKDBEWPpzfX9By7I@jetpack-hds-link-detector, firebug-button,personal-bookmarks"/> You would need to test if that works. According to Firefox sources, they keep the currentset attribute on a single line, always. From what I know, even technically possible with XML (see Are line breaks in XML attribute values valid?), the pretty-printers I know do not distribute an attribute value across multiple lines (please see Attribute-Value Normalization), so I would run some tests if you really need that as this depends on which value the application expects.
{ "pile_set_name": "StackExchange" }
Q: How to remove a layerGroup in leaflet? it is easy to add a layerGroup to a leaflet map by simply calling layergroup.addTo(map). How I can I remove the whole layergroup from the map? I tried layergroup.eachLayer(function(layer) { map.removeLayer(layer);}); But, the map begins to behaviour weirdly. A: You can simply use the removeLayer method, like this: map.removeLayer(layerGroup) Take a look at this plunker (click on the map to remove the layer): http://plnkr.co/edit/jSUE8ft9p7odLhQGeOVa
{ "pile_set_name": "StackExchange" }
Q: How I can use Gson in Retrofit library? I used Retrofit for send request and receive the response in android but have problem when I want convert response which come from the sever it is always give me Exception: retrofit.RetrofitError: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING When response from server should give me list from movies so I need put all this movies in list. Movie (Model Class): public class Movie { public Movie() {} @SerializedName("original_title") private String movieTitle; @SerializedName("vote_average") private String movieVoteAverage; @SerializedName("overview") private String movieOverview; ............ } GitMovieApi Class: public interface GitMovieApi { @GET("/3/movie/{movie}") public void getMovie(@Path("movie") String typeMovie,@Query("api_key") String keyApi, Callback<Movie> response); } RestAdapter configuration: RestAdapter restAdapter = new RestAdapter.Builder() .setLogLevel(RestAdapter.LogLevel.FULL) .setConverter(new GsonConverter(new GsonBuilder().registerTypeAdapter(Movie.class, new UserDeserializer()).create())) .setEndpoint("http://api.themoviedb.org") .build(); GitMovieApi git = restAdapter.create(GitMovieApi.class); git.getMovie("popular", "Keyapi", new Callback<Movie>() { @Override public void success(Movie movie, Response response) { Toast.makeText(getActivity(), "s", Toast.LENGTH_LONG).show(); } @Override public void failure(RetrofitError error) { Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_LONG).show(); } }); UserDeserializer: public class UserDeserializer implements JsonDeserializer<Movie> { @Override public Movie deserialize(JsonElement jsonElement, Type typeOF, JsonDeserializationContext context) throws JsonParseException { JsonElement userJson = new JsonParser().parse("results"); return new Gson().fromJson(userJson, Movie.class); } } Json(Response): { "page": 1, "results": [ { "adult": false, "backdrop_path": "/tbhdm8UJAb4ViCTsulYFL3lxMCd.jpg", "genre_ids": [ 53, 28, 12 ], "id": 76341, "original_language": "en", "original_title": "Mad Max: Fury Road", "overview": "An apocalyptic story set in the furthest.", "release_date": "2015-05-15", "poster_path": "/kqjL17yufvn9OVLyXYpvtyrFfak.jpg", "popularity": 48.399601, "title": "Mad Max: Fury Road", "video": false, "vote_average": 7.6, "vote_count": 2114 }, { "adult": false, "backdrop_path": "/sLbXneTErDvS3HIjqRWQJPiZ4Ci.jpg", "genre_ids": [ 10751, 16, 12, 35 ], "id": 211672, "original_language": "en", "original_title": "Minions", "overview": "Minions Stuart.", "release_date": "2015-06-25", "poster_path": "/s5uMY8ooGRZOL0oe4sIvnlTsYQO.jpg", "popularity": 31.272707, "title": "Minions", "video": false, "vote_average": 6.8, "vote_count": 1206 }, ], "total_pages": 11871, "total_results": 237415 } A: You don't even need to make a custom deserializer here. Get rid of UserDeserializer entirely, it's not needed. Your query is returning a list of movies, so make your callback to an object that actually reads the list of movies: public class MovieList { @SerializedName("results") List<Movie> movieList; // you can also add page, total_pages, and total_results here if you want } Then your GitMovieApi class would be: public interface GitMovieApi { @GET("/3/movie/{movie}") public void getMovie(@Path("movie") String typeMovie, @Query("api_key") String keyApi, Callback<MovieList> response); } Your RestAdapter: RestAdapter restAdapter = new RestAdapter.Builder() .setLogLevel(RestAdapter.LogLevel.FULL) .setConverter(new GsonConverter(new GsonBuilder()).create())) .setEndpoint("http://api.themoviedb.org") .build(); GitMovieApi git = restAdapter.create(GitMovieApi.class); The problem is not that you have written the Deserializer incorrectly (although, you have, but it's okay because you don't need it, JsonParser is not how you do it), but the default deserialization behavior should work just fine for you. Use the above code and it will work just fine.
{ "pile_set_name": "StackExchange" }
Q: How to run nested left join in mysql I have three tables, likes, users and statuses. So I am returning from likes tables and joining likes table with user table to see who liked it and joining likes table with statuses table to see who posted it. Now want to get the user information from status table to see who wrote the status. Here comes the problem. SQL Fiddle http://sqlfiddle.com/#!9/d0707b/2 My current query select l.*, s.* , a.id as aid, a.userName from likes l left join statuses s on l.source_id = s.id left join users a on l.user_id = a.id where l.user_id in (5,7) or (s.privacy='Public' and s.interest in ('mobile', 'andriod') ) order by l.id desc Here s.user_id=a.id I want to join the statuses table with user table. [If question is not clear please comment, will try to edit] Thank you. A: You have to make a join to the user table again. Take a look here: SELECT l.*, s.*, a.id AS aid, a.userName, b.userName FROM likes l LEFT JOIN statuses s ON l.source_id = s.id LEFT JOIN users a ON l.user_id = a.id LEFT JOIN users b ON s.user_id = b.id WHERE l.user_id IN (5, 7) OR ( s.privacy = 'Public' AND s.interest IN ('mobile', 'andriod') ) ORDER BY l.id DESC
{ "pile_set_name": "StackExchange" }
Q: Accessing Samba share through Raspberry Pi SSH I have a raspberry Pi at home that I can access over the internet using SSH (using only key authentication), which is behind a TP-Link router. This router has a hard drive attached to it, which I can access as a samba share locally using the router's IP address. I would like to access this hard drive when I'm away from home, but I don't want to expose my samba share to the internet (needless to say why). Is there a way I can access it securely through my Raspberry Pi's SSH server ? A: I am not 100% sure, if this is what you want. But what you can do: Mount your router drive via samba to your RPi's mount point. Access your PRi via sshfs. http://en.wikipedia.org/wiki/SSHFS Works for me like a charm. I found that using sshfs is much easier than nfs or samba under Linux. This solution definitely works when you access your RPi under Linux. Windows -> RPi, or Mac -> RPi.... perhaps, I don't know. I think there are sshfs solutions, but I don't know how stable or usable they are.
{ "pile_set_name": "StackExchange" }
Q: Assign grep count to variable How to assign the result of grep -c "some text" /tmp/somePath into variable so I can echo it. #!/bin/bash some_var = grep -c "some text" /tmp/somePath echo "var value is: ${some_var}" I also tried: some_var = 'grep -c \"some text\" /tmp/somePath' But I keep getting: command not found. A: To assign the output of a command, use var=$(cmd) (as shellcheck automatically tells you if you paste your script there). #!/bin/bash some_var=$(grep -c "some text" /tmp/somePath) echo "var value is: ${some_var}" A: Found the issue Its the assignment, this will work: some_var=$(command) While this won't work: some_var = $(command) Thank you for your help! I will accept first helpful answer. A: some_var=$(grep -c "some text" /tmp/somePath) From man bash: Command substitution allows the output of a command to replace the com‐ mand name. There are two forms: $(command) or `command` Bash performs the expansion by executing command and replacing the com‐ mand substitution with the standard output of the command, with any trailing newlines deleted.
{ "pile_set_name": "StackExchange" }
Q: MVC ViewModels and Entity Framework queries I am new to both MVC and Entity Framework and I have a question about the right/preferred way to do this. I have sort of been following the Nerd Dinner MVC application for how I am writing this application. I have a page that has data from a few different places. It shows details that come from a few different tables and also has a dropdown list from a lookup table. I created a ViewModel class that contains all of this information: class DetailsViewModel { public List<Foo> DropdownListData { get; set; } // comes from table 1 public string Property1 { get; set; } public string Property2 { get; set; } public Bar SomeBarObject { get; set; } // comes from table 2 } In the Nerd Dinner code, their examples is a little too simplistic. The DinnerFormViewModel takes in a single entity: Dinner. Based on the Dinner it creates a SelectList for the countries based on the dinners location. Because of the simplicity, their data access code is also pretty simple. He has a simple DinnerRepository with a method called GetDinner(). In his action methods he can do simple things like: Dinner dinner = new Dinner(); // return the view model return View(new DinnerFormViewModel(dinner)); OR Dinner dinner = repository.GetDinner(id); return View(new DinnerFormViewModel(dinner)); My query is a lot more complex than this, pulling from multiple tables...creating an anonymous type: var query = from a in ctx.Table1 where a.Id == id select new { a.Property1, a.Property2, a.Foo, a.Bar }; My question is as follows: What should my repository class look like? Should the repository class return the ViewModel itself? That doesn't seem like the right way to do things, since the ViewModel sort of implies it is being used in a view. Since my query is returning an anonymous object, how do I return that from my repository so I can construct the ViewModel in my controller actions? A: While most of the answers are good, I think they are missing an in-between lines part of your question. First of all, there is no 100% right way to go about it, and I wouldn't get too hung up on the details of the exact pattern to use yet. As your application gets more and more developped you will start seeing what's working and what's not, and figure out how to best change it to work for you and your application. I just got done completely changing the pattern of my Asp.Net MVC backend, mostly because a lot of advice I found wasn't working for what I was trying to do. That being said, look at your layers by what they are supposed to do. The repository layer is solely meant for adding/removing/and editing data from your data source. It doesn't know how that data is going to be used, and frankly it doesn't care. Therefore, repositories should just return your EF entities. The part of your question that other seem to be missing is that you need an additional layer in between your controllers and the repositories, usually called the service layer or business layer. This layer contains various classes (however you want to organize them) that get called by controllers. Each of these classes will call the repository to retrieve the desired data, and then convert them into the view models that your controllers will end up using. This service/business layer is where your business logic goes (and if you think about it, converting an entity into a view model is business logic, as it's defining how your application is actually going to use that data). This means that you don't have to call specific conversion methods or anything. The idea is you tell your service/business layer what you want to do, and it gives you business entities (view models) back, with your controllers having no knowledge of the actual database structure or how the data was retrieved. The service layer should be the only layer that calls repository classes as well. A: You are correct a repository should not return a view model. As changes to your view will cause you to change your data layer. Your repository should be an aggregate root. If your property1, property2, Foo, Bar are related in some way I would extract a new class to handle this. public class FooBarDetails { public string Property1 {get;set;} public string Property2 {get;set;} public Foo Foo {get;set;} public Bar Bar {get;set;} } var details = _repo.GetDetails(detailId); If Foo and Bar are not related at all it might be an option to introduce a service to compose your FooBarDetails. FooBarDetails details = _service.GetFooBar(id); where GetFooBar(int) would look something like this: _fooRepo.Get(id); _barRepo.Get(id); return new FooBarDetails{Foo = foo, Bar = bar, Property1 = "something", Property2 = "something else"}; This all is conjecture since the design of the repository really depends on your domain. Using generic terms makes it hard to develop potential relationships between your objects. Updated From the comment if we are dealing with an aggregate root of an Order. An order would have the OrderItem and also the customer that placed the order. public class Order { public List<OrderItem> Items{get; private set;} public Customer OrderedBy {get; private set;} //Other stuff } public class Customer { public List<Orders> Orders{get;set;} } Your repo should return a fully hydrated order object. var order = _rep.Get(orderId); Since your order has all the information needed I would pass the order directly to the view model. public class OrderDetailsViewModel { public Order Order {get;set;} public OrderDetailsViewModel(Order order) { Order = order; } } Now having a viewmodel with only one item might seem overkill (and it most likely will be at first). If you need to display more items on your view it starts to help. public class OrderDetailsViewModel { public Order Order {get;set;} public List<Order> SimilarOrders {get;set;} public OrderDetailsViewModel(Order order, List<Order> similarOrders) { Order = order; SimilarOrders = similarOrders; } }
{ "pile_set_name": "StackExchange" }
Q: Connecting to multiple CosmosDB documents I am trying to have multiple documents in Cosmos, one will hold some data from a submit form once it is submitted. I am trying to have a few other documents to hold the data for a drop down select list. How am I able to connect to multiple config.containerId to read some data and then write some data? I am currently only able to read/write to one. Thanks for any help! const config = {}; config.host = process.env.HOST || "https://localhost:8081"; config.authKey = process.env.AUTH_KEY || "key"; config.databaseId = "ToDoList"; config.containerId = "Items"; config.containerId2 = "List"; if (config.host.includes("https://localhost:")) { console.log("Local environment detected"); console.log("WARNING: Disabled checking of self-signed certs. Do not have this code in production."); process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; console.log(`Go to http://localhost:${process.env.PORT || '3000'} to try the sample.`); } module.exports = config; const CosmosClient = require('@azure/cosmos').CosmosClient const config = require('./config') const TaskList = require('./routes/tasklist') const TaskDao = require('./models/taskDao') const express = require('express') const path = require('path') const logger = require('morgan') const cookieParser = require('cookie-parser') const bodyParser = require('body-parser') const app = express() // view engine setup app.set('views', path.join(__dirname, 'views')) app.set('view engine', 'jade') // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')) app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: false })) app.use(cookieParser()) app.use(express.static(path.join(__dirname, 'public'))) //Todo App: const cosmosClient = new CosmosClient({ endpoint: config.host, key: config.authKey }) const taskDao = new TaskDao(cosmosClient, config.databaseId, config.containerId) //const taskDao = new TaskDao(cosmosClient, config.databaseId, config.containerId2) const taskList = new TaskList(taskDao) taskDao .init(err => { console.error(err) }) .catch(err => { console.error(err) console.error( 'Shutting down because there was an error settinig up the database.' ) process.exit(1) }) app.get('/', (req, res, next) => taskList.showTasks(req, res).catch(next)) app.post('/addtask', (req, res, next) => taskList.addTask(req, res).catch(next)) app.post('/completetask', (req, res, next) => taskList.completeTask(req, res).catch(next) ) app.set('view engine', 'jade') // catch 404 and forward to error handler app.use(function(req, res, next) { const err = new Error('Not Found') err.status = 404 next(err) }) // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message res.locals.error = req.app.get('env') === 'development' ? err : {} // render the error page res.status(err.status || 500) res.render('error') }) module.exports = app form(action="/completetask", method="post") label Closure Plan: <select name="ClosurePlan" id="ClosurePlanList" type="form" > if (typeof tasks === "undefined") tr td else each task in tasks tr <option value="Planned Closure">#{task.name}</option> Rest of the code is from here: https://github.com/MicrosoftDocs/azure-docs/blob/master/articles/cosmos-db/sql-api-nodejs-application.md A: You just need to instantiate another TaskDao to connect to your second container. Pls follow the steps below : Make sure that you have followed the doc and you can run the website on your local successfully as all my code modification is based on this demo. In my case, I have a DB named "ToDoList" which has two collections "Items" and "Items2". Go to config.js and add two configs for Items2: config.databaseId2 = "ToDoList"; config.containerId2 = "Items2"; Go to app.js , instantiate TaskDao2 : const taskDao2 = new TaskDao(cosmosClient, config.databaseId2, config.containerId2) taskDao .init(err => { console.error(err) }) .catch(err => { console.error(err) console.error( 'Shutting down because there was an error settinig up the database.' ) process.exit(1) }) taskDao2 .init(err => { console.error(err) }) .catch(err => { console.error(err) console.error( 'Shutting down because there was an error settinig up the database.' ) process.exit(1) }) const taskList = new TaskList(taskDao,taskDao2) Finally, go to routes/tasklist.js, modify constructor method as below : constructor(taskDao,taskDao2) { this.taskDao = taskDao; this.taskDao2 = taskDao2; } With this step is done, your app could connect to your another collection successfully. I write the same data to items2 collection when we adding tasks, go to addTask method and add the code below : await this.taskDao2.addItem(item); Ok, lets start the web app and add a task : Have a check the data in cosmos db : As you can see, you can write data to another collection now. Hope it helps .
{ "pile_set_name": "StackExchange" }
Q: issue with column name 'type' in rails 3 I have a columns named 'type' in one of my tables. When I try to access it like group.type, I got the following error: super: no superclass method `type' for #<Group:0x000000035eaf30> However, when I try to rename the column using a migration, I get the following error No such column: groups.type (migration failed) I tried to rename the column directly in the mysql db, using a query, but that doesn't work either. mysql> alter table groups change type group_type int(11); ERROR 1054 (42S22): Unknown column 'type' in 'groups' Please help. A: The error comes from the single table inheritance feature that comes with ActiveRecord. Just tell it to use a different column than type: class Group < ActiveRecord::Base self.inheritance_column = "not_sti" #... end With that, you don't have to rename the column.
{ "pile_set_name": "StackExchange" }
Q: How could Leia sense a specific death among so many? In Star Wars: The Force Awakens, when Han Solo died, Leia became aware of it instantly. Yes, Leia is force sensitive, but when Alderaan was destroyed, Obi-Wan heard billions of voices crying and going out of existence which is generic. When Han Solo died, Lots of people were also dying there. How could Leia intercept particular death signal provided that Han wasn't force sensitive? Talking about love, when Padme died, Vader never sensed it. Then, how come Leia sense this? A: Firstly, the timing isn't quite how you've portrayed it in your question: Leia reacts to Han's death well before the planet is actually destroyed, more or less immediately after he is killed. There is also precedent for Leia being sensitive in this way, i.e. able to sense the well-being of those she is very close to. When the second Death Star is destroyed, Leia is confident that Luke escaped the explosion. Han doesn't need to be a force-user for this kind of sensitivity to work. In The Empire Strikes Back, Vader's troops torture Han so that Luke will sense that his friends are in danger and attempt to rescue them, being drawn into Vader's trap. Another good example of this kind of sensitivity is Yoda being able to sense the jedi being slaughtered during the execution of Order 66. Many of the jedi are dying in war zones with lots of other death around them, but it's strongly implied that Yoda is sensing their deaths specifically rather than just general carnage. Regarding Vader/Padme, Padme's death occurs after Darth Vader loses his fight with Obi Wan on Mustafar, and before he wakes up from the life-saving medical treatment that leaves him in his famous suit. He was either unconscious or wracked with extreme pain at the moment she died, and so far this force-mediated awareness seems to occur at the moment of death rather than hanging around afterwards. (It's also possible that he wasn't well enough recovered to trust his senses, or that he sensed she was dead but was in denial about it.) A: In @SS-3's comment is perhaps another way to answer the question. Edit: 1) Additional supporting material (re: Kylo Ren) from the novel was added to provide a more comprehensive illustration of the two-way 'action and reaction' between Kylo Ren and Leia. 2) Caps usage has been trimmed down. 1) Leia knows that Han is going to attempt to 'reach' their son. This is a fact as this is something she specifically requests of Han before he leaves as she tells him to "bring him home". 2) Those sensitive to the Force have the potential to sense others who are also sensitive to the Force... (or sense the deaths of many like with the destruction of Alderaan, for example). This is a fact re-suggested in the movie when the Supreme Leader and Kylo Ren talk about sensing Rey who is sensitive to the Force and is awakening to it. With these two ideas in mind, my answer is that Force-sensitive Leia sensed the abomination that Kylo Ren - her own force-sensitive son - did, which was to kill his own father. I believe this answer is potentially further supported by two particular instances in the book where: 1a) Kylo Ren reacts to the mention of his mother... “No, it’s not.” Halfway across the walkway now, Han continued to move forward, smiling. “Never too late for the truth. Leave here with me. Come home.” Without the slightest trace of malice or deception, he cast a dagger. “Your mother misses you.”A strange sensation touched the younger man’s cheeks. Something long forgotten. Dampness. Tears.“I’m being torn apart. I want—I want to be free of this pain.” 1b) Kylo Ren reacts to what he's done... Stunned by his own action, Kylo Ren fell to his knees. Following through on the act ought to have made him stronger, a part of him believed. Instead, he found himself weakened. and 2) Leia admits that she knew of their son's potential corruption by and to the Dark side since the beginning... and yet tried to deny it and hide it because 1) she didn't think Han would handle it too well, and 2) she wanted to believe that their son could be kept with the Light and either not turned or capable of redemption. In this, Leia shows denial - YEARS of denial - when in truth, she knew deep down and long ago what really was going on and was likely to happen.Sending Han out to try and save their son reads, to me, like another last-ditch effort where she - once again - is 'naively' hoping for something that will likely not happen the way she wishes to. Though we have no idea as of yet if redemption is in the cards for Ben, killing his own father is a pretty big deal and coupled with the fact that Kylo Ren is shown to emotionally react to the mention of his mother (or just the sense of family)... For Leia, I think that's more than enough of a 'disturbance' in the Force (specifically, her son emotionally reacting towards the mention of her and family and being corrupted/turned enough to the Dark to kill his own father) for her to sense and be aware of. Note: Please excuse the choppy formatting of this answer as I am trying my best to ensure the majority of spoiler-worthy material is kept behind the spoiler tags while still keeping my answer readable. A: The novelization by Alan Dean Foster explicitly indicates Leia felt a Force shudder when Han died, NOT when other people died. On another world far, far away, a woman felt a shudder in the Force that lanced through her like a knife. She slumped into a seat, her head lowering, and started to cry. As to "how", @Renegade Princess answer offers some compelling theories, and i'll add one more of mine: He was killed by her son, a strong Force-user Ben/Kylo Ren. If nothing else, she likely could have sensed the event due to that connection, even if you're unwilling to accept that a Jedi can sense the death of non-Force-sensitive individual, despite that answer's arguments.
{ "pile_set_name": "StackExchange" }
Q: delete that add dynamically through jquery I am working on a project and I already took help in it from stackoverflow but i am stuck once again. The problem is that a user can select number of rows he want to add but if lets us suppose he want to add three but mistakenly he enter four and add four rows and now he want to remove any single row so he could do that below is the code for it $(function() { var spinner = $( "#spinner" ).spinner({ min: 0 }); $( "#ok" ).click(function() { var spiner_val = spinner.spinner( "value" ) ; var html = '<tr><td><input type="text" name="name" />&nbsp;<input type="text" name="name" />&nbsp;<input type="text" name="name" />&nbsp;<select><option value="">abc</option><option value="">abc</option><option value="">abc</option><option value="">abc</option></select><a href=""><img class="img-icons" src="images/delete.jpg" /></a></td></tr>'; for(i = 0; i < spiner_val;i++){ $(html).insertAfter('tr:last'); } }); }); So when user click the image infront of any row that row should be deleted.thanks in advance. here is the demo http://jsfiddle.net/aLZhw/2/ A: Add a class delete to the a element like <a href="" class="delete"><img class="img-icons" src="images/delete.jpg" /></a> then $('#my-table').on('click', '.delete', function(){ $(this).closest('tr').remove(); return false; }) Demo: Fiddle
{ "pile_set_name": "StackExchange" }
Q: Inequality for function of $\arctan(x)$ I want to show that $$f(x) = \frac{1}{\arctan(x)} - \frac{1}{x} $$ is increasing on $(0, \infty)$. I can see this clearly by plotting it, but I'm struggling to write it out rigorously. It obviously suffices to show its derivative is always positive in this range (which is also clear from plotting it). We have $$f'(x) = \frac{(1+x^2)\arctan^2(x) -x^2}{x^2(1+x^2)\arctan^2(x)}$$ so again it suffices to show that $$g(x) \equiv (1+x^2)\arctan^2(x) -x^2 \ge 0 \quad \forall x >0$$ (and, yet again, this is clear from plotting it). I've jumped down the rabbit hole of taking the derivative of $g$ as well (since it is $0$ at $x = 0$ so it would again suffice to show that $g' \ge 0$) and it doesn't yield anything immediately useful for me. Please help if you can A: $${1\over 1+x^2}\ge {1-x^2\over (1+x^2)^2}\quad \forall x >0$$ which is derivative of $${\arctan(x)}\ge {x\over 1+x^2}\quad \forall x >0$$ $${2\arctan(x)\over 1+x^2}\ge {2x\over (1+x^2)^2}\quad \forall x >0$$ which is derivative of $$\arctan^2(x) \ge {x^2\over 1+x^2}\quad \forall x >0$$ $$(1+x^2)\arctan^2(x) -x^2 \ge 0 \quad \forall x >0$$
{ "pile_set_name": "StackExchange" }
Q: Call same function from multiple views I'd like to be able to call a function from different views in django. For example, say I need to generate a random number from within various views, I don't want to have to have the same 'random number' code repeated in each view - I just want to 'call on a function'. I'm greatly simplifying the following code for the sake of keeping this question brief: views.py def viewOne(request): #code for this view, including needing to generate a random number import random myrandomnumber = random.randint(1,21)*5 def viewTwo(request): #code for this view, including needing to generate a random number import random myrandomnumber = random.randint(1,21)*5 As you can see, I'm using the same code in both views to generate a random number. If I wanted to update how I generate a random number, I'd have to update it in both views. This is the sort of thing I want to do: views.py def createRandomNumber(): import random myrandomnumber = random.randint(1,21)*5 def viewOne(request): #code for this view, including needing to generate a random number createRandomNumber() def viewTwo(request): #code for this view, including needing to generate a random number createRandomNumber() Thanks very much for any help you can give me A: Well in-order to this you would need to extract the function such that is would be available to all views that need it. You could for example create a file called utils.py in your django app define the function there and import it into the views.py utils.py import random def createRandomNumber(): return random.randint(1,21)*5 views.py from utils import createRandomNumber def viewOne(request): createRandomNumber() def viewTwo(request): createRandomNumber()
{ "pile_set_name": "StackExchange" }
Q: Reduce code into one string blocks['package'].fadeIn(); blocks['optional'].fadeIn(); blocks['setup1'].fadeIn(); blocks['payment'].fadeIn(); How can I oprimize this code into general behavior, tried something like : blocks['package', 'optional', 'setup1', 'payment'].fadeIn(); A: Libraries like Underscore.js or lodash make this kind of thing easy, but you can also do it easily with a simple loop: var fades = ['package', 'optional', 'setup1', 'payment']; for (var i = 0; i < fades.length; i++) { blocks[fades[i]].fadeIn(); }
{ "pile_set_name": "StackExchange" }
Q: Risk of removing the PIN from Bitlocker Microsoft's implementation of BitLocker for hard drive encryption/protection and integrity supports multiple ways to boot into the system. I will list 3: TPM chip (those that support it) without Pre-Boot PIN, TPM chip with the PIN, and lastly Network unlock (basically no PIN but the second authentication is grabbing a key over the network). In my understanding, there are trade offs with each of these. No PIN = less security but it’s not a hassle to the user to type it in every time. PIN = more security but more hassle. Network unlock = more security and usability but requires management and infrastructure. We are deciding which one to go with at my company. Management wants to remove the PIN because users are complaining that they have to type a PIN and then be presented to the login screen. I have informed management that requiring a pre-boot PIN stops the OS from loading the BitLocker encryption keys into memory before a valid PIN is entered (halts the boot process). If the PIN is removed, they will be vulnerable to side channel attacks. MS recommends the PIN for this reason. Network unlock turned them off because it requires infrastructure. I said that if the hosts are not storing sensitive or confidential data and are backed up, removing the PIN is rather low risk because it requires a more advanced attacker (usually) and it's probably not worth it (yes, generalities are bad). I have two questions. Is risk a good way to approach this situation? Does my reasoning make sense? I.e. No sensitive data, backed up, other controls, etc then OK to remove the PIN Lastly I don't have much to stand on, our company is worried about compliance and encrypting hard drives meets that, even if you remove the PIN. A: Is risk a good way to approach this situation? Yes, a risk based approach is always a good idea. :) Does my reasoning make sense? I.e. No sensitive data, backed up, other controls, etc then OK to remove the PIN Generally, using PINs vs not using PINs depends on your threat model and a few other factors/considerations. Consider the external factors like the location and portability of the specific devices in question, as well as the physical security level of your company premises. Laptops which will leave company premises have a different threat model than stationary desktops. Laptops: once the device leaves company premises, it's basically out of your reach in case something happens to it. If it's stolen, it's gone and the thief can do pretty much anything with it. This is where pre-boot PINs come into play. They would prevent an attacker from even booting the device, severely limiting his attack surface. Desktops: if your office premises are at least somehow secured (video surveillance, night guards, alarm systems, access control etc.) your desktops are much less at risk of being targeted by attackers. An attacker would first have to break into your office to access your clients. In that case, I'd say that pre-boot PINs are not that necessary because of the limited attack vectors. Just make sure to actually secure the desktops to their desks so no attacker can just walk away with some towers in their hands. In short: laptops = higher risk = PIN necessary, desktops = lower risk = PIN not necessary (but advised). All that being said, I think that enforcing your "No sensitive data on non-PIN clients" will be way harder to enforce and impelent than to educate your users and raise security awareness. You already have a bad start, because users are actively complaining about security measures. This indicates that security awareness is not high enough in your company, especially when your users already have management on their side. If your users detest BitLocker PINs that much, chances are high that they will use very insecure PINs in case they are forced to continue using them, e.g. 123456 or 0101010101. Find out why the users are complaining about PIN+Logon password and educate them and management on the benefits of pre-boot PINs on laptops, just make sure to leave the technical side out of the discussion - management and users won't understand your techno-babble. E.g. "If it's stolen, attackers cannot harm the company. And if the company is not harmed, your jobs are not at stake. You can do your part by keeping the company safe/secure", or something along those lines. Since your company is compliance-driven, a clear policy for home office/laptop usage should have pre-boot PINs as a mandatory requirement in them from a risk perspective. If it's part of a policy, compliance will have to enforce it. If your management still won't budge, remember that risk acceptance is also a valid risk treatment method (if it is documented in writing! With a risk owner, e.g. the manager in question, who will take the responsibility once something goes wrong.)
{ "pile_set_name": "StackExchange" }
Q: Updating DataGridView date cell to database mismatch error Vb.net first, I would like to say that thank all of the programmers, people that make this website so efficient! I'm proud to say that 80% of my programming knowledge on VB I gained was because of all of the samples and answers in this webpage. Anyway, so I'm developing a Quality Control application for my company and there's a datagridview in one of my forms. The user can make changes to it and after that he/she has to save the datagrid back to the MS Access database. I tried everything and I can't save the date field into the database. I checked for field formatting and the database table is formatted to "Date/time" here is what i have: Dim sql As String Try For i As Integer = 0 To dataAddemdumView.RowCount - 1 sql = "UPDATE MasterRecordsT SET Fecha = '" & dataAddemdumView.Rows(i).Cells("Fecha").Value & "', Pass = " & dataAddemdumView.Rows(i).Cells("Pass").Value & ", Fail = " & dataAddemdumView.Rows(i).Cells("Fail").Value & ", Employee = " & dataAddemdumView.Rows(i).Cells("Employee").Value & ", Gig = " & dataAddemdumView.Rows(i).Cells("Gig").Value & ", GigNotes = '" & dataAddemdumView.Rows(i).Cells("GigNotes").Value & "', Department = '" & dataAddemdumView.Rows(i).Cells("Department").Value & "' WHERE ID = " & dataAddemdumView.Rows(i).Cells("ID").Value & "" cmd = New OleDbCommand(sql, con) con.Open() da.UpdateCommand = con.CreateCommand() da.UpdateCommand.CommandText = sql da.UpdateCommand.ExecuteNonQuery() con.Close() Next Catch ex As Exception con.Close() 'MessageBox.Show("OPEX Quality encountered a problem, Try to reopen the application to solve issues", "Error 0002", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try thank you so much for your help guys! A: so this would be the final code and it works Dim sql As String Try For i As Integer = 0 To dataAddemdumView.RowCount - 1 If Not dataAddemdumView.Rows(i).Cells("Fecha").Value Is DBNull.Value Then sql = "UPDATE MasterRecordsT SET Fecha = '" & dataAddemdumView.Item("Fecha", i).Value & "', Pass = " & dataAddemdumView.Rows(i).Cells("Pass").Value & ", Fail = " & dataAddemdumView.Rows(i).Cells("Fail").Value & ", Employee = " & dataAddemdumView.Rows(i).Cells("Employee").Value & ", Gig = " & dataAddemdumView.Rows(i).Cells("Gig").Value & ", GigNotes = '" & dataAddemdumView.Rows(i).Cells("GigNotes").Value & "', Department = '" & dataAddemdumView.Rows(i).Cells("Department").Value & "' WHERE ID = " & dataAddemdumView.Rows(i).Cells("ID").Value & "" cmd = New OleDbCommand(sql, con) con.Open() da.UpdateCommand = con.CreateCommand() da.UpdateCommand.CommandText = sql da.UpdateCommand.ExecuteNonQuery() con.Close() End If Next Catch ex As Exception con.Close() MsgBox(ex.Message) 'MessageBox.Show("OPEX Quality encountered a problem, Try to reopen the application to solve issues", "Error 0002", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try
{ "pile_set_name": "StackExchange" }
Q: What should you set as rpcpassword and rpcusername in BitCoin? Every example/tutorial looks the same: rpcpassword=<somehashofsomesort> and rpcusername=rpcuser They always use something like rpcuser, and some hash for the password. Why is it like this? Does it offer any advantage to break out of the shell and have your username and password be something you like? In another place I found this: #rpcuser=alice #rpcpassword=DONT_USE_THIS_YOU_WILL_GET_ROBBED_8ak1gI25KFTvjovL3gAM967mies3E= Does setting your username to alice cause you to no longer be anonymous, and that's why everyone has the same username? Do I even need a username and password? A: I suggest you don't use rpcuser and password if you don't need to. If you don't set them, Bitcoin Core will use a cookie in your .bitcoin directory as a mean to identify you. Besides rpcuser and rpcpassword are deprecated now, you're supposed to use this python script to generate a password and copy the output in your config file like this : rpcauth=[user]:[long random string] But once again, I suggest you don't use it if you don't need it. As for the alice username, it's just a common placeholder name originally used in cryptography, "Alice" and "Bob" are the two parties that try to communicate, Eve is the passive eavedropper that tries to snoop on their private conversation and Mallory is the active attacker that tampers messages or disrupts communication. I think there's no harm using it as a rpcuser name though.
{ "pile_set_name": "StackExchange" }
Q: SVG math calculation in python using svg.path1.1 I have changed the code a little bit and add print d and print i to keep tracking the execution but it doesn't increment after the first iteration the length of path_strings is 29 from svg.path import parse_path, Line, Arc, CubicBezier, QuadraticBezier import numpy as np import pylab as pl from xml.dom import minidom doc = minidom.parse("C:\Users\DELL\Desktop\drawing(1).svg") path_strings = [path.getAttribute('d') for path in doc.getElementsByTagName('path')] doc.unlink() b = len(path_strings) X = [] Y = [] d = 0 while d <= b: path1 = parse_path(path_strings[d]) a = np.arange(0,1.01,0.01) print d d = d+1 for i in a: print i X.append(path1.point(i).real) Y.append(path1.point(i).imag) pl.scatter(X,Y) pl.show() it gives : >>> ================================ RESTART ================================ >>> 0 0.0 Sorry for the bad format of my post I am just a newbie here and thanks for help Carlo A: yep i found out that i am enough stupid to put the parameter <=b which equal to 29 in fact if the length is 29 so the d parameter must go from zero up to 28 and not 29 and this what make the index problem appears thank you everybody for not helping :) my robotic arm is finally working
{ "pile_set_name": "StackExchange" }
Q: After a background color change with Javascript the :hover don't change the color I have a long form with many fields. Some of the fields get their data from separate DIV, where there are other more specific fields. Every field, along with its label, is included into a separate block. To highlight the fields there is a CSS :hover for their class. The CSS :hoveron the fields blocks works smoothly, and also the onmouseover and onmouseout over the many DIV passing data to them, using the following Javascript: function LineOn(whichOne) { document.getElementById(whichOne).style.backgroundColor = '#cf0'; } function LineOff(whichOne) { document.getElementById(whichOne).style.backgroundColor = '#fff'; } But, after the execution of the Javascript, the hover stops to work (i.e. the block remains white), without reporting any console error or message. This happens both with Firefox 36.0.3 and with Chrome 39.0.2171.71, running on a Slackware current release. Is there a sort of hierarchy giving to the background color set with Javascript the priority over the one defined in the <style> section? A: Yes, styles defined directly in the element's style property overrides any value set in CSS, unless that style has !important on it. CSS specificity http://www.w3.org/wiki/CSS/Training/Priority_level_of_selector The priority level of the selector is decided in Point of combination of selectors. style attribute = a number of ID attributes in the selector = b number of other attributes and pseudo-classes in the selector = c number of element names and pseudo-elements in the selector = d That's one good reason not to set styles attributes; set a CSS class instead yet.
{ "pile_set_name": "StackExchange" }
Q: Mobile phone CSS I'd like to make a css for mobile as my site looks really deformed on mobile, but i have no idea how to do a separate mobile version from the desktop verion. I've seen that phones have an option to change between the two so i was just wondering how it's done and how i could do it and if you guys have any tips regarind making a css for mobile, like the dos and don'ts that'd be great. Also would i need to make one for different models etc or do i make 1 that will be for mobile devices? Thanks in advance. A: You can use media queries like in this example: @media only screen and (max-width: 600px) { body { background-color: lightblue; } } More infos here.
{ "pile_set_name": "StackExchange" }
Q: Find visually similar images for a given image file (on Windows) I want a software for Windows to find visually similar images (pictures) on my hard disk. My need is it must find a given image is visually similar. That is, take a sample image as input and search throughout the computer and find any images visually similar to it. I have tried many visually similarity image finders, but they all are only cross-checking each and every file against each other to find all possible combinations of similar images. None offers it for a single image specified, as I need it. See Find visually similar images to a given image for Linux software. A: Just found this today on my search for something similar. (I've been looking for this for years usually once a year. happened to be today) https://sourceforge.net/projects/imgseek/ imgSeek is a photo collection manager and viewer with content-based search and many other features. The query is expressed either as a rough sketch painted by the user or as another image you supply (or an image in your collection). A: The best Windows tool I can find for this is Visipics http://www.visipics.info/index.php?title=Main_Page It basically uses ImageMagick to fingerprint images, with a slider to pick out the similarity values. However, it seems to only do bulk comparisons (so you can't specify one file to look for, only whole folders). A: Try search by image browser-based OS-independent tool (Windows, Linux, Mac etc.), which I developed. The limitation is the browser type (works best for Chrome and Firefox, some browsers do not support folder selection or too slow parsing the file directory), the file read speed, type of images (browser-readable only), and available memory. But if you have a good PC, I would say it is possible to scan 50000-100000 images without a problem. In case of privacy concerns, it is possible to save and host the tool page locally (e.g. on http://localhost:8000/ with a local Python server). This way no information will pass to the Internet at all.
{ "pile_set_name": "StackExchange" }
Q: \RequirePackage within \if\else\fi Why does the package iftex have to be loaded outside of a \if...\else\fi structure? (The same goes for packages ifpdf, ifluatex, ifxetex.) Consider: \documentclass{myclass}\begin{document}\end{document} This works: i.e., when \RequirePackage{iftex} is outside of \ifodt\else\fi \NeedsTeXFormat{LaTeX2e}[1996/06/01] \ProvidesClass{myclass}[2013/12/15 v0.1 My Class] \LoadClass{article} \newif\ifodt\odttrue \RequirePackage{iftex} \ifodt \RequirePackage[utf8]{inputenc} \RequirePackage[T1] {fontenc} \else \ifLuaTeX\RequirePackage{fontspec}\fi \ifXeTeX \RequirePackage{fontspec}\fi \ifPDFTeX \RequirePackage[utf8]{inputenc} \RequirePackage[T1] {fontenc}\fi \fi But not this: i.e., when\RequirePackage{iftex} is within \ifodt\else\fi \NeedsTeXFormat{LaTeX2e}[1996/06/01] \ProvidesClass{myclass}[2013/12/15 v0.1 My Class] \LoadClass{article} \newif\ifodt\odttrue \ifodt \RequirePackage[utf8]{inputenc} \RequirePackage[T1] {fontenc} \else \RequirePackage{iftex} \ifLuaTeX\RequirePackage{fontspec}\fi \ifXeTeX \RequirePackage{fontspec}\fi \ifPDFTeX \RequirePackage[utf8]{inputenc} \RequirePackage[T1] {fontenc}\fi \fi Error: ! Undefined control sequence. l.12 \ifXeTeX \RequirePackage{fontspec}\fi ? A: In your \else branch you have \else \RequirePackage{iftex} \ifLuaTeX\RequirePackage{fontspec}\fi \ifXeTeX \RequirePackage{fontspec}\fi Now \ifXeTeX is an undefined command which is OK as this is being skipped but the \fi is \fi so terminates the outer \ifodt and things go wrong. Never define conditionals within a TeX primitive \if.. as this always happens:-) A: You have to delay the conditionals when (and if) the iftex package has been loaded. \NeedsTeXFormat{LaTeX2e}[1996/06/01] \ProvidesClass{myclass}[2013/12/15 v0.1 My Class] \newif\ifodt \DeclareOption{odt}{\odttrue} \ProcessOptions\relax \LoadClass{article} \ifodt \RequirePackage[utf8]{inputenc} \RequirePackage[T1] {fontenc} \expandafter\@gobble \else \RequirePackage{iftex} \expandafter\@firstofone \fi {\ifLuaTeX \RequirePackage{fontspec} \fi \ifXeTeX \RequirePackage{fontspec} \fi \ifPDFTeX \RequirePackage[utf8]{inputenc} \RequirePackage[T1]{fontenc} \fi} When \ifodt is true, the part in braces is gobbled, while if it is false, it's evaluated; since iftex has already been loaded, the conditionals will be defined and so matched with the corresponding \fi. There should be a better control, though, because when \documentclass[odt]{myclass} is found and LuaLaTeX or XeLaTeX are used, the packages inputenc and fontenc would be loaded, which is discouraged.
{ "pile_set_name": "StackExchange" }
Q: How can I output to a GUI, pause, then output something else (for instance using SwingWorker)? I'm making a simple text-based turn-based combat game in Java (as a learning exercise, so I'm trying to understand everything I do) and I want to simulate the opponent taking a turn. This essentially involves printing out a message (e.g. "Enemy's turn"), processing the enemy's turn, pausing (with Thread.sleep), and then printing out another message ("e.g. "Your turn"). My GUI is a JApplet class with Swing elements, though this is because it was simple to make and understand rather than because I have any attachment to using Swing. I have no experience in multithreading, but have read that SwingWorker is useful in this sort of situation (updating a Swing GUI while a lengthy background process is running). Here is a version with no actual game code and all included in the same class for simplicity: public class SimpleGame extends JApplet implements ActionListener { private Game game; private String inputCommand; private JTextArea textOutput; private JTextField inputField; public void init() { textOutput = new JTextArea(); DefaultCaret caret = (DefaultCaret) textOutput.getCaret(); caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE); textOutput.setEditable(false); Container window = getContentPane(); window.setLayout(new BorderLayout()); window.add(textOutput, BorderLayout.CENTER); JButton submitButton = new JButton("Submit"); submitButton.addActionListener(this); inputField = new JTextField(20); inputField.addActionListener(this); JPanel inputPanel = new JPanel(); inputPanel.add(inputField); inputPanel.add(submitButton); window.add(inputPanel, BorderLayout.SOUTH); inputField.requestFocusInWindow(); game = new Game(); } public class GuiUpdater extends SwingWorker<Boolean, String> { private String command; public GuiUpdater(String inputCommand) { super(); command = inputCommand; } public void publish(String chunk) { super.publish(chunk); } protected Boolean doInBackground() throws Exception { Output.setWorker(this); boolean successfulCommand = game.performCommand(command); return successfulCommand; } protected void process(List<String> chunks) { for (String chunk : chunks) { textOutput.append(chunk); } } } public void actionPerformed(ActionEvent event) { if (game.isItYourTurn()) { inputCommand = inputField.getText(); if (inputCommand.length() != 0) { GuiUpdater worker = new GuiUpdater(inputCommand); worker.execute(); boolean successfulCommand; try { successfulCommand = worker.get(); } catch (InterruptedException | ExecutionException e) { successfulCommand = false; } if (!successfulCommand) { textOutput.append("Invalid command.\n"); } inputField.setText(""); } } else { textOutput.append("\nWait for your turn!\n"); } } private static class Output { private static GuiUpdater worker; static void setWorker(GuiUpdater newWorker) { worker = newWorker; } static void update(String updateText) { worker.publish(updateText); } } private class Game { private boolean yourTurn; public Game() { yourTurn = true; } public boolean isItYourTurn() { return yourTurn; } public boolean performCommand(String inputString) throws InterruptedException { yourTurn = false; // perform player action Output.update("\nEnemy turn"); Thread.sleep(1000); // perform enemy action Output.update("\nYour turn"); yourTurn = true; return true; } } } Unfortunately instead of outputting one line, waiting a second, then outputting the second line, all lines are outputted to the Swing GUI after all sleeps have finished. If I replace my Output.update("text") with System.out.println("text") then the timing works as expected, but obviously I don't want to just rely on the console output for my game. If anyone has either an explanation as to what I'm doing wrong or an alternative method of pausing between outputs it would be greatly appreciated. Cheers! A: Your call to worker.get() is blocking the swing-applet thread until the worker completes. You need to move the handling of the result into the SwingWorker done() method, which won't be executed until the doInBackground() method has completed. That part of the code should look like this: public class GuiUpdater extends SwingWorker<Boolean, String> { private String command; public GuiUpdater(String inputCommand) { super(); command = inputCommand; } public void publish(String chunk) { super.publish(chunk); } @Override protected Boolean doInBackground() throws Exception { Output.setWorker(this); boolean successfulCommand = game.performCommand(command); return successfulCommand; } @Override protected void process(List<String> chunks) { for (String chunk : chunks) { textOutput.append(chunk); } } @Override protected void done() { boolean successfulCommand; try { successfulCommand = get(); } catch (InterruptedException | ExecutionException e) { successfulCommand = false; } if (!successfulCommand) { textOutput.append("Invalid command.\n"); } inputField.setText(""); } } @Override public void actionPerformed(ActionEvent event) { if (game.isItYourTurn()) { inputCommand = inputField.getText(); if (inputCommand.length() != 0) { GuiUpdater worker = new GuiUpdater(inputCommand); worker.execute(); } } else { textOutput.append("\nWait for your turn!\n"); } }
{ "pile_set_name": "StackExchange" }
Q: Configure Hibernate C3P0 Connection Pooling I'm stumbled upon a problem while developing a Web Application based on Struts2 with Spring and Hibernate. When I refresh the site a few times, for example 2-4 times, Hibernate is showing up an exception about Too many connections. I've tried to implement C3P0 Connection pool and have some problems with it The hibernate.cfg.xml configuration: <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/axelle</property> <property name="hibernate.connection.username">axelle</property> <property name="hibernate.connection.password">dbpassword</property> <property name="hibernate.current_session_context_class">thread</property> <property name="hibernate.c3p0.min_size">5</property> <property name="hibernate.c3p0.max_size">20</property> <property name="hibernate.c3p0.timeout">300</property> <property name="hibernate.c3p0.max_statements">50</property> <property name="hibernate.c3p0.idle_test_period">3000</property> applicationContext.xml <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" p:location="classpath:jdbc.properties"/> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}" p:connectionProperties="${jdbc.connectionProperties}"/> <!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation"> <value>classpath:hibernate.cfg.xml</value> </property> </bean> <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory"> <ref local="sessionFactory"/> </property> </bean> The log output is: org.hibernate.exception.JDBCConnectionException: Cannot open connection and: Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Data source rejected establishment of connection, message from server: "Too many connections" And this is how PROCESSLIST MySQL window looks: http://img844.imageshack.us/img844/3959/be69273cc2.png I've set max_size of connections to 20, but it seems like it doesn't read the C3P0 configuration from file, cause from the screen we can see that number of connections is higher than 20, or maybe I'm doing something wrong, but where? I really need some help guys, I'll appreciate this, and thanks in advance. A: Mention these property in your hibernate.cfg.xml file <property name="hibernate.c3p0.acquire_increment">1</property> <property name="hibernate.c3p0.idle_test_period">100</property> <property name="hibernate.c3p0.max_size">10</property> <property name="hibernate.c3p0.max_statements">10</property> <property name="hibernate.c3p0.min_size">10</property> <property name="hibernate.c3p0.timeout">100</property> Refer this link for better understanding: Configuration Properties
{ "pile_set_name": "StackExchange" }
Q: DocuSign For Salesforce All Contact Roles When defining a custom opportunity button, what parameters can be used that would load the full set of contact roles associated with the opportunity as envelope recipients when creating an envelope? Example. If an opportunity had 10 contact roles, then all 10 (contacts) contact roles would list as recipients. If it had 5 contact roles, then all 5 would load as recipients, etc. A: Add a call to CRL to include all contacts in the opportunity: LoadDefaultContacts. It might look something like this: CRL=’LoadDefaultContacts~1’; The problem is although all Contacts in the Opportunity will be pulled into the envelope, there is no guarantee that the contacts will fall in the signing order you might expect. You may need to add CCRM and CCTM to sort the order of the contacts.
{ "pile_set_name": "StackExchange" }
Q: How to estimate the hardness of SIS instances? The Short Integer Solution (SIS) problem is to find, given a matrix $A \in \mathbb{F}_q^{n \times m}$ with uniformly random coefficients, a vector $\mathbf{x} \in \mathbb{Z}^m \backslash \{\mathbf{0}\}$ such that $A\mathbf{x} = \mathbf{0} \mod q$ and $\Vert \mathbf{x} \Vert_2 < \beta$. This problem is at least as hard as the Shortest Independent Vectors Problem (SIVP) with approximation factor $\tilde{O}(\beta\sqrt{n})$ in $n$-dimensional lattices. Several proposed cryptosystems rely on SIS, most notable Ajtai's function in the original paper that defined the problem (link), the SWIFFT hash function (link), and several signature schemes (link) (link) (link). However, I am confused about estimating the security offered by these cryptosystems in terms of the computational cost of a successful attack. Very few sources actually present a hardness estimate and those that do consider the appropriate root Hermite factor $\delta$ rather than a count of arithmetic operations. For instance, the chapter by Micciancio and Regev (link) presents the following argument: There is an optimal number of columns of $A$ to take into account when attacking the SIS problem using lattice-based algorithms (presumably BKZ 2.0). Use too few columns and short lattice points might be too difficult to find (if they exist at all); use too many and the lattice will be too large. This minimum is found for $m = \sqrt{n \log q \, / \log \delta}$; at this point the average length of lattice points that can be computed in a "reasonable amount of time" is $2^{2\sqrt{n \log q \log \delta}}$, where $\delta$ is no less than $1.01$. So by requiring that $\beta < 2^{2\sqrt{n \log q \log \delta}}$, one guarantees that the SIS instance cannot be solved in a reasonable amount of time. A similar treatment of the hardness of SIS instances is given by Section 3.2 of Lyubashevsky's 2012 signature scheme (link), which uses $\delta = 1.007$ for setting parameters. Micciancio and Peikert's 2011 signature scheme (link) mentions that setting $\delta \leq 1.007$ corresponds to $2^{46}$ core-years of lattice-redution, which is about $2^{100}$ cycles on a 1.0 GigaHerz CPU. I have several questions regarding this. What makes it impossible or difficult to translate the parameters $(m,n,q,\beta)$ into an attack runtime estimate, and what is the significance of the root Hermite factor $\delta$ in this context? Given that $\delta$ is a useful tool, how does one translate between $\delta$ and attack complexity (in number of bits of security)? Given a target short vector length and lattice parameters, how to estimate the time before BKZ 2.0 finds a lattice point of this length? (Or, if this is not a sensible question, why doesn't this runtime matter?) A: The value $\delta$ characterizes, how short a vector you can expect to find using an algorithm (typically used in the context of lattice reduction). In particular, for a vector $\mathbf{v} \in \Lambda$ (where $\Lambda$ is a lattice), the associated $\delta$ (often also denoted by $\delta_0$) is defined to be such that $\| \mathbf{v} \| = \delta^n \det(\Lambda)^{1/n}$. This was introduced in GN08 in the context for lattice reduction, because it was observed that the $\delta$ for output vectors returned by lattice reduction converges (for growing $n$) to a constant for every type and parametrization of reduction. Generally, reduction algorithms are parameterized and allow for a trade-off between output quality (i.e. size of $\delta$) and running time. The exact trade-off is still a subject to research, especially as reduction algorithms continue to improve, but a good summary of the state-of-the-art is given in APS15 (Section 3). Roughly speaking, translating a SIS instance to a $\delta$ required to break it, is relatively easy, but translating the $\delta$ to a running time is not as straight-forward. The reason is that the behavior of lattice reduction, the most efficient approximation algorithms to date, is not very well understood and the community has not converged on a model yet. One issue with lattice reduction is that it uses an exact SVP solver (in lower dimension). In order to instantiate these solvers there are different algorithms, some behaving better in practice and others being asymptotically more efficient. This makes it hard to analyze exactly, how long it will take to obtain a short vector of quality $\delta$.
{ "pile_set_name": "StackExchange" }
Q: How is Hibernate Database Independent? Have been asked recently in one of my interview. Can some one explain in detail why is Hibernate database idependent ? Regards, Yrus A: Database independency means writing no code dependent to the database vendor. Hibernate, or in general JPA, prevents you from writing code according to the Oracle specifications or MySQL specifications. You use JPA classes and interfaces and make JPA implementation(like Hibernate or Toplink) do the rest.
{ "pile_set_name": "StackExchange" }
Q: Constant Pressure Cylinder The solution to this states that "pressure of the gas is constant." What implies this? Is it because the piston was elevated then stopped? If the gas pushed the Piston all the way up to where it stopped moving (and kept pushing) would Pressure be constant then? Thank You. A: For the pressure of the gas to be considered constant, the expansion would have to be carried out quasistatically that is, very slowly, so that the pressure of the gas was only differentially greater than the external pressure at each stage of the expansion, or $$P_{gas}=P_{ext}+dP$$ In this way the pressure of the gas can be considered in equilibrium with the external pressure throughout the expansion. Hope this helps.
{ "pile_set_name": "StackExchange" }
Q: Computation of 2-norm using Eigenvalues vs. Matlab For example, consider the matrix $B$: \begin{bmatrix} 5 & -2\\ -2 & 2 \end{bmatrix} computation of the 2-norm of $B$ using its eigenvalues (which is $6$ and $1$) yields $\sqrt{6}$ (since 6 is the largest eigenvalue of $B$). But Matlab norm(B,2) yields 6.0000 This is obviously the answer without the square root. What am I missing here? Is Matlab not square rooting the answer? A: I hope it can help you: $$\bbox[yellow,5px] {\lVert B \rVert_{2}=\sqrt{\text {maximum eigenvalue of $B^TB$} }}$$ $$B=\begin{bmatrix} 5 & -2\\ -2 & 2 \end{bmatrix}$$ $$B^TB=\begin{bmatrix} 29 & -14\\ -14 & 8 \end{bmatrix}$$ \begin{aligned}|[B^TB]-\lambda I|&=\left|{\begin{bmatrix}29&-14\\-14&8\end{bmatrix}}-\lambda {\begin{bmatrix}1&0\\0&1\end{bmatrix}}\right|={\begin{vmatrix}29-\lambda &-14\\-14&8-\lambda \end{vmatrix}},\\&=\lambda ^{2}-37\lambda +36.\end{aligned} $$\lambda=\{1,36\}$$ $$\text{max $\lambda$}=36$$ $\lVert B \rVert_{2}=\sqrt{\text {maximum eigenvalue of $B^TB$} }=\sqrt{36}=6$
{ "pile_set_name": "StackExchange" }
Q: Multiple Solution Layout for ASP.NET Web Portal? At work, we've developed a custom ASP.NET Web Portal (That's very similar to iGoogle). We have "Apps" (self-contained, large web forms) and "Modules" (similar to Google Gadgets). Currently, we use a single-solution model. Right now, we have: 3 core projects 60 application projects 80 module projects To reduce copy and pasting between projects, we're going to factor out common functionality (Data Access, Business Logic) into separate projects. I'd also like to introduce Unit Tests, which is going to increase the number of projects even more. We've already reached the point where Visual Studio is choking on the number of projects. We generally only load the 3 core projects and then whatever app's/module's project we're working on. Would a different solution structure help us out? Our number of projects is only going to increase. In general, an app or module only references the 3 core projects. Soon, apps/modules may start referencing the Data Access/Business Logic projects. But in general, apps and modules do not make references between themselves. So to recap, what is the best practice for solution structure when there are MANY projects that use a small number of core projects? A: We have developed similar ASP.NET web portals based on strong modular principles. Tax we pay is lots of Visual Studio projects. There is a single master solution with all modules, web-sites, unit-tests and so on but this solution is usually infeasible to work with on day-by-day basis on computers with small amount of RAM (<= 4 GB). We have common infrastructure code (~ 10 projects) and business module projects. A single business module is composed of all projects dealing with some aspect of business requirements, e.g. Orders, Customer management, Distribution... The business module typically has: ASP.NET web application project (which becomes a sub-web of the Shell module web-site), domain model assembly (class library with no dependencies) + interface assembly, OR/M adapter for domain model (we use Entity Framework and NHibernate), front-end assembly with presenters, controllers, view models, ..., back-end assembly with module business services and DTOs + interface assembly, unit test assemblies, other assemblies (like Silverlight components, MSQM DTOs, etc.). We use SLNTools Filter (http://slntools.codeplex.com/) to filter out single business module VS solutions from the master solution. So we have solutions OrdersModule.sln, CustomersModule.sln etc. Each such solution has common infrastructure projects (~10) and the module projects (~10-15). SLNTools Filter automatically includes all dependent projects so it's very easy to create a new filtered solution.
{ "pile_set_name": "StackExchange" }
Q: How to disable HTTP requests on Heroku and/or auto-redirect to HTTPS? I'm currently deploying a Scala Play 2.7.x application to Heroku intending only HTTPS access but the HTTP access is still available and then in this case, the authentication doesn't work. How can I disable HTTP completely for a Scala Play application deployed in Heroku? A: Heroku doesn't handle redirection for you: Redirects need to be performed at the application level as the Heroku router does not provide this functionality. You should code the redirect logic into your application. It looks like this is relatively straightforward with Play Framework version 2.6 or later: play.filters.enabled += play.filters.https.RedirectHttpsFilter If necessary, you can override this setting in your development environment by passing -Dplay.filters.enabled=<whatever> locally, or provide an alternate configuration file with -Dconfig.file.
{ "pile_set_name": "StackExchange" }