id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_2700
|
I've seen that ant-style file pattern is only one pattern, not a list.
Specifically I want my rule to match **/*.wsdl and **/*.WSDL and eventually files with other extensions.
Is there a better way to do this than replicating the rule?
thanks.
| |
doc_2701
|
I'm not sure what Intent to put in my onActivityResult():
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
String name = data.getExtras().getString("name");
Toast.makeText(this, name, Toast.LENGTH_SHORT).show();
}
}
Here is my first Activity:
public class ToDoActivity extends Activity {
private ArrayList<String> todoItems;
private ArrayAdapter<String> todoAdapter; // declare array adapter which will translate the piece of data to teh view
private ListView lvItems; // attach to list view
private EditText etNewItem;
private final int REQUEST_CODE = 20;
//private Intent i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to_do);
etNewItem = (EditText) findViewById(R.id.etNewItem);
lvItems = (ListView) findViewById(R.id.lvItems); // now we have access to ListView
//populateArrayItems(); // call function
readItems(); // read items from file
todoAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItems); //create adapter
lvItems.setAdapter(todoAdapter); // populate listview using the adapter
//todoAdapter.add("item 4");
setupListViewListener();
setupEditItemListener();
onActivityResult(REQUEST_CODE, RESULT_OK, /** Intent variable **/);
}
private void launchEditItem(String item) {
Intent i = new Intent(this, EditItemActivity.class);
i.putExtra("itemOnList", item); // list item into edit text
//startActivityForResult(i, REQUEST_CODE);
startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
String text = (String) lvItems.getItemAtPosition(pos);
launchEditItem(text);
}
});
}
private void setupListViewListener() {
lvItems.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapter, View item, int pos, long id) {
todoItems.remove(pos);
todoAdapter.notifyDataSetChanged(); // has adapter look back at the array list and refresh it's data and repopulate the view
writeItems();
return true;
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.to_do, menu);
return true;
}
public void onAddedItem(View v) {
String itemText = etNewItem.getText().toString();
todoAdapter.add(itemText); // add to adapter
etNewItem.setText(""); //clear edit text
writeItems(); //each time to add item, you want to write to file to memorize
}
private void readItems() {
File filesDir = getFilesDir(); //return path where files can be created for android
File todoFile = new File(filesDir, "todo.txt");
try {
todoItems = new ArrayList<String>(FileUtils.readLines(todoFile)); //populate with read
}catch (IOException e) { // if files doesn't exist
todoItems = new ArrayList<String>();
}
}
private void writeItems() {
File filesDir = getFilesDir(); //return path where files can be created for android
File todoFile = new File(filesDir, "todo.txt");
try {
FileUtils.writeLines(todoFile, todoItems); // pass todoItems to todoFile
} catch (IOException e) {
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
String name = data.getExtras().getString("name");
Toast.makeText(this, name, Toast.LENGTH_SHORT).show();
}
}
}
I thought about using the Intent from the second activity but I'm not sure how to do so.
Here is my second Activity.
public class EditItemActivity extends Activity {
private EditText etEditItem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_item);
Intent i = getIntent();
String ItemToEdit = i.getStringExtra("itemOnList");
etEditItem = (EditText)findViewById(R.id.etEditItem);
etEditItem.setText(ItemToEdit);
onSubmit(etEditItem);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.edit_item, menu);
return true;
}
public void DoneEdit(View v) {
this.finish();
}
public void onSubmit(View v) {
EditText etName = (EditText) findViewById(R.id.etEditItem);
Intent data = new Intent();
data.putExtra("EditedItem", etName.getText().toString());
setResult(RESULT_OK, data);
finish();
}
}
A: To get result form an activity (child) you do as follow :
In the parent activity
startActivityForResult(myIntent, 1);
global vars of your parent activity
boolean backFromChild = false;
String aString;
then still in the parent activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
// code for result
aString = getIntent().getExtras().getString("aString");
backFromChild = true;
}
if (resultCode == RESULT_CANCELED) {
// Write your code on no result return
}
}
}
in your child you do somewhere something like that
Intent returnIntent = new Intent();
//example of sending back a string to the parent.
returnIntent.putExtra("aString", aString);
setResult(RESULT_OK, returnIntent);
finish();
The thing is that onResume of your parent activity will be called when returning from your child. In there you have to perform the update, in your case it is to update the information of the edited text :
@Override
public void onResume(){
super.onResume();
if (backFromChild){
backFromChild = false;
//do something with aString here
Toast.makeText(this, aString, Toast.LENGTH_SHORT).show();
}
}
Basically, in the onActivityResult I get the info back from the intent of the child. Then in onResume I use this info.
A: For your concern you can utilize SharedPreferences
For ex: Put data in SP in second activity like this
SharedPreferences spppp = getSharedPreferences("tab", 0);
SharedPreferences.Editor editors = spppp.edit();
editors.putString("for", "0");
editors.commit();
and fetch data for list view in first activity like this
SharedPreferences spppp = getSharedPreferences("tab", 0);
String your_list_view_value = spppp.getString("for", "");
| |
doc_2702
|
When i install with apk on device it scaled not right
Its quite hard to understand the reason
| |
doc_2703
|
<html>
<?php
// connect to the database
include('connect-db.php');
$result = mysql_query("SELECT * FROM log WHERE type='c' ") ;
echo "<div style='height:auto;'><table border='0' cellpadding='10' class='table table-striped table-bordered'>";
echo "<tr> <th>ID</th> <th>Date</th> <th>Type</th> <th>Batch name</th> <th>No.of Pages</th> <th>User</th><th>file</th><th>Status</th><th></th><th></th></tr>";
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array( $result )) {
$id=$row['batch_file'];
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['assdate'] . '</td>';
echo '<td>' . $row['type'] . '</td>';
echo '<td>'.substr($row['batch_file'], 0, -4).'</td>';
echo '<td>' . $row['no_pages'] . '</td>';
echo '<td>' . $row['assign'] . '</td>';
echo '<td><a href="copy_test_uploads/'.$row['batch_file'].'"target="_blank"><img src="pdf.png" style=width:35px;></td>';
echo '<td>' . $row['status'] . '</td>';
echo '<td><a href="controllogviewedit.php?id=' . $row['id'] . '">Edit</a></td>';
echo '<td><a href="controllogviewdelete.php?id=' . $row['id'] . '">Delete</a></td>';
echo "</tr>";
}
// close table>
echo "</table></div>";
?>
</html>
| |
doc_2704
|
Any advice will be highly appreciated!
A: There is no variable for the refresh position.
The only way I found to affect it is by creating a CSS rule, in src/app/app.scss for example:
ion-refresher {
top: 100px !important;
}
!important is required because Ionic will otherwise override it on the element itself during pulling.
A: I've managed to solve this is a better way. Since I'm using a Component for shrinkable header, I'm already invoking the ion-content there. Hence when I'm doing a Dom Re-render, each time while scrolling, I'm also changing the position of my ion-content as follows:
this.renderer.setStyle(this.scrollArea._elementRef.nativeElement, 'top', (this.newHeaderHeight - 74) + 'px');
Where scrollArea is my ion-content gotten by ID.
This is the tutorial I've used, plus significantly improved his code for best performance (Facebook style): https://www.joshmorony.com/creating-a-shrinking-header-for-segments-in-ionic/
| |
doc_2705
|
public class LoginRequest extends StringRequest {
private static final String LOGIN_REQUEST_URL="http://192.168.0.17/WebD/HASSAPP/login.php";
private Map<String, String> params;
public LoginRequest(String username,String password , Response.Listener<String> listener) {
super(Method.POST, LOGIN_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("username",username);
params.put("password",password);
}
@Override
public Map<String,String> getParams() {
return params;
}
}
public class Login extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);//Edit to change title text
setSupportActionBar(toolbar);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final Button bLogin = (Button) findViewById(R.id.bLogin);
bLogin.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String businessname = jsonResponse.getString("businessname");
String username = jsonResponse.getString("username");
Intent intent = new Intent(Login.this, MainActivity.class);
intent.putExtra("businessname", businessname);
intent.putExtra("username", username);
Login.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(Login.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginrequest = new LoginRequest(username,password,responseListener);
RequestQueue queue = Volley.newRequestQueue(Login.this);
queue.add(loginrequest);
}
});
}
I cannot understand how me sending via Post on my register is working fine but On Log-in it's non responsive , Log-in button does nothing , not even send me to mainactivity like the intent's purpose,
Kind Regards,
Andrew
A: This overriden method should be protected. You have it as public.
@Override
protected Map<String,String> getParams() {
return params;
}
Also, for debugging purposes, you might want to override the error listener as well.
| |
doc_2706
|
A: Instead of FacePointsInColorSpace, use FacePointsInInfraredSpace.
The color space has a resolution of 1920x1080, while the infrared space has a resolution of 512x424 pixels.
Green screen implementation is most probably using the depth space to extract the proper pixels.
| |
doc_2707
|
I want to write a regex which matches a character if its a non word, non digit and non star (*) character. So, the characters [0-9][a-z][A-Z] * should not match and the others should.
I tried writing [\W[^*]] but it doesn't seem to work.
A: The simplest regular expression that matches a single character, that is not one of those you described, independent of any particular regular-expression extensions, would be:
[^0-9a-zA-Z *]
A: [^\w\*]
Simple enough.
A: Try this instead:
[^\w\*]
A: Please try the following regex:
[\W_]
| |
doc_2708
|
<div className="wrapper">
<div className="box box1" ref="04"/>
<div className="box box1" ref="03"/>
<div className="box box1" ref="02"/>
</div>
In reality there are 25 nested divs I just listed 3. Question is how can I loop through these elements so I can change the className property for all of them?
A: You could do something like the following:
const Example = () => {
const newArr = [...Array(25)];
return (
<div>
{
newArr.map((i, index) => {
return (
<div key={index} className={`box${index}`}>{index}</div>
)
})
}
</div>
);
}
ReactDOM.render(<Example />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
A: Use JSX
<div className="wrapper">
{
[...Array(25)].map((un, index) => (
<div key={index} className={yourClassName} ref={yourRef} />
)
)
}
</div>
| |
doc_2709
|
setSupportActionBar().setElevation(3.0f);
I have the following layout
CordinatorLayout
--LinearLayout
----AppBarLayout
-----------Toolbar
----/AppBarLayout
----FrameLayout
-----------ListView
----/FrameLayout
----BottomNavigationView
--/LinearLayout
/CordinatorLayout
what are the other possibilities the shadow isn't drawn
Edit,
---------------------------------------------------------------------------------------------------------
older devices like Galaxy s3 running Android 4.4.2 still doesn't show any shadow, even with hardware acceleration enabled
A: So the issue wasn't related to toolbar elevation, view clipping or incorrect layouts, the manifest entry for this particular activity had hardware acceleration turned off.
<activity
..
..
..
android:hardwareAccelerated="false"/>
changing this to true fixed it
| |
doc_2710
|
const sortDropDown = <div className={classes.customselect}>
<select
className={classes.sortSelector}
id="lang"
onChange={onChangeSort}
// defaultValue={8}
value={sortValue}
>
<option className={classes.selectOption} value={''}>{sortValue}</option>
{availableSortMethods.map((method,index)=>
<option className={classes.selectOption} value={[method.text,method.attribute,method.sortDirection]}>{method.text}</option>
)}
</select>
</div>
The options list is fetched from an array.I need to customize the options list box to add a border-radius as follows
How can I do this with CSS to change border-radius values of the dropdown options list not the button.Please help
| |
doc_2711
|
I've two classes, the first is readFromFile and the second class is newClass
readFromFile.java -
*
*This reads a text file
*Parses the lines of text into seperate strings
*The values of these strings are stored in a String [ ] called dArray
*For testing I've printed all values out and it works
newClass.java
*
*This class is intended to copy the value of the string [ ] dArray into a new string and from there use the values ( for simplicity all I've included in the newClass is the code relating to copying the array)
*What I'm doing wrong is that I'm returning dArray but its returning an array with nothing stored in it, so I either need a way to call main method from readFromFile.class / help creating a method in readFromFile that would do the same which I call from main
please help
import java.util.Scanner;
import java.io.*;
public class readFromFile
{
static String[] dArray = new String [30];
public static void main (String[] args) throws IOException
{
String part;
Scanner fileScan, partScan;
int i = 0;
int x = 0;
fileScan = new Scanner (new File("C:\\stuff.txt"));
// Read and process each line of the file
while (fileScan.hasNext())
{
part = fileScan.nextLine();
partScan = new Scanner (part);
partScan.useDelimiter(":");
while ( partScan.hasNext()){
dArray[i] = partScan.next();
i++;
}
}
for (x = 0;x<i;x++)
{ System.out.println(dArray[x]);
}
}
public String[] getArray()
{
return dArray;
}}
newClass.java
public class newClass {
readFromFile results = new readFromFile();// creating object from class readFromFile
public void copyArray() {
String[] dArray = results.getArray(); // Trying to return the values of String [] dArray from rr classs
//Method getArray in rr class is
// public String[] getArray()
// { return dArray; }
String[] arrayCopy = new String[dArray.length];
System.arraycopy(dArray, 0, arrayCopy, 0, dArray.length);
for (int i = 0; i < arrayCopy.length; i++)
System.out.println(arrayCopy[i]);
}
public static void main(String[] args) {
newClass.copyArray();
}
}
A: Your results generation is in readFromFile.main(), but you're expecting to call it in your readFromFile(). You need to make a constructor for readFromFile, and call that in your main method, as well.
A: The problem is that both classes have a main method. Only the class that you intend to run should have a main method, the other classes need only constructors. Assuming you want to run a unshown class it would be written like this.
public class ThirdClass{
public static void main(String[] args) {
readFromFile reader = new ReadFromFile();
newClass copy = new newClass();
reader.readFromFile();
String[] strings = reader.getArray();
copy.copyArray(strings)
}
For this to work you need to put all of the code in the main of readFromFile in a method called "readFromFile". and you need a method in newClass that accepts a string array as an argument. Or a constructor that accepts a string array.
Make sure that neither of them have main methods or it won't work.
A: *
*Remove the static keyword before your dArray variable
*Change public static void main(String[] args) throws IOException in your first class to public readFromFile() throws IOException. Keep the code inside it the same.
*Change the line newClass.copyArray(); in your second class to (new newClass()).copyArray();
*Move the line in your second class readFromFile results = new readFromFile(); into the public void copyArray() method.
*Change public void copyArray() in your second class to public void copyArray() throws IOException
*Put a try..catch block around your code in the second class's main method. i.e. change (new newClass()).copyArray(); to something like try { (new newClass()).copyArray(); } catch (IOException e) { e.printStackTrace(); }
The above should get your thing working, but a friendly note would be to experiment with the code (once it works) since it's an excellent example to understand how static keywords are used, how Exceptions are handled or thrown, and how IO is used. ;)
| |
doc_2712
|
// Import Global Game Variables
include('../engine/engine_core_functions.php');
// Convert our gamestate(gameID)
//$curGamestate = getCurrentGamestate($gameID);
// Make sure it's a valid turn
if(isMyTurn()) {
// Draw a card from the card drawing mechanism
$cardValue = drawCard();
$cardValue = str_replace("\r", 'R', $cardValue);
echo $cardValue;
}
else echo 'Error 3';
The line skip occurs immediately after the include file at the top. Before the include, no line break, after the include, line break. So I go to the include file. Placing my
echo 'OMG!';
at the VERY END of the included file does NOT produce a line break. Which led me to believe that including a file may (why!?) generate a line break (it's 5 AM...). However, there are multiple included files at the top of the offending included file. None of them generate breaks. The entire "engine_core_functions.php" generates no line breaks at all.
However, a break shows up when it is included in the above-shown script. Needless to say, I'm baffled and extremely annoyed. I could simply remove the offending characters (via PHP or Javascript) but it annoys me I can't seem to fix the root of the problem. Please help, thank you.
A: You could have some kind of invisible BOM mark at the beginning of your file or something else.
Always let <? or <?php be the first string of your PHP files and make it a practice NOT to end the entire PHP file with ?> if it's going to be included by another file.
| |
doc_2713
|
I was wondering if it were possible to do this? To be able to use the services' scripts remotely from the Flex Mobile application? Thanks!
To clarify... right now I'm trying to test something out, and I'm just getting an AsyncToken object, and I'm not sure if I'm doing anything correctly. I basically want to be able to execute the services like in those basic Employee tutorials, except I want the PHP scripts on my website where the Flex Mobile application will access them remotely.
Any suggestions on going about this? Thanks!
A: Yes of course, what you need is a remoting bridge to serialize object form and to PHP and ActionScript 3. Look for AMFPHP here http://www.silexlabs.org/amfphp/
| |
doc_2714
|
c.executemany('INSERT INTO frame VALUES (?,?)', list( ((f[0],), tuple(f[1])) ) )
This is f: ('Constructed_Restraints', ['hogtie', 'hobble'])
So this is what the 2nd argument of my .executemany line becomes:
[('Constructed_Restraints',), ('hogtie', 'hobble')]
However, I'm getting this error:
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 2, and there are 1 supplied.
I've tried nearly everything in various SO answers to other questions, but I continue getting this error. How am I only providing 1 binding? The list has 2 tuples in it.
A: Assuming you want two rows inserted with a null in the second field, try this:
c.executemany('INSERT INTO frame VALUES (?,?)', list( ((f[0],None), tuple(f[1])) )
On the other hand, if you want one row inserted with some sort of serialised value, try:
c.execute('INSERT INTO frame VALUES (?,?)', (f[0], ','.join(f[1])) )
The latter will insert the second value in comma separated value syntax which poses normalisation problems. Going beyond this probably requires database thinking, but SQLite is pretty capable so the query issues can probably be handled in place (insert and update anomalies on the other hand are different).
| |
doc_2715
|
Ajax call always gives NetwrokEror-bad request 404
Ajax call code is here
$.ajax(
{
type:'get'
cache: true,
url: 'http://localhost:4277/v1/virtuals/aa54fa50-e4ca-4a16-9f2b-db6491062cf7',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
alert('success');
},
error: function (msg, url, line) {
alert('error trapped in error: function(msg, url, line1)');
alert('msg = ' + msg + ', url = ' + url + ', line = ' + line);
console.log(msg);
}
});
A: Not sure but just giving you suggestion. This issue generally comes when the requested url path is wrong. You hit your url directly in browser and then test what is coming. It can give you some idea.
You check this link also : Tomcat 404 error
A: What you are getting is a HTTP 404 error, which says that the file does not exist. You need to check the path, if it is correct.
Or, the other situation might be like this. Cross-Domain requests might be blocked by the browser for security reasons. Try doing a proxy method to avid CORS. Some insights on CORS are here:
*
*Cross-origin resource sharing - Wikipedia
*Enable cross-origin resource sharing
*Cross-Origin Resource Sharing - W3C Recommendation
| |
doc_2716
|
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <readline/readline.h>
#include <readline/history.h>
int main()
{
char* input, shell_prompt[100];
// Configure readline to auto-complete paths when the tab key is hit.
rl_bind_key('\t', rl_complete);
for(;;) {
// Create prompt string from user name and current working directory.
snprintf(shell_prompt, sizeof(shell_prompt), "%s:%s $ ", getenv("USER"), getcwd(NULL, 1024));
// Display prompt and read input (n.b. input must be freed after use)...
input = readline(shell_prompt);
// Check for EOF.
if (!input)
break;
// Add input to history.
add_history(input);
// Do stuff...
// Free input.
free(input);
}
}
I'm working on a restricted environment were readline was not available, so I had to download the sources, compile it and install it to my home dir.
This is the structure inside my home directory:
.local
├── include
│ └── readline
│ ├── chardefs.h
│ ├── history.h
│ ├── keymaps.h
│ ├── readline.h
│ ├── rlconf.h
│ ├── rlstdc.h
│ ├── rltypedefs.h
│ └── tilde.h
└── lib
├── libhistory.a
├── libhistory.so -> libhistory.so.6
├── libhistory.so.6 -> libhistory.so.6.2
├── libhistory.so.6.2
├── libreadline.a
├── libreadline.so -> libreadline.so.6
├── libreadline.so.6 -> libreadline.so.6.2
└── libreadline.so.6.2
The problem is, when I call gcc it throws me an error:
$ gcc hello.c -o hello_c.o -I /home/my-home-dir/.local/include
/tmp/cckC236E.o: In function `main':
hello.c:(.text+0xa): undefined reference to `rl_complete'
hello.c:(.text+0x14): undefined reference to `rl_bind_key'
hello.c:(.text+0x60): undefined reference to `readline'
hello.c:(.text+0x77): undefined reference to `add_history'
collect2: error: ld returned 1 exit status
There is an answer about this here, but I'm not using Netbeans and I'm not quite sure how to specify the path to the library on the command line.
I tried to tell the linker where the libraries are, but the result is still the same:
$ gcc hello.c -o hello_c.o -I /home/my-home-dir/.local/include -Xlinker "-L /home/my-home-dir/.local/lib"
/tmp/cceiePMr.o: In function `main':
hello.c:(.text+0xa): undefined reference to `rl_complete'
hello.c:(.text+0x14): undefined reference to `rl_bind_key'
hello.c:(.text+0x60): undefined reference to `readline'
hello.c:(.text+0x77): undefined reference to `add_history'
collect2: error: ld returned 1 exit status
Any ideas what I might be missing here?
A: You need to link against the actual library using -lreadline in gcc arguments.
| |
doc_2717
|
Are there any "compilers" or merging applications for HTML that can merge multiple HTML files?
Example:
a.htm
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
</head>
<body>
INCLUDE "b.htm"
<div>
INCLUDE "c.htm"
</div>
</body>
</html>
b.htm
some text
<a href="#">Link</a>
INCLUDE "c.htm"
c.htm
more <span>text</span>
would be merged to:
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
</head>
<body>
some text
<a href="#">Link</a>
more <span>text</span>
<div>
more <span>text</span>
</div>
</body>
</html>
A: There are indeed – depending on your needs these offer drastically different mechanisms and tools.
One particular quite simple HTML compiler that is fashionable at the moment is Jekyll. Jekyll powers the blogging engine on GitHub Pages and is both easy to use and extensible.
In your case, you’d for instance write
{% include c.htm %}
instead of
INCLUDE "c.htm"
A: I decided to write htmlcat for exactly this purpose.
| |
doc_2718
|
MinGW is not installing due to some reason. And I've spent a lot of time trying to run it some other way. From my research, I think the best way to go about it is to download Visual Studio, but I have a low-end PC and I don't think I should install Visual Studio. Can I, somehow, only install the C/C++ compiler that comes with it without installing Visual Studio itself.
If it helps, I usually run my (python) code in atom, but also have Visual Studio Code installed on my machine.
I apologize if my question is stupid, I am a self-taught programmer who learned to code from MIT's 6.00.1x and 6.00.2x and am currently trying to learn C from 'The C Programming Language' by Kernighan and Ritchie. I've never formally studied computer science.
A: You can download the compiler and related stuff as part of the Visual Studio Build Tools. The 2017 version is here:
https://www.visualstudio.com/downloads/#build-tools-for-visual-studio-2017
A: What you want is called the "Windows SDK", wich contains everything you need to build applications on windows, except the IDE (Visual Studio).
It comes with all necessary libraries, header files, a compiler, nmake et cetera, and a handy shortcut for a preconfigured cmd.exe that puts all of these tools in your PATH. If you know what you are doing, this is what you want to use.
What version of the SDK you want depends on the system you are compiling on, but you will find all of them on the microsoft website. For windows 10 for example, the SDK can be found here: https://developer.microsoft.com/en-US/windows/downloads/windows-10-sdk
Be aware though, that the windows compiler cl.exe can be a bit tricky at times, and nmake is not what you expect when you only learned GNUmake. If you are only starting out learning C, then I would not recommend using the SDK for the reasons given in the comments to your question. However, if all you want is compile on windows, without having to drag 20+ Gigabytes of IDE around, then the SDK is an option to consider.
(We are using virtual machines with a preinstalled windows SDK quite successfully in lectures and exercises.)
UPDATE:
I have been made aware that as of windows 8 the SDK no longer contains the build tools for C++ based applications. These are now only contained in a Visual Studio installation.
| |
doc_2719
|
*
*Be available for v7a devices in the Play Store?
*Run on v7a devices?
If it does run, are there any features like using threads that will lead to unexpected behaviour or crashes?
I've got a simple app and am trying to keep it small. Also, I don't have a v7a device to do a quick experiment.
Clarification:
While there seems to be clear acceptance that it is "safe, but not so performant" to compile an Android app with only the amreabi library (see this excellent post: Why use armeabi-v7a code over armeabi code?), the Xamarin docs on CPU architecture, that I assume applies to their compiled .so libraries, says:
it is important to remember that the armeabi runtime used by
Xamarin.Android is thread safe. If an application that has armeabi
support is deployed to an armeabi-v7a device, many strange and
unexplainable exceptions will occur.
I have since been able to test my app that is just compiled with armeabi on a v7a device and haven't run into any "strange and unexplainable exceptions" YET.
Update:
Looks like the Xamarin docs has since been updated and now (2014-07-14) reads:
it is important to remember that the armeabi runtime used by
Xamarin.Android is not thread safe. If an application that has
armeabi support is deployed to an armeabi-v7a device, many strange
and unexplainable exceptions will occur.
A: According to the Xamarin Android documentation, armeabi code will crash in unexpected ways on a multi-core armeavi-v7 device.
http://docs.xamarin.com/guides/android/advanced_topics/cpu_architecture
Section 1.1
Note: Xamarin.Android’s armeabi code is not thread safe and should not
be used on multi-CPU armeabi-v7a devices (described below). Using
aremabi code on a single-core armeabi-v7a device is safe.
The reason that Xamarin Android make it a requirement to include armeabi-v7a has to do with thread safe memory access. Put simply the armeabi instruction set lacks the instructions necessary to safely lock memory on SMP devices.
The most thorough discussion of the issue can be found in this bug report: https://bugzilla.xamarin.com/show_bug.cgi?id=7013
Jonathan Pryor 2012-09-20 11:41:45 EDT
As far as I can determine, it is (nearly) IMPOSSIBLE to SAFELY use an armeabi
library on a SMP armeabi-v7a device. This is because armeabi lacks the CPU
instructions necessary to safely lock data on SMP devices, so if the armeabi
library contains data that must be protected against access from multiple
threads, it's busted, and libmonodroid.so is such a library. This may be
fixable by creating a libmonodroid.so which dynamically determines the runtime
CPU, allowing it to use either armeabi or armeabi-v7a lock instructions
accordingly, but this has not been done yet, and the implementation timeframe
is unknown.
Thus, if your app will be running on SMP hardware, you should include the
armeabi-v7a runtime with your app. This can be done in the Project Options
dialog.
These crashes are rare but catastrophic and very hard to debug as you experience random memory corruption and segmentation faults.
I was able to reproduce the issue reliably on a Galaxy S3. Some example code that demonstrates the crash is in this bug report: https://bugzilla.xamarin.com/show_bug.cgi?id=7167
It's unknown whether or not this bug affects other NDK applications on Android. But it definitely affects Xamarin Android.
A: I clicked through and read the Xamarin comments. Based on reading them, I think you are asking the wrong question. The answer to the question you asked is (as CommonsWare stated in his comment), "yes, unless Xamarin screwed something up". Unfortunately, their docs indicate that they think that they did, arguably, screw something up. There are some typos in their documentation that confuse things a bit, specifically in one place (Section 1.1) they say "is thread safe" when they clearly mean "is NOT thread safe". They restate this correctly in Section 1.2:
Note: Xamarin.Android’s armeabi code is not thread safe and should not
be used on multi-CPU armeabi-v7a devices (described below). Using
aremabi code on a single-core armeabi-v7a device is safe.
I think if you combine information from sections 1.2 and 1.1, it becomes clear what Xamarin is telling you. To be clear I'm just restating what their documentation says, not making any assertions about the veracity of their documentation. That is, in the case where the armeabi libs (which are not thread safe) get loaded on a multi-core or multi-processor device, bad things may happen. This case can arise due to a bug in ICS (4.0.0-4.0.3). Therefore:
applications built by using Xamarin.Android 4.2 or lower should explicitly specify the armeabi-v7a as the sole ARM-based ABI
Here is the actual info from their docs (formatting added) rearranged into an order that may help make it clearer:
From Section 1.2.1
Note: Xamarin.Android’s armeabi code is not thread safe and should not be used on multi-CPU armeabi-v7a devices (described below). Using aremabi code on a single-core armeabi-v7a device is safe.
From Section 1.1
Due to a bug in Android 4.0.0, 4.0.1, 4.0.2, and 4.0.3, the native libraries will be picked up from the armeabi directory even though there is an armeabi-v7a directory present and the device is an armeabi-v7a device.
Note: Because of these reasons, it is strongly recommended that applications built by using Xamarin.Android 4.2 or lower should explicitly specify the armeabi-v7a as the sole ARM-based ABI.
I think that based on the rest of the doc, this is what the first paragraph in Section 1.1 should say (bold edits are mine):
The Application Binary Interface will be discussed in detail below,
but it is important to remember that the armeabi runtime used by
Xamarin.Android is not thread safe. If an application that has armeabi
support is deployed to multi-CPU armeabi-v7a device, many strange and
unexplainable exceptions will occur.
A: http://www.arm.com/products/processors/instruction-set-architectures/index.php
If you look at this diagram it explains the ethos of ARM processor design.
New iterations extend the base feature set, but don't change it. NEON and SIMD need to be directly referenced to be used, so cannot be referenced from an ARMv5 binary. Unless your binary is huge (that's the actual executable, not the whole APK), I would compile both and get the best of both worlds. See this question for details.
Regardless, I would contact Xamarin to clarify that slightly loaded 'unexplainable exceptions' statement. If they perceive issues with their code running on multiple processors then their code is inherently not thread safe regardless of the number of cores.
A: Yes.
armeabi is the general base and armeabi-v7a includes some additional instructions not found in the armeabi instruction set. v7a has support for hardware floating point operations, which can make your code much faster if it is doing any floating point operations. Android will attempt to load an armeabi-v7a library first if the hardware supports that, but if not, it will fall back to the armeabi version.
| |
doc_2720
|
I have a screen where the administrator of the site configures the mail server settings, which would then be used by the application to send out emails whenever needed.
Below is a highly abridged version of the code that we have:
public static boolean sendEmail(String toAddress, String fromAddress, String userName, String userPassword,String smtpHost, String portNumber, String emailSubject,String emailBody) {
// Recipient's email ID needs to be mentioned.
String to = toAddress;
// Sender's email ID needs to be mentioned
String from = fromAddress;//change accordingly
final String username = userName;//change accordingly
final String password = userPassword;//change accordingly
// Assuming you are sending email through relay.jangosmtp.net
String host = smtpHost;
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.fallback", "false");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.socketFactory.port", portNumber);
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", portNumber);
//For NTLM
props.setProperty("mail.imap.auth.ntlm.domain","");
// Get the Session object.
SMTPAuthenticator authenticator = new SMTPAuthenticator(username, password);
props.put("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
Session session = Session.getInstance(props, authenticator);
try {
// Create a default MimeMessage object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
// Set Subject: header field
message.setSubject(emailSubject);
// Now set the actual message
message.setText(emailBody);
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
return true;
}
It worked fine, until we deployed our application in one of our client environments. Our client uses an on-premise MS Exchange Server that uses NTLM authentication
Here, we need to specify the from and to addresses as MYDOMAIN\s.sriram as opposed to [email protected]
The above code does not work in this situation, which throws the following exception:
Exception in thread "main" java.lang.RuntimeException: com.sun.mail.smtp.SMTPSendFailedException: 501 5.1.7 Invalid address
;
nested exception is:
com.sun.mail.smtp.SMTPSenderFailedException: 501 5.1.7 Invalid address
at com.ycs.tenjin.mail.EmailUtil.sendEmail(EmailUtil.java:86)
at com.ycs.tenjin.mail.EmailUtil.main(EmailUtil.java:19)
Caused by: com.sun.mail.smtp.SMTPSendFailedException: 501 5.1.7 Invalid address
;
nested exception is:
com.sun.mail.smtp.SMTPSenderFailedException: 501 5.1.7 Invalid address
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2108)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1609)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1117)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at com.ycs.tenjin.mail.EmailUtil.sendEmail(EmailUtil.java:80)
... 1 more
Caused by: com.sun.mail.smtp.SMTPSenderFailedException: 501 5.1.7 Invalid address
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1616)
... 5 more
However, if I try set the from and to addresses to the conventional format, i.e. [email protected], then I get an Authentication unsuccessful error, like the one below:
Exception in thread "main" java.lang.RuntimeException: javax.mail.AuthenticationFailedException: 535 5.7.3 Authentication unsuccessful
at com.ycs.tenjin.mail.EmailUtil.sendEmail(EmailUtil.java:85)
at com.ycs.tenjin.mail.EmailUtil.main(EmailUtil.java:19)
Caused by: javax.mail.AuthenticationFailedException: 535 5.7.3 Authentication unsuccessful
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:826)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:761)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:685)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at com.ycs.tenjin.mail.EmailUtil.sendEmail(EmailUtil.java:79)
... 1 more
Either way, this does not work.
Now, the customer tells me that he has another application where he has been able to successfully configure and send emails with the same MS Exchange server and the from & to address being specified like MYDOMAIN\s.sriram. I was even shown the other application's email configuration screen, where there was an option to explicitly choose NTLM as the authentication type. All other parameters were the same as what I have described in my code snippet above.
Is there a way we can set authentication type to NTLM instead of SMTP?
If no, could anyone suggest a way out of this problem?
| |
doc_2721
|
Text | Label
Some text | 0
hellow bye what | 1
...
Each row is a data point. Label is 0/1 binary. The only feature is Text which contains a set of words. I want to use the presence or absence of each word as features. For example, the features could be contains_some contains_what contains_hello contains_bye, etc. This is typical one hot encoding.
However I don't want to manually create so many features, one for every single word in the vocabulary (the vocabulary is not huge, so I am not worried about the feature set exploding). But I just want to supply a list of words as a single column to tensorflow and I want it to create a binary feature for each word in the vocabulary.
Does tensorflow/keras have an API to do this?
A: You can use sklearn for this , try this:
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer(binary=True)
X = vectorizer.fit_transform(old_df['Text'])
new_df = pd.DataFrame(X.toarray(), columns=vectorizer.get_feature_names())
new_df['Label'] = old_df['label']
and this should give you :
bye hellow some text what target
0 0 1 1 0 0
1 1 0 0 1 1
CountVectorizer convert a collection of text documents to a matrix of token counts.
This implementation produces a sparse representation of the counts using scipy.sparse.csr_matrix and if binary = True then all non zero counts are set to 1. This is useful for discrete probabilistic models that model binary events rather than integer counts.
A: What you're looking for is a (binary) bag of words which you can get from scikit-learn using their CountVectorizer here.
You can do something like:
from sklearn.feature_extraction.text import CountVectorizer
bow = CountVectorizer(ngram_range=(1, 1), binary=True)
X_train = bow.fit_transform(df_train['text'].values)
This will create an array of binary values indicating the presence of a word in each text. Use binary=True to output a 1 or 0 if the word is present. Without this field you will get counts of occurrences per word, either method works fine.
In order to inspect the counts you could use the below:
# Create sample dataframe of BoW outputs
count_vect_df = pd.DataFrame(X_train[:1].todense(),columns=bow.get_feature_names())
# Re-order counts in descending order. Keep top 10 counts for demo purposes
count_vect_df= count_vect_df[count_vect_df.iloc[-1,:].sort_values(ascending=False).index[:10]]
# print combination of original train dataframe with BoW counts
pd.concat([df_train['text'][:1].reset_index(drop=True), count_vect_df], axis=1)
Update
If your features include categorical data you could try using to_categorical from tf.keras. See the docs for more information.
| |
doc_2722
|
Time Prediction
1 02.01.2015 01:00 - 02.01.2015 02:00 (CET) 10984
2 02.01.2015 02:00 - 02.01.2015 03:00 (CET) 10600
3 02.01.2015 03:00 - 02.01.2015 04:00 (CET) 9900
4 02.01.2015 04:00 - 02.01.2015 05:00 (CET) 9857
5 02.01.2015 05:00 - 02.01.2015 06:00 (CET) 10615
Now I need to copy each row 4 times. I tried
rbind(dt.prediction, dt.prediction, dt.prediction, dt.prediction)
dt.prediction[order(Time)
But because the time is all these values in one column it doesn't work. If I order it 2016 is at the bottom and the top while there is 2015-2017 in my dataset. Is there a way to order it the right way? Or do I need somehow to split the time column in to more columns or something?
Thanks!
| |
doc_2723
|
Would I do the saving in self.editFruit = function (fruit) { after fruit.beginEdit(self.editTransaction); ? in FireBug I set a breakpoint on the fruit object but can't see the properties, i.e do something like var name = fruit.name but if I put name in an alert I just see a function, no property.
Any pointers?
A: I am a little confused about how you are trying to save, but to see the name in the alert you must unwrap the property.
var x = fruit.name();
or depending on how your vm is set
var x = fruit().name();
| |
doc_2724
|
i tried by using syscall and the adress of the buffer but i dont have any idea of how to solve this question.
i dont really know how to do this because i didn't find an easy way to get binary values from the bit.
in addition,in order to calculate M^2 i need always the the matrix column,which are not organized as an array in the memory.
thanks to all helpers.
| |
doc_2725
|
In Nhibernate I saw a lot of code written as:
using(ISession sess = factory.OpenSession()) {
using(ITransaction trans = sess.BeginTransaction()) {
// query, or save
trans.Commit();
}}
Starting transactions for queries or even single entity update always puzzled me why? Then after reading I learned that if you follow this pattern you will get 2 benefits:
*
*Automatic connection release
*Automatic flush
Fair enough.
My question is in regards to Castle ActiveRecord and connection pooling.
I am using Active Record in ASP.NET app, and the common pattern is to create a session for entire request.
My questions are:
1.
Should I use SessionScope or TransactionScope (and use start/end transaction to get/release my connection) so that I achieve efficient connection pooling,- ie. I want to hold on to the database connection (ADO.net connection object) during my persistence logic only, not for the entire life-time of the request (use connection semantics that are implemented by nhibernate transactions mentioned above)?
2.
Does SessionScope flushes when it goes out of scope (ie. in its Dispose method)?
LK (Answered): Yes, unless the scope is read-only.
3.
Does TransactionScope rollback when it goes out of scope (ie. in its Dispose method)?
LK (Answered): Depends on onDispose action, but by default it commits.
4.
Where's the official Castle Active Record documentation, - I see bits and pieces on various sites and various sites with broken links. Is there an official PDF documentation like for nhibernate or even a book?
A: You can use SessionScope. It will handle the common transaction semantics for you. You can use a TransactionScope when you need more fine grained control on the transaction. You can even open a TransactionScope within a SessionScope to handle multiple transactions within a single session.
The official documentation is here:
http://docs.castleproject.org/Active%20Record.MainPage.ashx
It is not great.
The old documentation is here:
http://old.castleproject.org/activerecord/documentation/trunk/index.html
The old stuff is better for some topics.
| |
doc_2726
|
A: The provisioning profile must be signed by Apple for a device to accept it.
So while you could create a new plist, with an extra UDID and then sign it - unless you have one of Apple's private keys - the new provisioning profile would not be recognised.
| |
doc_2727
|
The game is a multiplication times tables game with the intention that when the user enters answers (on prev activity) the answer they entered are shown in the item (i.e. 12 items) and the correct answer for each is shown in each sub-item.
.Java code:
public class Results extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.results);
ListView itemList = (ListView) findViewById(R.id.lvresults);
//gets array from prev act
int[] results = getIntent().getIntArrayExtra("results");
int numberPassed = getIntent().getIntExtra("numberPassed", 0);
ArrayList < HashMap <String, String> > list = new ArrayList < HashMap <String, String> > ();
// loop to give list view
for (int i = 1; i <= 12; ++i)
{
int userAnswer = results[i - 1];
int expectedAnswer = numberPassed * i;
String userString = numberPassed + "x" + i + "=" + userAnswer;
String expectedString = "" + expectedAnswer;
HashMap <String, String> map = new HashMap <String, String> ();
map.put("user", userString);
map.put("expected", expectedString);
list.add(map);
}
String[] keys = {"user", "expected"};
int[] ids = {R.id.user_answer, R.id.expected_answer};
SimpleAdapter adapter = new SimpleAdapter(this, list, android.R.layout.simple_list_item_2, keys, ids);
itemList.setAdapter(adapter);
}
}
XML code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/lvresults"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ListView>
<TextView
android:id="@+id/user_answer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp" />
<TextView
android:id="@+id/expected_answer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp" />
</LinearLayout>
A: int[] ids={android.R.id.text1,android.R.id.text2}
and remove the two TextView from the layout
| |
doc_2728
|
The next method gets a GridFSFile object (which represents a file in MongoDB GridFSFileStorage) and then calls uploadMemoryStream method to do the upload.
It's worth to mention that gridFSFile does have content after findById and that length dows also has content and that position is initially in 0.
The gridFSFile.Open method creates a Stream object that I then pass as an argument to the upload.
private static void iterateOverVersionCollection(Version version, Asset asset)
{
try
{
string _gridFSId = version.GridFSId;
GridFSFile gridFSFile = gridFSFileStorage.FindById(_gridFSId);
if (gridFSFile == null) return;
string size = version.Name.ToLower();
asset.Size = size;
CloudBlockBlob blockBlob = GetBlockBlobReference(version, gridFSFile, asset);
uploadMemoryStream(blockBlob, gridFSFile, asset);
asset.UploadedOK = true;
}
catch (StorageException ex)
{
asset.UploadedOK = false;
logException(ex, asset);
}
}
private static void uploadMemoryStream(CloudBlockBlob blockBlob, GridFSFile gridFSFile, Asset asset)
{
Stream st = gridFSFile.Open();
blockBlob.UploadFromStream(st);
}
UploadFromStream takes forever and never does the upload, and one thing to mention is that no matter how I work with gridFSFile, if I try to create a MemoryStream with it with Stream.copyTo c# method it is also taking forever and never ending so the app is getting stuck at blockBlob.UploadFromStream(st);
Instead of just passing gridFSFile.Open to UploadFromMemoryStream I've also tried the next piece of code:
using (var stream = new MemoryStream())
{
byte[] buffer = new byte[2048]; // read in chunks of 2KB
int bytesRead;
while((bytesRead = st.Read(buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, bytesRead);
}
byte[] result = stream.ToArray();
}
But the same, program gets stuck in st.Read line.
Any help will be much appreciated.
A: Please note that since UploadFromFileAsync() or UploadFromStream is not a reliable and efficient operation for a huge blob, I'd suggest you to consider following alternatives:
If you can accept command line tool, you can try AzCopy, which is able to transfer Azure Storage data in high performance and its transferring can be paused & resumed.
If you want to control the transferring jobs programmatically, please use Azure Storage Data Movement Library, which is the core of AzCopy.Sample code for the same
string storageConnectionString = "myStorageConnectionString";
CloudStorageAccount account = CloudStorageAccount.Parse(storageConnectionString);
CloudBlobClient blobClient = account.CreateCloudBlobClient();
CloudBlobContainer blobContainer = blobClient.GetContainerReference("mycontainer");
blobContainer.CreateIfNotExistsAsync().Wait();
string sourcePath = @"C:\Tom\TestLargeFile.zip";
CloudBlockBlob destBlob = blobContainer.GetBlockBlobReference("LargeFile.zip");
// Setup the number of the concurrent operations
TransferManager.Configurations.ParallelOperations = 64;
// Setup the transfer context and track the upoload progress
var context = new SingleTransferContext
{
ProgressHandler =
new Progress<TransferStatus>(
progress => { Console.WriteLine("Bytes uploaded: {0}", progress.BytesTransferred); })
};
// Upload a local blob
TransferManager.UploadAsync(sourcePath, destBlob, null, context, CancellationToken.None).Wait();
Console.WriteLine("Upload finished !");
Console.ReadKey();
If you are still looking for uploading file programmatically from stream, i would suggest you to upload it in chunks which is possible using below code
var container = _client.GetContainerReference("test");
container.CreateIfNotExists();
var blob = container.GetBlockBlobReference(file.FileName);
var blockDataList = new Dictionary<string, byte[]>();
using (var stream = file.InputStream)
{
var blockSizeInKB = 1024;
var offset = 0;
var index = 0;
while (offset < stream.Length)
{
var readLength = Math.Min(1024 * blockSizeInKB, (int)stream.Length - offset);
var blockData = new byte[readLength];
offset += stream.Read(blockData, 0, readLength);
blockDataList.Add(Convert.ToBase64String(BitConverter.GetBytes(index)), blockData);
index++;
}
}
Parallel.ForEach(blockDataList, (bi) =>
{
blob.PutBlock(bi.Key, new MemoryStream(bi.Value), null);
});
blob.PutBlockList(blockDataList.Select(b => b.Key).ToArray());
on hte other hand if you have file available in your system and want to use Uploadfile method, we have flexibility in this method too to upload files data in chunks
TimeSpan backOffPeriod = TimeSpan.FromSeconds(2);
int retryCount = 1;
BlobRequestOptions bro = new BlobRequestOptions()
{
SingleBlobUploadThresholdInBytes = 1024 * 1024, //1MB, the minimum
ParallelOperationThreadCount = 1,
RetryPolicy = new ExponentialRetry(backOffPeriod, retryCount),
};
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(ConnectionString);
CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
cloudBlobClient.DefaultRequestOptions = bro;
cloudBlobContainer = cloudBlobClient.GetContainerReference(ContainerName);
CloudBlockBlob blob = cloudBlobContainer.GetBlockBlobReference(Path.GetFileName(fileName));
blob.StreamWriteSizeInBytes = 256 * 1024; //256 k
blob.UploadFromFile(fileName, FileMode.Open);
For detailed explanation, please browse
https://www.red-gate.com/simple-talk/cloud/platform-as-a-service/azure-blob-storage-part-4-uploading-large-blobs/
Hope it helps.
| |
doc_2729
|
Here is my code:
Users.java:
package com.example.how;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
public class Users extends AppCompatActivity {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference UsersRef = db.collection("Users");
private UsersAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_users);
setUpRecyclerView();
}
private void setUpRecyclerView() {
Query query = UsersRef;
FirestoreRecyclerOptions<UsersModel> options = new FirestoreRecyclerOptions.Builder<UsersModel>()
.setQuery(query, UsersModel.class)
.build();
adapter = new UsersAdapter(options);
RecyclerView recyclerView = findViewById(R.id.FireStoreList);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
@Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
@Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
activity_users.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Users">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/FireStoreList"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" >
</androidx.recyclerview.widget.RecyclerView>
</androidx.constraintlayout.widget.ConstraintLayout>
UsersModel.java:
package com.example.how;
public class UsersModel {
private String FName,LName,DOB,email,PhoneNumber,UserID;
private UsersModel(){}
private UsersModel(String FName,String LName, String DOB, String email, String PhoneNumber,
String UserID){
this.FName = FName;
this.LName = LName;
this.DOB = DOB;
this.email = email;
this.PhoneNumber = PhoneNumber;
this.UserID = UserID;
}
public String getFName() {
return FName;
}
public void setFName(String FName) {
this.FName = FName;
}
public String getLName() {
return LName;
}
public void setLName(String LName) {
this.LName = LName;
}
public String getDOB() {
return DOB;
}
public void setDOB(String DOB) {
this.DOB = DOB;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNumber() {
return PhoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
PhoneNumber = phoneNumber;
}
public String getUserID() {
return UserID;
}
public void setUserID(String userID) {
UserID = userID;
}
}
UsersAdapter.java:
package com.example.how;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
public class UsersAdapter extends FirestoreRecyclerAdapter<UsersModel, UsersAdapter.UsersHolder>
{
public UsersAdapter(@NonNull FirestoreRecyclerOptions<UsersModel> options) {
super(options);
}
@Override
protected void onBindViewHolder(@NonNull UsersHolder holder, int position, @NonNull UsersModel
model) {
holder.FName.setText(model.getFName());
holder.LName.setText(model.getLName());
holder.email.setText(model.getEmail());
holder.PhoneNumber.setText(model.getPhoneNumber());
holder.DOB.setText(model.getDOB());
holder.UserID.setText(model.getUserID());
}
@NonNull
@Override
public UsersHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v =
LayoutInflater.from(parent.getContext()).inflate(R.layout.userdetails,parent,false);
return new UsersHolder(v);
}
class UsersHolder extends RecyclerView.ViewHolder{
TextView FName,LName,DOB,email,PhoneNumber,UserID;
public UsersHolder(View itemView) {
super(itemView);
FName= itemView.findViewById(R.id.txtFName);
LName= itemView.findViewById(R.id.txtLName);
DOB= itemView.findViewById(R.id.txtDOB);
email= itemView.findViewById(R.id.txtemail);
PhoneNumber= itemView.findViewById(R.id.txtPhoneNumber);
UserID= itemView.findViewById(R.id.txtUserID);
}
}
}
userdetails.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/txtFName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="51dp"
android:text="hrllo"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/txtLName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="13dp"
android:text="hrllo"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/txtFName" />
<TextView
android:id="@+id/txtDOB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="13dp"
android:text="hrllo"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/txtLName" />
<TextView
android:id="@+id/txtemail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="11dp"
android:text="hrllo"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/txtDOB" />
<TextView
android:id="@+id/txtPhoneNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="11dp"
android:text="hrllo"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/txtemail" />
<TextView
android:id="@+id/txtUserID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="11dp"
android:text="hrllo"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/txtPhoneNumber" />
</androidx.constraintlayout.widget.ConstraintLayout>
A: The first error was solved by @MayurGajra which was that I was inflating activity_users instead of userdetails. And the second error was that fields' names should be the same in the Model.java, and the firebase. If they were different, data would not be retrieved
| |
doc_2730
|
select?q=*%3A*&wt=json&indent=true
So I got such result with json
"response":{"numFound":35851492,"start":0,"maxScore":1.0,"docs":
but when I wrote another query like this
select?q=*%3A*&start=100000&wt=json&indent=true
I got another numfound
"response":{"numFound":35850348,"start":100000,"maxScore":1.0,"docs":
Now I want to get why there are different numfound in the same data and how can I get the correct numfound for my application! thank you!
A:
I have tried to get the number of results when I used Solr-Cluster
This is the key. It has nothing to do with "rows", and everything to do with querying a cluster.
The internal load balancing is probably picking a different shard, and the shard replicas must not have identical data.
You can try querying the shards individually (and also passing the param distrib=false to avoid distributed search and query that shard only).
| |
doc_2731
|
Exception in thread "main" java.lang.NoClassDefFoundError: start (wrong name: Start)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:482)
I have found other examples of people getting similar errors but cant seem to find the solution to mine or why it is happening. So that is my question, why am i getting this error? What can I do to prevent it from happening again?
Thanks, Ciaran.
A: You have to use the fully qualified class name. if your class Start is in package a, then you must launch using java a.Start for example. You can also use the -cp option to set Classpath.
A: You have to open the CMD from the main path and run the java command with full package details.
Ex: If your Start.class is in C:\EampleProj\com\test\Start.class. then you should try
C:\EampleProj>java com.test.Start
| |
doc_2732
|
My current Code looks like this at the moment:
public class NetworkTask extends AsyncTask<Void, byte[], Boolean> {
Socket nsocket; //Network Socket
InputStream nis; //Network Input Stream
OutputStream nos; //Network Output Stream
boolean bSocketStarted = false;
byte[] buffer = new byte[4096];
@Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
}
@Override
protected Boolean doInBackground(Void... params) { //This runs on a different thread
boolean result = false;
try {
// Connect to address
Log.i(TAG, "doInBackground: Creating socket");
SocketAddress sockaddr = new InetSocketAddress("google.de", 80);
nsocket = new Socket();
nsocket.connect(sockaddr, 5000); //10 second connection timeout
if (nsocket.isConnected()) {
bSocketStarted = true;
nis = nsocket.getInputStream();
nos = nsocket.getOutputStream();
Log.i("AsyncTask", "doInBackground: Socket created, streams assigned");
Log.i("AsyncTask", "doInBackground: Waiting for inital data...");
int read = nis.read(buffer, 0, 4096); //This is blocking
while(bSocketStarted) {
if (read > 0){
byte[] tempdata = new byte[read];
System.arraycopy(buffer, 0, tempdata, 0, read);
publishProgress(tempdata);
Log.i(TAG, "doInBackground: Got some data");
}
}
}
} catch (IOException e) {
e.printStackTrace();
Log.i(TAG, "doInBackground: IOException");
result = true;
} catch (Exception e) {
e.printStackTrace();
Log.i(TAG, "doInBackground: Exception");
result = true;
} finally {
try {
nis.close();
nos.close();
nsocket.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Log.i(TAG, "doInBackground: Finished");
}
return result;
}
public boolean SendDataToNetwork(final byte[] cmd) { //You run this from the main thread.
// Wait until socket is open and ready to use
waitForSocketToConnect();
if (nsocket.isConnected()) {
Log.i(TAG, "SendDataToNetwork: Writing received message to socket");
new Thread(new Runnable() {
public void run() {
try {
nos.write(cmd);
}
catch (Exception e) {
e.printStackTrace();
Log.i(TAG, "SendDataToNetwork: Message send failed. Caught an exception");
}
}
}
).start();
return true;
}
else
Log.i(TAG, "SendDataToNetwork: Cannot send message. Socket is closed");
return false;
}
public boolean waitForSocketToConnect() {
// immediately return if socket is already open
if (bSocketStarted)
return true;
// Wait until socket is open and ready to use
int count = 0;
while (!bSocketStarted && count < 10000) {
try {
Thread.sleep(500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
count += 500;
}
return bSocketStarted;
}
@Override
protected void onProgressUpdate(byte[]... values) {
try {
if (values.length > 0) {
Log.i(TAG, "onProgressUpdate: " + values[0].length + " bytes received.");
String str = new String(buffer, "UTF8");
Log.i(TAG,str);
tv.setText(str);
tv.setMovementMethod(new ScrollingMovementMethod());
}
} catch (Exception e) {
e.printStackTrace();
}
finally {}
}
@Override
protected void onCancelled() {
Log.i(TAG, "Cancelled.");
}
@Override
protected void onPostExecute(Boolean result) {
if (result) {
Log.i(TAG, "onPostExecute: Completed with an Error.");
} else {
Log.i(TAG, "onPostExecute: Completed.");
}
}
}
I can instantiate the Task and call SendDataToNetwork from my activity. However, all the text I pass to SendDataToNetwork, for example, 'GET / HTTP/1.1' is continously sent to the server.
How can I modify my Code to maintain the connection in doInBackground and do nothing until I call SendDataToNetwork and after sending bytes to the server just wait until new data is ready to be sent? Basically I want to run the AsyncTask until I explicitly cancel (= close the connection) it.
A: nsocket.connect(sockaddr, 5000); //10 second connection timeout
if (nsocket.isConnected()) {
The test is pointless. If the socket wasn't connected, connect() would have thrown an exception.
Your read loop is also fundamentally flawed, in that it doesn't keep reading. There are standard solutions as to how to read a stream, e.g.:
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
Your waitForSocketToConnect() method doesn't really do anything useful either.
You need to rethink all this.
| |
doc_2733
|
You need to classify it because you need to reuse the TextFormField elsewhere.
But I want to see the value I entered in the TextFormField at the caller.
How can I see the text of the controller in this case?
import 'package:flutter/material.dart';
class Sample extends StatelessWidget {
const Sample({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
ElevatedButton(
onPressed: () {
// print(_controller.text);
},
child: const Text('text is...'),
),
],
),
);
}
}
class SampleField extends StatefulWidget {
const SampleField({Key? key}) : super(key: key);
@override
State<SampleField> createState() => _SampleFieldState();
}
class _SampleFieldState extends State<SampleField> {
late TextEditingController _controller;
@override
void initState() {
_controller = TextEditingController();
super.initState();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return TextFormField(
controller: _controller,
);
}
}
I would like to thank you in advance.
thank you!
| |
doc_2734
|
`SELECT a.id, b.user FROM (SELECT...FROM a_table) a, (SELECT...FROM b_table) b WHERE a.date = b.date;`
but it returns error "loop (...)+ does not match input....".
Does Hive support multiple subqueries in FROM just like Oracle DB?
A: Multiple subqueries allowed in hive.
I tested with below code,it works.
select * from (select id from test where id>10) a
join (select id from test where id>20) b on a.id=b.id;
Please post your exact code so that I can give relevant solution.
A: join subqueries is supported Absolutely.
I think the key problem is that u use SELECT...FROM.
The correct syntax is SELECT * FROM
SELECT a.id, b.user
FROM
(SELECT * FROM a_table) a
JOIN (SELECT * FROM b_table) b ON a.date = b.date;
A: If you want to obtain the full Cartesian product before applying the WHERE
clause, instead:
SELECT a.id, b.user FROM (SELECT...FROM a_table) a, (SELECT...FROM b_table) b WHERE a.date = b.date;
you should use 'join' in the middle, i.e.
SELECT a.id, b.user FROM (SELECT...FROM a_table) a join (SELECT...FROM b_table) b WHERE a.date = b.date;
above is not admissible in strict mode.
| |
doc_2735
|
A: I know this exact problem... I didn't find a way to access the files through Joomla, but we arranged a collection of important files (quite a lot) on our Joomla Server. There is a component called jifile which is able of indexing all sorts of files. We built up an index with jifile (pretty easy and fast) and now we can search for files and their contents through the Joomla search. If you end up using this approach I'll be happy to help if you have any questions :-)
| |
doc_2736
|
But some users and admins are receiving the emails with html code.. I checked in many ways with gmail, webmail.. All are displaying good.. Finally I tested with outlook and in outlook mail was getting in html code.. By enquiring the users they said that they r using outlook.. So that issue was with outlook I think so..
Can anyone help me to solve this issue.. Here is the source code which was used for displaying in email message.
$to = $obj_check_out->email;
$subject = "NEW YORK PRODUCT ORDER";
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From: Instyle Customer Accounts <[email protected]>" . "\r\n";
$message = '<table width="100%" align="center">
<tbody><tr><td bgcolor="#393939">
<br>
<br>
<table cellspacing="0" cellpadding="0" width="650" border="0" align="center">
<tbody>
<tr>
<td width="10" bgcolor="#efefef">
<img src="images/newsletter/top_left.jpg" class="CToWUd">
</td>
<td width="630" height="92" bgcolor="#efefef" background="images/newsletter/top_bg.jpg">
<table width="630">
<tbody>
<tr>
<td width="514">
<font color="#333333" style="font-family:Tahoma;font-size:12px">
<br>
<b><a target="_blank" href="#"><span class="il">NEWYORK</span>.COM</a> ORDER CONFIRMATION</b> </font>
<font color="#333333" style="font-family:Tahoma;font-size:10px">[ DATE: '.$response["date_ordered"].' ]</font>
</td>
<td width="104" align="right">
<font color="#333333" style="font-family:Tahoma;font-size:12px">
<br>
<b>ORDER#:</b></font>
<font color="#333333" style="font-family:Tahoma;font-size:10px"> '.$response["order_log_id"].'</font>
</td>
</tr>
</tbody>
</table>
<br>
</td>
<td width="10" bgcolor="#efefef">
<img src="images/newsletter/top_right.jpg" class="CToWUd">
</td>
</tr>
<tr>
<td bgcolor="#efefef"> </td>
<td bgcolor="#efefef">
<font color="#333333">
<table cellspacing="0" cellpadding="2" width="630" border="0">
<tbody>
<tr>
<td height="35" bgcolor="#767676" background="images/newsletter/bar_bg.jpg" colspan="2">
<font color="#ffffff" style="font-family:Tahoma;font-size:12px">
<b>SHIPPING DETAILS</b></font>
</td>
</tr>
<tr>
<td width="170"> <font style="font-family:Tahoma;font-size:10px"><b>Name :</b></font></td>
<td width="452"><font style="font-family:Tahoma;font-size:10px">'.$response["firstname"].' '.$response["lastname"].'</font></td>
</tr>
<tr>
<td> <font style="font-family:Tahoma;font-size:10px"><b>Address :</b></font></td>
<td><font style="font-family:Tahoma;font-size:10px">'.$response["ship_address1"].' '.$response["ship_address2"].'</font></td>
</tr>
<tr>
<td> <font style="font-family:Tahoma;font-size:10px"><b>City :</b></font></td>
<td><font style="font-family:Tahoma;font-size:10px">'.$response["ship_city"].'</font></td>
</tr>
<tr>
<td> <font style="font-family:Tahoma;font-size:10px"><b>State :</b></font></td>
<td><font style="font-family:Tahoma;font-size:10px">'.$response["ship_state"].'</font></td>
</tr>
<tr>
<td> <font style="font-family:Tahoma;font-size:10px"><b>Country :</b></font></td>
<td><font style="font-family:Tahoma;font-size:10px">'.$response["ship_country"].'</font></td>
</tr>
<tr>
<td> <font style="font-family:Tahoma;font-size:10px"><b>Zip :</b></font></td>
<td><font style="font-family:Tahoma;font-size:10px">'.$response["ship_zipcode"].'</font></td>
</tr>
<tr>
<td> <font style="font-family:Tahoma;font-size:10px"><b>Phone :</b></font></td>
<td><font style="font-family:Tahoma;font-size:10px">'.$response["telephone"].'</font></td>
</tr>
<tr>
<td> <font style="font-family:Tahoma;font-size:10px"><b>Email :</b></font></td>
<td><font style="font-family:Tahoma;font-size:10px"><a target="_blank" href="mailto:'.$response["email"].'">'.$response["email"].'</a></font></td>
</tr>
<tr>
<td> <font style="font-family:Tahoma;font-size:10px"><b>Courier :</b></font></td>
<td><font style="font-family:Tahoma;font-size:10px">'.$response["courier"].'</font></td>
</tr>
</tbody>
</table>
<br>
<table cellspacing="0" cellpadding="2" width="630" border="0">
<tbody><tr>
<td background="images/newsletter/bar_bg.jpg" align="center"><font color="#a1a1a1" style="font-family:Tahoma;font-size:11px"><b>Thumb</b></font></td>
<td background="images/newsletter/bar_bg.jpg" align="center"><font color="#a1a1a1" style="font-family:Tahoma;font-size:11px"><b>Item</b></font></td>
<td background="images/newsletter/bar_bg.jpg" align="center"><font color="#a1a1a1" style="font-family:Tahoma;font-size:11px"><b>Style Number</b></font></td>
<td background="images/newsletter/bar_bg.jpg" align="center"><font color="#a1a1a1" style="font-family:Tahoma;font-size:11px"><b>Size</b></font></td>
<td background="images/newsletter/bar_bg.jpg" align="center"><font color="#a1a1a1" style="font-family:Tahoma;font-size:11px"><b>Color</b></font></td>
<td background="images/newsletter/bar_bg.jpg" align="center"><font color="#a1a1a1" style="font-family:Tahoma;font-size:11px"><b>Quantity</b></font></td>
<td background="images/newsletter/bar_bg.jpg" align="center"><font color="#a1a1a1" style="font-family:Tahoma;font-size:11px"><b>Price</b></font></td>
<td background="images/newsletter/bar_bg.jpg" align="center"><font color="#a1a1a1" style="font-family:Tahoma;font-size:11px"><b>Subtotal</b></font></td>
</tr>
'.$ordermsg.'
<tr>
<td align="right" colspan="7"><font style="font-family:Tahoma;font-size:12px">Grand-Total : </font></td>
<td align="right"><font style="font-family:Tahoma;font-size:12px">$'.$grandtotal.'</font></td>
</tr>
<tr>
<td align="right" colspan="7"><font style="font-family:Tahoma;font-size:9px">( For countries other than United State, you will be contacted by customer service for shipping fees ) </font></td>
<td align="center"></td>
</tr>
<tr>
<td align="center" colspan="8"><font style="color:red;font-family:Tahoma;font-size:9px"><br><br>* NOTE: Your order was received and will ship according to the availability notice on product page. </font><br></td>
</tr>
</tbody></table>
<table width="630" align="center" style="border-top:1px solid black">
<tbody><tr>
<td width="630" align="center">
<font color="#333333" style="font-family:Tahoma;font-size:10px">
<span class="il">Instyle</span> <span class="il">New</span> <span class="il">York</span>
230 West 38th Street
<span class="il">New</span> <span class="il">York</span>, NY 10018
PHONE: 212-840-0846 ext 22 EMAIL <a target="_blank" href="mailto:[email protected]">info@<span class="il">company</span>.com</a>
</font>
</td>
</tr>
<tr>
<td width="630" align="center">
<font color="#333333" style="font-family:Tahoma;font-size:10px">
Purchaser agrees to abide by the <a target="_blank" href="#"><span class="il">company</span>.com</a> return policy.
</font>
</td>
</tr>
</tbody></table>
</font>
</td>
<td bgcolor="#efefef"> </td>
</tr>
<tr>
<td><img src="images/newsletter/bottom_left.jpg" class="CToWUd"></td>
<td><img src="images/newsletter/bottom_bg.jpg" class="CToWUd"></td>
<td><img src="images/newsletter/bottom_right.jpg" class="CToWUd"></td>
</tr>
</tbody>
</table>
<br><br>
</td></tr>
</tbody>
</table>';
mail($to,$subject,$message,$headers);
The email in outlook getting the same html code of $message with containing order details..
Thanks
A: If your code doesn't contain a valid <!doctype html> declaration and <body> tags etc, then that could contribute to the problem.
People using Outlook (or other similar mail clients) may have their settings set to not display HTML and images. I have seen that happen quite often before.
*
*This stands at being a local issue and you have no control over that.
Therefore, you need to include a seperate header as TEXT only which is the usual norm when sending mail.
Use Phpmailer or Swiftmailer. That should solve everything.
References:
*
*https://github.com/PHPMailer/PHPMailer
*http://phpmailer.worxware.com/
*http://swiftmailer.org/
and read the documentation on its implementation.
Other options are to use services such as MailChimp, Constant Contact etc. which work well and are services that are used widely and are already setup to handle both HTML and plain text formats.
*
*http://mailchimp.com/
*http://www.constantcontact.com/
| |
doc_2737
|
Window for drawing strips
The x value for all strips are 0, and those strips showed up in the middle of the container. What I really want it to draw the strip so that when the x value is 0, it is proximate to the left side of the container. Any idea about how to achieve this? Thanks.
A: The coordinates of the scene elements are given in the scene coordinate system. Each view transforms the scene coordinates to the view coordinates. You need to set the transformation to map the scene x=0 to view x=0. If the full scene is visible, all it takes is to set proper alignment:
view.setAlignment(Qt::AlignLeft | Qt::AlignTop);
| |
doc_2738
|
from http.server import HTTPServer, BaseHTTPRequestHandler
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write(b'Hello, world!')
def do_POST(self):
content_length = int(self.headers['Content-Length'])
body = self.rfile.read(content_length)
try:
result = json.loads(body, encoding='utf-8')
# Do other stuff with result
p = subprocess.Popen(['/usr/bin/env', 'lp', '-d', printer_queue, temp.name], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
self.send_response(200)
self.end_headers()
response = BytesIO()
response.write(b'POST Received: ')
response.write(body)
self.wfile.write(response.getvalue())
except Exception as err:
tb = traceback.format_exc()
print(tb)
self.send_response(500) # 500 Internal Server Error
self.end_headers()
response = BytesIO()
response.write(b'ERROR: Blah')
self.wfile.write(response.getvalue())
httpd = HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler)
and everything was awesome. Then I read that HTTPServer shouldn't be used in Production and everything was no longer awesome.
So how can I write the equivalent code that can be used as a production server? I have a Apache web server, but I'm not sure how to add the above Python code to it (preferrably without changing the above code too much since there is a lot of it).
A: I found out a way to connect your code with nginx server. At first add some code with your function add create socket and after that write a nginx conf file. it will work
Step 1 :
add main() function in your function
from http.server import HTTPServer, BaseHTTPRequestHandler
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write(b'Hello, world!')
def do_POST(self):
content_length = int(self.headers['Content-Length'])
body = self.rfile.read(content_length)
try:
result = json.loads(body, encoding='utf-8')
# Do other stuff with result
p = subprocess.Popen(['/usr/bin/env', 'lp', '-d', printer_queue, temp.name], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
self.send_response(200)
self.end_headers()
response = BytesIO()
response.write(b'POST Received: ')
response.write(body)
self.wfile.write(response.getvalue())
except Exception as err:
tb = traceback.format_exc()
print(tb)
self.send_response(500) # 500 Internal Server Error
self.end_headers()
response = BytesIO()
response.write(b'ERROR: Blah')
self.wfile.write(response.getvalue())
def main():
try:
server = HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler)
print ('Starting BaseServer.')
server.serve_forever ()
except KeyboardInterrupt:
print ('Interrupt recieved; closing server socket')
server.socket.close()
if __name__ == '__main__':
main()
Step 2 :
nginx.conf file should be like this
server {
location / {
root /data/www;
}
location / {
proxy_pass http://localhost:8000;
}
}
If face any issue comment below
| |
doc_2739
|
I thought I might have some luck with using the Microsoft.Office.Interop.Word.COMAddins and .Addins properties, but the .Addins property gives an empty list and COMAddins is a collection of opaque COM objects.
An alternative question suggests making the ribbon menu invisible, but I actually want to unload the add-in altogether.
A: I had similar requirement and achieved it by little cheat.
I had a addin called AddinLauncher (with no ribbons) which will look for the user type and launch or closes the other addin.
This code was called during AddinLauncher Addin Startup event.
foreach (COMAddIn addin in Globals.ThisAddin.Application.COMAddins)
{
if (**specify your own condition**)
{
addin.Connect = true;
}
}
The following changes are required in your deployment
The Loadbehaviour for AddinLaucher addin is 3 and all the other addins are 0.
More about Loadbehaviour here
| |
doc_2740
|
pls help thanks
It isnt able to take input only as per my debugging. I feel my algorithm is correct and method too but I'm missing something small somewhere or making a silly mistake I'm not able to find.
Help will be appreciated. thanks a lot
#include <iostream>
#include <cstring>
using namespace std;
struct Stack {
int data;
Stack *next;
}*top=NULL,*temp;
void push(int item)
{
Stack *new_node = new Stack;
new_node->data=item;
new_node->next=top;
top=new_node;
}
int pop()
{
int item;
if (top==NULL)
cout<<"stack underflow";
else {
temp=top;
item=top->data;
top=top->next;
free(temp);
}
return item;
}
void evaluate(char postfix)
{
int i,val;
int A, B;
ch - '0' is used for getting digit rather than ASCII code of digit */
if (isdigit(postfix))
push(postfix - '0');
else if (postfix == '+' || postfix == '-' || postfix == '*' || postfix == '/')
{
A = pop();
B = pop();
switch (postfix)
{
case '*': val=B*A; break;
case '/': val=B/A; break;
case '+': val=B+A; break;
case '-': val=B-A; break;
}
push(val);
}
}
int main()
{
int i;
string exp;
getline(cin,exp);
for (i=0;i<exp.length();i++)
evaluate(exp[i]);
cout<<"Value of "<<exp<<" is "<<pop();
return 0;
}
A: Look at the if statement inside your pop function:
if (top=NULL)
cout<<"stack underflow";
else {
temp=top;
item=top->data;
top=top->next;
free(temp);
}
top=NULL always overwrites top with NULL and then takes the else branch (because NULL is false), where top->data will dereference the freshly-assigned null pointer.
Even an input as simple as 5 will trigger this problem, as you use pop() to read the final value.
| |
doc_2741
|
Graphics.cpp
#include <windows.h>
#include <time.h>
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
static HWND hwnd { 0 };
void DrawPixel(HWND hwnd, int x, int y);
int WINAPI
WinMain (HINSTANCE hInstance, HINSTANCE hPrevInst, LPTSTR lpCmdLine, int nShowCmd) {
MSG msg;
WNDCLASSW wc = {0};
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpszClassName = L"Pixels";
wc.hInstance = hInstance;
wc.hbrBackground = GetSysColorBrush(COLOR_3DFACE);
wc.lpfnWndProc = WndProc;
wc.hCursor = LoadCursor(0, IDC_ARROW);
RegisterClassW(&wc);
CreateWindowW(wc.lpszClassName, L"Pixels",
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
100, 100, 300, 250, NULL, NULL, hInstance, NULL);
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
srand(time(NULL));
return (int) msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg,
WPARAM wParam, LPARAM lParam) {
switch(msg) {
case WM_PAINT:
break;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProcW(hwnd, msg, wParam, lParam);
}
void DrawPixel(int x, int y) {
PAINTSTRUCT ps;
RECT r;
GetClientRect(hwnd, &r);
if (r.bottom == 0) {
return;
}
HDC hdc = BeginPaint(hwnd, &ps);
SetPixel(hdc, x, y, RGB(255, 0, 0));
EndPaint(hwnd, &ps);
}
main.cpp
#include <iostream>
#include <windows.h>
#include <windef.h>
void DrawPixel(int x, int y);
int main(){
DrawPixel(100, 100);
}
I am pretty sure it has something to do with the windows handle and how I am retrieving it but no matter how I refactor my code it wont work.
Edit: It turns out the issue is that the WinMain function isnt running.
| |
doc_2742
|
/www/public/pubfiles/myfile.php
I can link to these with no problem. We also have an upload script that by design puts the files in...
/uploads/nonlinkablefile
And then stores the path and a filename, etc. in a db. When someone clicks a link to retrieve these files, a script gets the file and returns it as a download.
The files in the second option are stored this way so they cannot be linked to or shared. We are able to check a users permission on pages or directly on a file to see if they should be able to download.
What I'm wondering now is, if we can do those checks, and then somehow display the files (PDFs moslty) in a new tab in the browser vs. forcing a download.
Since there isn't a web-enable path to the file, I'm not finding a way to do so.
Thanks.
A: You can try with the file() function, instead of a download ask the browser to open the file, i.e.:
return response()->file('/uploads/nonlinkablefile.pdf');
You can find more info in the official documentation.
Obviously the path in which the files are stored should be accessible by the webserver, but the file does not need to be under the public or DocumentRoot directory.
| |
doc_2743
|
A: This doesn't work 100% but it's a starting point, based off my comment:
Main Form:
public Form1()
{
InitializeComponent();
}
private Point _cellClick;
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
var h = dataGridView1.Rows[0].Height;
if (MousePosition.Y % h == 0)
{
_cellClick = new Point(MousePosition.X, MousePosition.Y);
}
else
{
var y = MousePosition.Y;
do
{
y++;
} while (y % h != 0);
_cellClick = new Point(MousePosition.X, y);
}
}
private void button1_Click(object sender, EventArgs e)
{
var f = new Form2(_cellClick);
f.ShowDialog(this);
}
Child Form:
private Point loc;
public Form2(Point location)
{
InitializeComponent();
loc = location;
}
private void Form2_Load(object sender, EventArgs e)
{
this.SetDesktopLocation(loc.X, loc.Y);
}
Edit This is really close to what you're looking for, the only issue is that the child form doesn't show up "adjacent" to the cell, but exactly where the mouse was when they clicked on the cell.
You could probably do some basic arithmetic to figure out the height of a cell to offset MousePosition.Y so that the child form shows up adjacent to it. I think you just need to round the coordinate to the nearest multiple of N, where N is dataGridView1.Rows[0].Height, rounding up.
Edit 2 I just edited the code to try something like this, and now the child form tends to show up just a little bit below the row.
| |
doc_2744
|
import time
from tkinter import *
#This is where "Svar" or in English "answer" is being defined.
def Kalk(event):
if operator.get() == "+":
global Svar
Svar = int(Nummer_1.get()) + int(Nummer_2.get())
Answer(event)
elif operator.get() == "-":
Svar = int(Nummer_1.get()) - int(Nummer_2.get())
Answer(event)
elif operator.get() == "*":
Svar = int(Nummer_1.get()) * int(Nummer_2.get())
Answer(event)
elif operator.get() == "/":
Svar = int(Nummer_1.get()) / int(Nummer_2.get())
Answer(event)
else:
Svar = ("Vennligst velg et av alternativene overfor")
Answer(event)
#This is where it displays "Svar" which is "answer".
def Answer(event):
#I want this label("Label_4") to be reset so when I run this def again the numbers won't stack
label_4 = Label(topFrame, text=Svar)
label_4.grid(row=6)
print(Svar)
kalkis = Tk()
kalkis.geometry("300x250")
kalkis.title("Kalkulator")
topFrame = Frame(kalkis)
topFrame.grid(row=0)
label = Label(topFrame, text="Du kan velge mellom '+', '-', '*'. '/' ")
label.grid(row=0)
operator = Entry(topFrame)
operator.grid(row=1)
label_2 = Label(topFrame, text="Skriv inn hvilket tall du vil bruke ")
label_2.grid(row=2)
Nummer_1 = Entry(topFrame)
#Nummer_1 = int(answer.get())
Nummer_1.grid(row=3)
Label_3 = Label(topFrame, text="Skriv inn ditt andre tall ")
Label_3.grid(row=4)
Nummer_2 = Entry(topFrame)
#Nummer_2 = int(answer.get())
Nummer_2.grid(row=5)
#Nummer_2.bind("<Return>", Kalk())
Refresh = Button(topFrame, text="Enter", command=kalkis)
Refresh.bind("<Enter>", Kalk)
Refresh.grid(row=6, column=1, sticky=W)
#Refresh.bind("<Return>", Kalk())
kalkis.mainloop()
A: An easy way to change a Label() is to associate it to a textvariable of type StringVar(). Any updates to the textvariable will propagate to the label. Eg.
display_text = StringVar()
label_4 = Label(topFrame, textvariable=display_text)
The function Answer() creates a new label each time it is called. Instead just create the label one time and then update the textvariable for each calculation.
import time
from tkinter import *
#This is where "Svar" or in English "answer" is being defined.
def Kalk(event):
if operator.get() == "+":
Svar = int(Nummer_1.get()) + int(Nummer_2.get())
display_text.set(str(Svar)) # Update textvariable
elif operator.get() == "-":
Svar = int(Nummer_1.get()) - int(Nummer_2.get())
display_text.set(str(Svar)) # Update textvariable
elif operator.get() == "*":
Svar = int(Nummer_1.get()) * int(Nummer_2.get())
display_text.set(str(Svar)) # Update textvariable
elif operator.get() == "/":
Svar = int(Nummer_1.get()) / int(Nummer_2.get())
display_text.set(str(Svar)) # Update textvariable
else:
Svar = ("Vennligst velg et av alternativene overfor")
display_text.set(Svar) # Update textvariable
kalkis = Tk()
kalkis.geometry("300x250")
kalkis.title("Kalkulator")
topFrame = Frame(kalkis)
topFrame.grid(row=0)
label = Label(topFrame, text="Du kan velge mellom '+', '-', '*'. '/' ")
label.grid(row=0)
operator = Entry(topFrame)
operator.grid(row=1)
label_2 = Label(topFrame, text="Skriv inn hvilket tall du vil bruke ")
label_2.grid(row=2)
Nummer_1 = Entry(topFrame)
Nummer_1.grid(row=3)
Label_3 = Label(topFrame, text="Skriv inn ditt andre tall ")
Label_3.grid(row=4)
Nummer_2 = Entry(topFrame)
Nummer_2.grid(row=5)
# This is where it displays "Svar" which is "answer".
display_text = StringVar() # Create a StringVar() to hold the result
label_4 = Label(topFrame, textvariable=display_text) # Associate to label
label_4.grid(row=6)
Refresh = Button(topFrame, text="Enter", command=kalkis)
Refresh.bind("<Enter>", Kalk)
Refresh.grid(row=6, column=1, sticky=W)
kalkis.mainloop()
| |
doc_2745
|
I have a large project with a structure like this:
- data_prep
- dataset
- dataset_1
- helper.py
- dataset_2
- data_postproc
- helper
- misc.py
- array_transform.py
- ...
- visualizations
- ... [more subfolders]
Notice how I have a file called helper.py in my folder structure. However, I also have a folder with a similar name. My IDE flags this as inappropriate because it can cause confusion I guess.
The reason I have this additional helper.py file is because there are some file operations for specific datasets. I dont want to clutter my more general helper-files with these functions, hence the separate file.
The question is: is this way of organizing your code a clear way? How do other organizations/projects deal with an issue like this?
Or does it all boil down to writing proper documentation and then you can do whatever you like?
Then my last question: where can I learn about these kind of code-organization problems? I don't have any solid resource for this and I have the idea that it is very company-dependent on what is acceptable.
| |
doc_2746
|
A: Try something like this -
CREATE TABLE #Tmp_test(col NVARCHAR(1000));
INSERT INTO #Tmp_test(col) VALUES (N'My data has ')
,(N'My data has ')
,(N'My data has ')
,(N'No emoji');
SELECT COUNT(1)
FROM #Tmp_test WHERE CAST(col AS varchar(100)) != col;
| |
doc_2747
|
Only the background.js has the ability to read those headers (from what I've understood, tell me if I'm wrong).
This extension is in devtools (F12), here is an extract from my manifest :
"devtools_page": "devtools.html",
"permissions": [
"webRequest", "<all_urls>"
],
this devtool.html has a devtool.js that calls :
chrome.devtools.panels.create('test', '/icon.png', '/panel.html', function(extensionPanel) {
...
}
so that I have a panel.html (containing a panel.js), representing the interface.
The question is : How can I emit messages from the background.js to the panel.js ?
What works so far : The panel is visible in the devtools, my html and scripts from panel.html and panel.js are as expected. I know how to get the devtool's console (CTRL + SHIFT + "I" or "J" while focusing the devtools) in order to debug.
Note : Only the devtool.js and panel.js have their console.log() recorded in this console. I couldn't find where the background.js sends his console.log().
I've tested everything from https://developer.chrome.com/extensions/messaging#simple , maybe I did them wrong. I can't find how to do this.
Thanks you for your help.
A: I have solved my problem.
It's not the way it work : background.js is useless.
In panel.js, I can call
chrome.devtools.network.onRequestFinished.addListener(
function(request) {
which gives access to those headers informations :
console.log(request.time);
console.log(request.request.url);
console.log(request.request.queryString[2]);
console.log(request.response.status);
console.log(request.response.headers[3]);
| |
doc_2748
|
is there a way to draw a line or something like this using opengl directly inside the UIViewController?
thanks in advance
A: Are you sure about the OpenGL?
I believe it will be impossible to use OpenGL above regular views.
You might add a custom view (inherit from UIView) above all the other views and draw anything you want on that view.
This view should have a transparent background color.
In addition, if you want to interact with the other views (tap buttons, edit text views, scroll etc.) then you will have to implement the hitTest method in your custom view in order to pass the touch event to the views that are located under this one...
EDIT: Don't mess with the hitTest. Just uncheck the User Interaction Enabled in the XIB...
EDIT: Code sample:
@interface TransparentDrawingView : UIView {
CGPoint fromPoint;
CGPoint toPoint;
}
- (void)drawLineFrom:(CGPoint)from to:(CGPoint)to;
@end
@implementation TransparentDrawingView
- (void)initObject {
// Initialization code
[super setBackgroundColor:[UIColor clearColor]];
}
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
// Initialization code
[self initObject];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aCoder {
if (self = [super initWithCoder:aCoder]) {
// Initialization code
[self initObject];
}
return self;
}
- (void)drawRect:(CGRect)rect {
// Drawing code
// Draw a line from 'fromPoint' to 'toPoint'
}
- (void)drawLineFrom:(CGPoint)from to:(CGPoint)to {
fromPoint = from;
toPoint = to;
// Refresh
[self setNeedsDisplay];
}
@end
A: First I think you should know responsibilities of UIView and UIViewController.
UIView is mainly responsible for drawing (override touchBegin, ToucheMove, etc.), animating, manage subviews, and handle event; UIViewController is mainly responsible for loading, unloading views etc.
So, you should 'draw' this line at your customized view (UIView), not view controller.
Second: If you only need to display some simple shapes or lines. I suggest you use UI controls and images. Even 'drawRect' is not recommended since it will cause more resources used. Surely OpenGL need much resources.
A: The answer is quite simple, you have to create a new class extending UIView, and override the drawRect function in order to draw (with Quartz...) your line. Use this method if you want gradient background as well.
I am also developping with Adobe Flex 4, and I notice that iPhone SDK has no Skin and Layout "patterns" like Flex 4 does (for instance, UIView could have a Skin (in a separate file..) and a Layout (horizontal, Vertical, Tile....)), for me that is a terrible lack!
Its something that the open source library Three20 tries to bring to the iPhone SDK.
| |
doc_2749
|
When I test my app, it works fine(I have a iPhone 4s Ios 5.1 in the Netherlands), but when I upload it to the appstore for review it's denied. They say the camera view doesn't work, and that they get just a black screen.
I really don't know what to do, because it works fine for me. I can't reproduce the error.
Is there someone who had the same problem like me? Or someone who knows what to do?
A: You don't say whether you use OpenGL ES 2.0 to do this, but if you do, it's possible they tested your application on an iPhone 3G, which lacks 2.0 support. You can filter out those unsupported devices by adding the opengles-2 key to your UIRequiredDeviceCapabilities in your Info.plist.
A second possibility is that you are trying to display an image from your camera that exceeds the max OpenGL ES texture size of the tester's device. You can check this size, but on devices older than the iPad 2, this max texture size is 2048x2048. On the iPad 2, new Retina iPad, and iPhone 4S, that texture size is 4096x4096. The iPhone 4 can capture images that are more than 2048 pixels wide, which might explain why your camera view works on your iPhone 4S, but shows a black image on older hardware.
There's also a remote possibility that you're using an OpenGL ES extension that doesn't exist on that older hardware, but I don't think any of the recent additions in the A5 chips would be useful for image processing. I think the newer hardware also supports a greater number of texture units, attributes, and varyings, but I'd need to check on that.
This is why I always try to test on the oldest hardware that has the minimum capabilities I need in my applications, because there are subtle variations in the way the different device GPUs handle things.
A: I did not inlcude the framework, on an iphone 4s this was not necessary, it was on an iphone 4...
| |
doc_2750
|
Here's an example of my histograms
A: To set bar width you need to set pointWidth
A pixel value specifying a fixed width for each column or bar. When null, the width is calculated from the pointPadding and groupPadding.
You can't set the distance between the bars the same without resizing what you see. That means you either have to set the size of the highcharts div appropriately, or you need to set min and max for the chart so that the same number of bars will be in each histogram.
| |
doc_2751
|
You can see demo of what Issues having. when scroll to last menu that time having problem(which show in GIF Image Demo)
Here Link where get all HTML/CSS/JS https://drive.google.com/drive/folders/0B6tYK76Lu9DkWnlMM2g2SXUyZkE
HTML CODE which I am trying for that
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>SB Admin - Bootstrap Admin Template</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<link href="css/hover.css" rel="stylesheet">
<link rel="stylesheet" href="css/bootstrap-dropdownhover.css">
<link href="http://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">
<!-- custom scrollbar stylesheet -->
<link rel="stylesheet" href="css/jquery.mCustomScrollbar.css">
<!-- Custom CSS -->
<link href="css/sb-admin.css" rel="stylesheet">
<link href="css/font.css" rel="stylesheet">
<!-- Morris Charts CSS -->
<link href="css/plugins/morris.css" rel="stylesheet">
<link rel="stylesheet" href="css/fm.scrollator.jquery.css" />
<!-- Custom Fonts -->
<link href="css/font-awesome.css" rel="stylesheet" type="text/css">
<link href='http://fonts.googleapis.com/css?family=Lato&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/bootstrap-dropdownhover.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<style>
.verticle-menu {width: 100%; float: left;}
.verticle-menu #info {font-size: 18px; color: #555; text-align: center; margin-bottom: 25px;}
.verticle-menu a { color: #000000; font-size: 12px; text-transform: uppercase;}
.verticle-menu .scrollbar {margin-left: 0px; float: left; /*height: 700px;*/ background: #fff; overflow-y: scroll; margin-bottom: 0px; width: 100%;}
.verticle-menu .force-overflow {min-height: 450px; border-right: 1px solid #cccccc; height: 100%;}
.verticle-menu #wrapper {text-align: center; width: 500px; margin: auto;}
.verticle-menu #style-3::-webkit-scrollbar-track {background-color: #fff;}
.verticle-menu #style-3::-webkit-scrollbar {width: 6px; background-color: #fff;}
.verticle-menu #style-3::-webkit-scrollbar-thumb {background-color: #fff;}
.verticle-menu .wrapper {position: relative;}
.verticle-menu ul {width: 100%; overflow-x: hidden; overflow-y: auto;}
.verticle-menu ul {color: white; font-family: sans-serif; font-size: 16px; padding: 0;}
.verticle-menu li {position: static; list-style: none;}
.verticle-menu li .wrapper {position: absolute; z-index: 10; display: none; left: 100% !important;}
.verticle-menu li:hover > .wrapper {display: block;}
.verticle-menu li {line-height: 34px; border-bottom: 1px solid #cccccc; font-size: 12px; padding: 0px 5px;}
.verticle-menu li ul {margin: 0;}
.verticle-menu li span {color: #000;}
.verticle-menu li .wrapper {cursor: auto; border: 1px solid #cccccc; margin-left: -1px; width: 100%; margin-top: -1px; -webkit-border-radius: 0px; -moz-border-radius: 0px; border-radius: 0px; padding:0px; border-bottom:none;}
.verticle-menu li .wrapper li {line-height: 34px; border-bottom: 1px solid #cccccc; font-size: 12px; padding: 0px 7px;}
.verticle-menu li .wrapper li a:hover {color: #F70004;}
.verticle-menu li:nth-child(2n) {background: #fff;}
.verticle-menu li:nth-child(2n+1) {background: #fff;}
.verticle-menu li.parent {cursor: pointer;}
#scrollable_div1 {height: 700px; width: 100%; overflow: auto; background-color: #fff; border: 1px solid #cccccc;}
.topcls{top: auto !important;}
</style>
</head>
<body>
<div>
<!-- Navigation -->
<div class="col-lg-12 padding0">
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<h4 style="color:#fff; text-transform:uppercase;display:block; text-align:center;">HEADER</h4>
</nav>
</div>
<div class="clearfix"></div>
<div class="col-lg-12 padding0">
<!-- Sidebar Menu Items - These collapse to the responsive navigation menu on small screens -->
<div style="width:12%; float:left; z-index:2; position:fixed;">
<div class="verticle-menu">
<div id="scrollable_div1">
<div>
<ul>
<li class="parent">
<span class="main-icon"> </span>
<span>Menu 01</span>
<div class="wrapper">
<ul>
<li><a href="#" tabindex="-1">Menu 01</a></li>
<li><a href="#" tabindex="-1">Menu 02</a></li>
<li><a href="#" tabindex="-1">Menu 03</a></li>
<li><a href="#" tabindex="-1">Menu 04</a></li>
<li><a href="#" tabindex="-1">Menu 05</a></li>
</ul>
</div>
</li>
<li class="parent">
<span class="main-icon"> </span>
<span>Menu 02</span>
<div class="wrapper">
<ul>
<li><a href="#" tabindex="-1">Menu 01</a></li>
<li><a href="#" tabindex="-1">Menu 02</a></li>
<li><a href="#" tabindex="-1">Menu 03</a></li>
<li><a href="#" tabindex="-1">Menu 04</a></li>
<li><a href="#" tabindex="-1">Menu 05</a></li>
</ul>
</div>
</li>
<li class="parent">
<a href="#">
<span class="main-icon"> </span>
<span>Menu 03</span>
</a>
<div class="wrapper">
<ul>
<li><a href="#" tabindex="-1">Menu 01</a></li>
<li><a href="#" tabindex="-1">Menu 02</a></li>
<li><a href="#" tabindex="-1">Menu 03</a></li>
<li><a href="#" tabindex="-1">Menu 04</a></li>
<li><a href="#" tabindex="-1">Menu 05</a></li>
</ul>
</div>
</li>
<li class="parent">
<a href="#">
<span class="main-icon"> </span>
<span>Menu 04</span>
</a>
<div class="wrapper">
<ul>
<li><a href="#" tabindex="-1">Menu 01</a></li>
<li><a href="#" tabindex="-1">Menu 02</a></li>
<li><a href="#" tabindex="-1">Menu 03</a></li>
<li><a href="#" tabindex="-1">Menu 04</a></li>
<li><a href="#" tabindex="-1">Menu 05</a></li>
</ul>
</div>
</li>
<li class="parent">
<a href="#">
<span class="main-icon"> </span>
<span>Menu 05</span>
</a>
<div class="wrapper">
<ul>
<li><a href="#" tabindex="-1">Menu 01</a></li>
<li><a href="#" tabindex="-1">Menu 02</a></li>
<li><a href="#" tabindex="-1">Menu 03</a></li>
<li><a href="#" tabindex="-1">Menu 04</a></li>
<li><a href="#" tabindex="-1">Menu 05</a></li>
</ul>
</div>
</li>
<li class="parent">
<a href="#">
<span class="main-icon"> </span>
<span>Menu 06</span>
</a>
<div class="wrapper">
<ul>
<li><a href="#" tabindex="-1">Menu 01</a></li>
<li><a href="#" tabindex="-1">Menu 02</a></li>
<li><a href="#" tabindex="-1">Menu 03</a></li>
<li><a href="#" tabindex="-1">Menu 04</a></li>
<li><a href="#" tabindex="-1">Menu 05</a></li>
</ul>
</div>
</li>
<li class="parent">
<a href="#">
<span class="main-icon"> </span>
<span>Menu 07</span>
</a>
<div class="wrapper">
<ul>
<li><a href="#" tabindex="-1">Menu 01</a></li>
<li><a href="#" tabindex="-1">Menu 02</a></li>
<li><a href="#" tabindex="-1">Menu 03</a></li>
<li><a href="#" tabindex="-1">Menu 04</a></li>
<li><a href="#" tabindex="-1">Menu 05</a></li>
</ul>
</div>
</li>
<li class="parent">
<a href="#">
<span class="main-icon"> </span>
<span>Menu 08</span>
</a>
<div class="wrapper">
<ul>
<li><a href="#" tabindex="-1">Menu 01</a></li>
<li><a href="#" tabindex="-1">Menu 02</a></li>
<li><a href="#" tabindex="-1">Menu 03</a></li>
<li><a href="#" tabindex="-1">Menu 04</a></li>
<li><a href="#" tabindex="-1">Menu 05</a></li>
</ul>
</div>
</li>
<li class="parent">
<a href="#">
<span class="main-icon"> </span>
<span>Menu 09</span>
</a>
<div class="wrapper">
<ul>
<li><a href="#" tabindex="-1">Menu 01</a></li>
<li><a href="#" tabindex="-1">Menu 02</a></li>
<li><a href="#" tabindex="-1">Menu 03</a></li>
<li><a href="#" tabindex="-1">Menu 04</a></li>
<li><a href="#" tabindex="-1">Menu 05</a></li>
</ul>
</div>
</li>
<li class="parent">
<a href="#">
<span class="main-icon"> </span>
<span>Menu 10</span>
</a>
<div class="wrapper">
<ul>
<li><a href="#" tabindex="-1">Menu 01</a></li>
<li><a href="#" tabindex="-1">Menu 02</a></li>
<li><a href="#" tabindex="-1">Menu 03</a></li>
<li><a href="#" tabindex="-1">Menu 04</a></li>
<li><a href="#" tabindex="-1">Menu 05</a></li>
</ul>
</div>
</li>
<li class="parent">
<a href="#">
<span class="main-icon"> </span>
<span>Menu 11</span>
</a>
<div class="wrapper">
<ul>
<li><a href="#" tabindex="-1">Menu 01</a></li>
<li><a href="#" tabindex="-1">Menu 02</a></li>
<li><a href="#" tabindex="-1">Menu 03</a></li>
<li><a href="#" tabindex="-1">Menu 04</a></li>
<li><a href="#" tabindex="-1">Menu 05</a></li>
</ul>
</div>
</li>
<li class="parent">
<a href="#">
<span class="main-icon"> </span>
<span>Menu 12</span>
</a>
<div class="wrapper">
<ul>
<li><a href="#" tabindex="-1">Menu 01</a></li>
<li><a href="#" tabindex="-1">Menu 02</a></li>
<li><a href="#" tabindex="-1">Menu 03</a></li>
<li><a href="#" tabindex="-1">Menu 04</a></li>
<li><a href="#" tabindex="-1">Menu 05</a></li>
</ul>
</div>
</li>
<li class="parent">
<a href="#">
<span class="main-icon"> </span>
<span>Menu 13</span>
</a>
<div class="wrapper">
<ul>
<li><a href="#" tabindex="-1">Menu 01</a></li>
<li><a href="#" tabindex="-1">Menu 02</a></li>
<li><a href="#" tabindex="-1">Menu 03</a></li>
<li><a href="#" tabindex="-1">Menu 04</a></li>
<li><a href="#" tabindex="-1">Menu 05</a></li>
</ul>
</div>
</li>
<li class="parent">
<a href="#">
<span class="main-icon"> </span>
<span>Menu 14</span>
</a>
<div class="wrapper">
<ul>
<li><a href="#" tabindex="-1">Menu 01</a></li>
<li><a href="#" tabindex="-1">Menu 02</a></li>
<li><a href="#" tabindex="-1">Menu 03</a></li>
<li><a href="#" tabindex="-1">Menu 04</a></li>
<li><a href="#" tabindex="-1">Menu 05</a></li>
</ul>
</div>
</li>
<li class="parent">
<a href="#">
<span class="main-icon"> </span>
<span>Menu 15</span>
</a>
<div class="wrapper">
<ul>
<li><a href="#" tabindex="-1">Menu 01</a></li>
<li><a href="#" tabindex="-1">Menu 02</a></li>
<li><a href="#" tabindex="-1">Menu 03</a></li>
<li><a href="#" tabindex="-1">Menu 04</a></li>
<li><a href="#" tabindex="-1">Menu 05</a></li>
</ul>
</div>
</li>
<li class="parent">
<a href="#">
<span class="main-icon"> </span>
<span>Menu 16</span>
</a>
<div class="wrapper">
<ul>
<li><a href="#" tabindex="-1">Menu 01</a></li>
<li><a href="#" tabindex="-1">Menu 02</a></li>
<li><a href="#" tabindex="-1">Menu 03</a></li>
<li><a href="#" tabindex="-1">Menu 04</a></li>
<li><a href="#" tabindex="-1">Menu 05</a></li>
</ul>
</div>
</li>
<li class="parent">
<a href="#">
<span class="main-icon"> </span>
<span>Menu 17</span>
</a>
<div class="wrapper">
<ul>
<li><a href="#" tabindex="-1">Menu 01</a></li>
<li><a href="#" tabindex="-1">Menu 02</a></li>
<li><a href="#" tabindex="-1">Menu 03</a></li>
<li><a href="#" tabindex="-1">Menu 04</a></li>
<li><a href="#" tabindex="-1">Menu 05</a></li>
</ul>
</div>
</li>
<li class="parent">
<a href="#">
<span class="main-icon"> </span>
<span>Menu 18</span>
</a>
<div class="wrapper">
<ul>
<li><a href="#" tabindex="-1">Menu 01</a></li>
<li><a href="#" tabindex="-1">Menu 02</a></li>
<li><a href="#" tabindex="-1">Menu 03</a></li>
<li><a href="#" tabindex="-1">Menu 04</a></li>
<li><a href="#" tabindex="-1">Menu 05</a></li>
</ul>
</div>
</li>
<li class="parent">
<a href="#">
<span class="main-icon"> </span>
<span>Menu 19</span>
</a>
<div class="wrapper">
<ul>
<li><a href="#" tabindex="-1">Menu 01</a></li>
<li><a href="#" tabindex="-1">Menu 02</a></li>
<li><a href="#" tabindex="-1">Menu 03</a></li>
<li><a href="#" tabindex="-1">Menu 04</a></li>
<li><a href="#" tabindex="-1">Menu 05</a></li>
</ul>
</div>
</li>
<li class="parent">
<a href="#">
<span class="main-icon"> </span>
<span>Menu 20</span>
</a>
<div class="wrapper">
<ul>
<li><a href="#" tabindex="-1">Menu 01</a></li>
<li><a href="#" tabindex="-1">Menu 02</a></li>
<li><a href="#" tabindex="-1">Menu 03</a></li>
<li><a href="#" tabindex="-1">Menu 04</a></li>
<li><a href="#" tabindex="-1">Menu 05</a></li>
</ul>
</div>
</li>
<li class="parent">
<a href="#">
<span class="main-icon"> </span>
<span>Menu 21</span>
</a>
<div class="wrapper">
<ul>
<li><a href="#" tabindex="-1">Menu 01</a></li>
<li><a href="#" tabindex="-1">Menu 02</a></li>
<li><a href="#" tabindex="-1">Menu 03</a></li>
<li><a href="#" tabindex="-1">Menu 04</a></li>
<li><a href="#" tabindex="-1">Menu 05</a></li>
</ul>
</div>
</li>
<li class="parent">
<a href="#">
<span class="main-icon"> </span>
<span>Menu 22</span>
</a>
<div class="wrapper">
<ul>
<li><a href="#" tabindex="-1">Menu 01</a></li>
<li><a href="#" tabindex="-1">Menu 02</a></li>
<li><a href="#" tabindex="-1">Menu 03</a></li>
<li><a href="#" tabindex="-1">Menu 04</a></li>
<li><a href="#" tabindex="-1">Menu 05</a></li>
</ul>
</div>
</li>
<li class="parent">
<a href="#">
<span class="main-icon"> </span>
<span>Menu 23</span>
</a>
<div class="wrapper">
<ul>
<li><a href="#" tabindex="-1">Menu 01</a></li>
<li><a href="#" tabindex="-1">Menu 02</a></li>
<li><a href="#" tabindex="-1">Menu 03</a></li>
<li><a href="#" tabindex="-1">Menu 04</a></li>
<li><a href="#" tabindex="-1">Menu 05</a></li>
</ul>
</div>
</li>
<li class="parent">
<a href="#">
<span class="main-icon"> </span>
<span>Menu 24</span>
</a>
<div class="wrapper">
<ul>
<li><a href="#" tabindex="-1">Menu 01</a></li>
<li><a href="#" tabindex="-1">Menu 02</a></li>
<li><a href="#" tabindex="-1">Menu 03</a></li>
<li><a href="#" tabindex="-1">Menu 04</a></li>
<li><a href="#" tabindex="-1">Menu 05</a></li>
</ul>
</div>
</li>
<li class="parent">
<a href="#">
<span class="main-icon"> </span>
<span>Menu 25</span>
</a>
<div class="wrapper">
<ul>
<li><a href="#" tabindex="-1">Menu 01</a></li>
<li><a href="#" tabindex="-1">Menu 02</a></li>
<li><a href="#" tabindex="-1">Menu 03</a></li>
<li><a href="#" tabindex="-1">Menu 04</a></li>
<li><a href="#" tabindex="-1">Menu 05</a></li>
</ul>
</div>
</li>
<li class="parent dropdown dropdown-inline">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown">
<span class="main-icon"> </span>
<span>Menu 26</span>
</a>
<div class="wrapper dropdown-menu">
<ul>
<li><a href="#" tabindex="-1">Menu 01</a></li>
<li><a href="#" tabindex="-1">Menu 02</a></li>
<li><a href="#" tabindex="-1">Menu 03</a></li>
<li><a href="#" tabindex="-1">Menu 04</a></li>
<li><a href="#" tabindex="-1">Menu 05</a></li>
</ul>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
<!-- /.navbar-collapse -->
<div id="page-wrapper" style="width:88%; float:left; z-index:0; position:absolute; right:0;">
<div class="container-fluid">
// Contain which i removed
</div>
<!-- /.container-fluid -->
</div>
</div>
</div>
<!-- /#wrapper -->
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
<script src="js/index.js"></script>
<script src="js/jquery-1.11.0.min.js"></script>
<script src="js/fm.scrollator.jquery.js"></script>
<script src="js/bootstrap-dropdownhover.js"></script>
<script>
(function ($) {
$(window).resize(function () {
$('#scrollable_div1').height($(window).height() - 52);
});
$(window).on("load", function () {
$('#scrollable_div1').height($(window).height() - 52);
$('#scrollable_div1').scrollator();
});
})(jQuery);
</script>
</body>
</html>
Thank you advance.
| |
doc_2752
|
my current code is accumulating all the data instead of starting from scratch each time it loops thru. First loop, use all the csv files in 0th index, second loop, use all the csv files in the 1st index - but dont accumulate
path = "C:/DataFolder/"
allFiles = glob.glob(path + "/*.csv")
fileChunks = [['2003.csv','2004.csv','2005.csv'],['2006.csv','2007.csv','2008.csv']]
for i in range(len(fileChunks)):
"""move empty dataframe here"""
df = pd.DataFrame()
for file_ in fileChunks[i]:
df_temp = pd.read_csv(file_, index_col = None, names = names, parse_dates=True)
df = df.append(df_temp)
note: fileChunks is derived from a function, and it spits out a list of lists like the example above
any help to documentation or pointing out my error would be great - I want to learn from this. thank you.
EDIT
It seems that moving the empty dataframe to within the first for loop works.
A: This should unnest your files and read each separately using a list comprehension, and then join them all using concat. This is much more efficient than appending each read to a growing dataframe.
df = pd.concat([pd.read_csv(file_, index_col=None, names=names, parse_dates=True)
for chunk in fileChunks for file_ in chunk],
ignore_index=True)
>>> [file_ for chunk in fileChunks for file_ in chunk]
['2003.csv', '2004.csv', '2005.csv', '2006.csv', '2007.csv', '2008.csv']
| |
doc_2753
|
from splinter import browser
ImportError: No module named 'splinter'
now, I installed it via git, and ensured the dist-packages was created. I've tried python 2.7 and 3. Now lately, I'm using the following:
#!/usr/bin/env python2 (get errors when changing to 3 as well)
import splinter
def navigate_to(web_page, how_long):
b = splinter.Browser()
b.visit(web_page)
which gives the following
Traceback (most recent call last):
File "./hw", line 30, in <module>
navigate_to(platform_int, 60)
File "./hw", line 23, in navigate_to
b = splinter.Browser()
File "build/bdist.linux-x86_64/egg/splinter/browser.py", line 63, in Browser
File "build/bdist.linux-x86_64/egg/splinter/driver/webdriver/firefox.py", line 49, in __init__
File "/usr/local/lib/python2.7/dist-packages/selenium-3.3.1-py2.7.egg/selenium/webdriver/firefox/webdriver.py", line 145, in __init__
self.service.start()
File "/usr/local/lib/python2.7/dist-packages/selenium-3.3.1-py2.7.egg/selenium/webdriver/common/service.py", line 74, in start
stdout=self.log_file, stderr=self.log_file)
File "/usr/lib/python2.7/subprocess.py", line 390, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1024, in _execute_child
raise child_exception
OSError: [Errno 8] Exec format error
Help?!
| |
doc_2754
|
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void startRecording(int resultCode, Intent data) {
Log.v(TAG, "Starting recording...");
MediaProjectionManager mProjectionManager = (MediaProjectionManager) getApplicationContext().getSystemService (Context.MEDIA_PROJECTION_SERVICE);
mMediaRecorder = new MediaRecorder();
mMediaRecorder.setOnErrorListener(this::onRecorderError);
mMediaRecorder.setOnInfoListener(this::onRecorderInfo);
DisplayMetrics metrics = new DisplayMetrics();
WindowManager wm = (WindowManager) getApplicationContext().getSystemService(WINDOW_SERVICE);
wm.getDefaultDisplay().getRealMetrics(metrics);
int mScreenDensity = metrics.densityDpi;
int displayWidth = metrics.widthPixels;
int displayHeight = metrics.heightPixels;
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mMediaRecorder.setVideoEncodingBitRate(8 * 1000 * 1000);
mMediaRecorder.setVideoFrameRate(15);
mMediaRecorder.setVideoSize(displayWidth, displayHeight);
Log.v(TAG, "Recorder parameters done");
String videoDir = Environment.getExternalStoragePublicDirectory(DIRECTORY_MOVIES).getAbsolutePath();
Long timestamp = System.currentTimeMillis();
String orientation = "portrait";
if( displayWidth > displayHeight ) {
orientation = "landscape";
}
String filePathAndName = videoDir + "/time_" + timestamp.toString() + "_mode_" + orientation + ".mp4";
mMediaRecorder.setOutputFile( filePathAndName );
Log.v(TAG, "Recorder output path done, prepairing...");
try {
mMediaRecorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.v(TAG, "Recorder prepaired");
Surface surface = mMediaRecorder.getSurface(); //Stops here
Log.v(TAG, "Surface ready");
mMediaProjection = mProjectionManager.getMediaProjection(resultCode, data);
Log.v(TAG, "Media projection ready");
mVirtualDisplay = mMediaProjection.createVirtualDisplay("MainActivity",
displayWidth, displayHeight, mScreenDensity, VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
surface, null, null);
Log.v(TAG, "Display ready");
mMediaRecorder.start();
Log.v(TAG, "Started recording");
}
But when i call mMediaRecorder.getSurface(), activity just stops completly, no exceptions, no callbacks from mMediaRecorder, not even calling onDestory() of my service, but the app itself keeps running
It is as if service just stops working at all
What am i doing wrong? I am testing on android 9.1.0.181C10 HUAWEI LLD-L31
A: Not exact one but I might have seen similar problem while investigating the cause of strange crashes around MediaCodec, which occurred only on some Huawei, Samsung and Motorola devices.
Long story short, it was due to laziness. It takes time for MediaCodec to get ready on those devices. Trying to let it run too quickly, underlying system module falls into infinite loop and gets terminated forcibly.
If you could find LogCat exhausting some lines containing "libstagefright_foundation.so" or "__ubsan_handle_mul_overflow_minimal_abort", that would be. Then, try inserting a little delay e.g. Thread.sleep(100) after the MediaRecorder.prepare() for workaround.
A: Turns out problem was in app permissions. Since i was deleting and installing it several times, app permissions were reset, and application lost its file access permission. When i enabled it in settings, it worked as intended
| |
doc_2755
|
*
*Lib #1 runs with JiBX Runtime 1.0.1
*Lib #2 runs with JiBX Runtime 1.2.6
The current version number is coded in the interface : org.jibx.runtime.IBindingFactory#CURRENT_VERSION_NUMBER .
When calling org.jibx.runtime.BindingDirectory#getFactory(), there's a compatibility test.
If the generated class and the runtime are incompatible, we got an exception like this :
Caused by: org.jibx.runtime.JiBXException: Binding information for
class Xxxx must be
regenerated with current binding compiler at
org.jibx.runtime.BindingDirectory.getFactoryFromName(Unknown Source)
at org.jibx.runtime.BindingDirectory.getFactory(Unknown Source)
EDIT - 29/07/2015
Another possible exception :
Caused by: org.jibx.runtime.JiBXException: Binding information for
class
Yyyyy must
be recompiled with current binding compiler (compiled with jibx_1_0_1,
runtime is jibx_1_2_5_SNAPSHOT) at
org.jibx.runtime.BindingDirectory.getFactoryFromName(BindingDirectory.java:125)
at
org.jibx.runtime.BindingDirectory.getFactory(BindingDirectory.java:178)
at
org.jibx.runtime.BindingDirectory.getFactory(BindingDirectory.java:197)
Is it possible to make it work ?
I've looked at the doc about JiBX Runtime but didn't found anything.
JiBX Runtime on Maven Central Repo.
| |
doc_2756
|
Say for instance, my image is stored in a variable called flowers as seen in the below javascript code:
<script>
var flowers = "myFlowers.gif";
</script>
In the following HTML code, I reference the flowers variable in my img src in order to display the image but cant seem to get this to work.
<img src= flowers class="card-img-top" id="flowers">
Please help, What am I doing wrong?
A: You can't insert it directly like that. Instead you set the attribute src through javascript.
let flowers = "https://picsum.photos/200/300";
document.querySelector('#flowers').src = flowers;
<img class="card-img-top" id="flowers">
| |
doc_2757
|
A: Math.round(argument) returns a number that is rounded from the argument.
In your example you ignore the returned value.
You probably meant to write:
odleglosc = Math.round(odleglosc);
A: x = Math.round(x);
Otherwise if you just write Math.round(x);
Java will make the calculation and have no variable to assign it to, and gets thrown away.
A: Math.round() does not modify your variable because a double the value is passed to the function (compare all-by-value vs call-by-reference).
To round your value use
a = Math.round(a);
| |
doc_2758
|
A: The main problem I had with jarsign taking too long (on Linux, at least) was the kernel entropy pool drying up. At this point, the process blocks until more entropy arrives. This leads to the symptoms you are seeing of the jarsigner process sitting there not eating CPU time but not doing much either.
At some point (from 1.5 to 1.6 AFAIK), Java went from using /dev/urandom to /dev/random. Real entropy is actually a scarce resource on modern computers - lots of RAM decreases disk activity, smart programs that cache things decrease network activity. I'm told that on a virtual machine (like many build servers live on) that entropy collection rates can be even lower.
You can either
*
*Reconfigure Java back to using /dev/urandom (if you're not paranoid)
*Deploy a means of injecting additional entropy into /dev/random
I went for option B : I installed the randomsound package for my chosen distro (Ubuntu). This samples your mike for whitenoise and uses it to inject entropy into /dev/random when it runs dry. The main downside to this is that it blocks the mike for other uses. There are other ways of getting extra entropy, like copying a disk to /dev/null, or doing a package update (lots of disk and network traffic). You may want to kit one or more of your servers out with a hardware RNG and install something that can serve entropy-as-a-service to the others. Or even a USB soundcard and randomsound would work (lots of whitenoise in a server room...)
For option A, you can set property
-Djava.security.egd=file:/dev/./urandom
(note the extra dot - this is to workaround a "smart" bit of code that assumes you want /dev/random even if you don't say so : see : https://bugs.openjdk.java.net/browse/JDK-6202721 )
| |
doc_2759
|
and also we know the way that get the mime type by a file signature in C#,(using the urlmon.dll Using .NET, how can you find the mime type of a file based on the file signature not the extension ,my question is that how can we get the exact mime type in IOS,no matter the file's extension is changed by someone,we can getthe right mime type.
thank you for your attention~!
A:
Would you tell me how I get the right mime type exactly when I get a
path of a file.
iOS uses the concept of Uniform Type Identifiers (UTI) to handle document types.
NSString *path; // contains the file path
// Get the UTI from the file's extension:
CFStringRef pathExtension = (__bridge_retained CFStringRef)[path pathExtension];
CFStringRef type = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, NULL);
CFRelease(pathExtension);
// The UTI can be converted to a mime type:
NSString *mimeType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass(type, kUTTagClassMIMEType);
if (type != NULL)
CFRelease(type);
You should consider using UTIs for your purpose directly instead of converting them to the less powerful mime type.
| |
doc_2760
|
Resolution center gave me some advice to fix:
Please either revise your Info.plist to include the UISupportedExternalAccessoryProtocols key and update your Review Notes to include the PPID # - or remove the external-accessory value from the UIBackgroundModes key.
The first was rejected, UIBackgroundModes been removed, and then reviewed again, but still are in the same reasons for rejection,and I don't know what PPID.
In addition, APPLE has given me this advice:
Additionally, your app must be authorized by MFi to use the desired hardware. If you are not yet in the MFi Program, you can enroll at MFi program.
So I must be register MFi to pass review it?
A: PPID means the chip which your using ..The hardware merchant need to register his hardware device with apple will provide bundle id to chip hardware merchant from then u can get PPID... Hope so it will usefull..
| |
doc_2761
|
// Blur image
void blur(int height, int width, RGBTRIPLE image[height][width])
{
RGBTRIPLE temp_img[height][width];
// copy original image array
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
temp_img[i][j] = image[i][j];
}
}
// iterate throughout the image
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
int sumBlue = 0;
int sumGreen = 0;
int sumRed = 0;
float count_pix = 0;
// obtain value of original colour values around target pixel- red green blue
for (int r = -1; r <= 1; r++)
{
for (int c = -1; c <= 1; c++)
{
// logic to determine if pixel is existent
if ((0 <= i + r && i + r < height) && (0 <= j + c && j + c < width))
{
// add all RGB values accordingly, with counter
sumBlue += temp_img[i + r][j + r].rgbtBlue;
sumGreen += temp_img[i + r][j + r].rgbtGreen;
sumRed += temp_img[i + r][j + r].rgbtRed;
count_pix ++; //count number of iterations to average out later
}
}
}
// average out and add replace values into original image for output
image[i][j].rgbtBlue = round(sumBlue / count_pix);
image[i][j].rgbtGreen = round(sumGreen / count_pix);
image[i][j].rgbtRed = round(sumRed / count_pix);
}
}
return;
}
Below is the list of expected output and output from this code
:( blur correctly filters middle pixel
expected "127 140 149\n", not "123 137 145\n
:( blur correctly filters pixel on edge
expected "80 95 105\n", not "85 100 110\n
:( blur correctly filters pixel in corner
expected "70 85 95\n", not "65 80 90\n
| |
doc_2762
|
It works perfectly, but the only problem that I noticed is that it returns movie titles, TV-series, actors, directors, etc.. while I ONLY need MOVIE TITLES.
Question:
Is there a way to get only movie titles integrating with their image in my auto-complete text-box (Not TV-series, Not actors, ..)? (I mean I want to disable auto-complete feature for actors, Series, etc., so if user typed "Tom.." in the search-box, it shouldn't show "Tom Criuse"..)
PS. If it is not possible, How can I show small image of movies when user types a movie name in auto-complete text-box? I have crawled IMDb poster links of movies and saved them in my database. (I saw This similar question, but actually, It didn't use images stored in DB which is my case)
UPDATE:
In order to avoid TV-series, I crawled list of IMDb movie titles and saved them in my DB. I am trying to compare the string that user enters with the titles in my DB, ao if no match were found it means it is not a movie and it might be g.g., TV-series..
Here is what I changed in suggest.php:
if(isset($arr['d'])){
foreach($arr['d'] as $d){
try{
include('imdbconnection.php');
$stmt = $conn->prepare("SELECT movieName FROM featuredfilms_EN WHERE movieName = :term");
$stmt->bindValue(':term', $d['l']);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_OBJ);
if (!empty($result)) {
$img = preg_replace('/_V1_.*?.jpg/ms', "_V1._SY50.jpg", $d['i'][0]);
if ((strpos($d['s'], "Actor,") === false) {
$s[] = array('label' => $d['l'], 'value' => $d['id'], 'cast' => $d['s'], 'img' => $img, 'q' => $d['q']);
}
//REST OF THE CODE
However, it does not work :|
A: Set condition (Actor, Tv-series, Directors and writers) & filter the results in suggestion page (Line #23)
if (strpos($d['s'], "Actor,") === false) { // Here avoiding all actors
$s[] = array('label' => $d['l'], 'value' => $d['id'], 'cast' => $d['s'], 'img' => $img, 'q' => $d['q']);
}
| |
doc_2763
|
[]is a excel cell
For example, now my data is:
[0.0 0.00 0.000 0.00000] [ ] [ ]
[216.6 -81.88 85.236 12.00000] [ ] [ ]
[214.4 -77.18 80.538 6.00000] [ ] [ ]
I want to split:
[0.0] [0.00] [0.000] [0.00000]
[216.6] [-81.88] [85.236] [12.00000]
[214.4] [-77.18] [80.538] [6.00000]
Now my new data will have a empty column between first column and second column.I try this code but the data will be:
[0.0] [0.00] [0.000] [0.00000]
[ ] [ ] [ ] [ ]
[216.6] [-81.88] [85.236] [12.00000]
[ ] [ ] [ ] [ ]
[214.4] [-77.18] [80.538] [6.00000]
[ ] [ ] [ ] [ ]
I have this small code:
import csv
l = []
with open('F:\csv\shortcircuit0707','rt') as f:
cr = csv.reader(f, delimiter=" ", skipinitialspace=True)
for column in cr:
l.append(column)
with open('F:\csv\shortcircuit0707_1','wt') as f2:
cw = csv.writer(f2)
for item in l:
cw.writerow(item)
cw.writerows(l)
Thanks in advance!
A: It looks like your data is not exactly in a CSV (C for comma) file, but fields are separated by spaces (or tabs).
You can try adding delimiter=" ", skipinitialspace=True (depending on your actual separator) parameters to csv.reader. See the document of the csv module.
Working example:
r = csv.reader(f, delimiter=" ", skipinitialspace=True)
A: I advice you to using pandas rather than CSV library
install it by this command in terminal ("pip install pandas")
and use it in code
import pandas as pd
my_csv=pd.read_csv("M:\csv\shortcircuit0707.csv",delimiter="\t")
my_csv.to_csv("M:\csv\shortcircuit0707_1.csv)
Note delimeter could be "\t" or ";" according to your CSV_file split data
see documentation https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html
| |
doc_2764
|
Here is my code:
$options = array(
'yes'=>t('Yes'),
'no'=>t('No')
);
$form['checklist_fieldset']['heating'] = array(
'#type' => 'radios',
'#title' => t('Heating options'),
'#options' =>$options,
'#default_value'=>$options['yes'],
);
I am getting yes as default value when I submit the form, but for users I need to show that as checked already. How can I achieve it?
A: Try this
$options = array(
'yes'=>t('Yes'),
'no'=>t('No')
);
$form['checklist_fieldset']['heating'] = array(
'#type' => 'radios',
'#title' => t('Heating options'),
'#options' =>$options,
'#default_value'=>'yes',
);
| |
doc_2765
|
This is how I do it inside the for loop.
WebSite.objects.all(); The database that I saved in a different area on django.
web_site = WebSite.objects.all():
for web in web_site:
get information from web
I want to run this for loop in parallel.
How can I achieve this, is there an easy way? I can also implement it directly in func code or try a feature of django/celery.
| |
doc_2766
|
df %>% mutate(N = if_else(Interval != lead(Interval) | row_number() == n(), criteria/Count, NA_real_))
In Python I wrote the following:
import pandas as pd
import numpy as np
df = pd.read_table('Fd.csv', sep=',')
for i in range(1,len(df.Interval)-1):
x = df.Interval[i]
n = df.Interval[i+1]
if x != n | x==df.Interval.tail().all():
df['new']=(df.criteria/df.Count)
else:
df['new']='NaN'
df.to_csv (r'dataframe.csv', index = False, header=True)
However, the output returns all NaNs.
Here is what the data looks like
Interval | Count | criteria
0 0 0
0 1 0
0 2 0
0 3 0
1 4 1
1 5 2
1 6 3
1 7 4
2 8 1
2 9 2
3 10 3
and this is what I want to get ( I also need to consider the last line)
Interval | Count | criteria | new
0 0 0
0 1 0
0 2 0
0 3 0 0
1 4 1
1 5 2
1 6 3
1 7 4 0.5714
2 8 1
2 9 2 0.2222
3 10 3 0.3333
If anyone could help find my mistake, I would greatly appreciate.
A: 1. Start indexing at 0
The first thing to note is that Python starts indexing at 0 (in contrast to R which starts at 1). Therefore, you need to modify the index range of your for-loop.
2. Specify row indices
When calling
df['new']=(df.criteria/df.Count)
or
df['new']='NaN'
you are setting/getting all the values in the "new" column. However, you intend to set the value only in some rows. Therefore, you need to specify the row.
3. Working example
import pandas as pd
df = pd.DataFrame()
df["Interval"] = [0,0,0,0,1,1,1,1,2,2,3]
df["Count"] = [0,1,2,3,4,5,6,7,8,9,10]
df["criteria"] = [0,0,0,0,1,2,3,4,1,2,3]
df["new"] = ["NaN"] * len(df.Interval)
last_row = len(df.Interval) - 1
for row in range(0, len(df.Interval)):
current_value = df.Interval[row]
next_value = df.Interval[min(row + 1, last_row)]
if (current_value != next_value) or (row == last_row):
result = df.loc[row, 'criteria'] / df.loc[row, 'Count']
df.loc[row, 'new'] = result
| |
doc_2767
|
Situation:
*
*I forked a Repository as my master then cloned it locally.
*Made my changes, and sent a pull request.
*The pull request has been closed, and has been "added manually"
(patch and apply).
Question:
*
*How do I get my local (and remote) repository back in sync with the upstream project?
*
*I don't care about keeping minor differences.
*I want my code to be easily pulled in the future.
*I don't want to lose history (mine or upstreams).
*Will the solution cause me issues with developing in the future?
Alternatives:
*
*is there an easier way?
*Should I just rename this branch (somehow) and start afresh?
*
*
*(somehow) sync the rename locally and work from a new master?
*
*
*Should I now forget using branches named master as this will cause me issues?
Github's in question:
*
*Original Upstream "pull"
*My Repository
A: Well, the easiest thing if you don't want to lose your history is to always create a feature branch where you work on your pull request.
In your case (if you want to keep your history), create a new branch
git checkout master
git checkout -b my-old-feature
Then, just reset your master branch to whatever point is the upstream master branch
git remote add upstream <upstream-repo-uri>
git fetch upstream
git checkout master
git reset --hard upstream/master
There you then have a clean state and your master branch will be exactly the upstream one. In the future, just always keep master branch following the upstream/master one, and work on feature branch you create to prevent collision with upstream updates.
edit:
By the way, I always prefer to have my branches named the same as the upstream. But you can also track upstream/master on another branch name. For example:
git pull upstream master:upstream-master
Hope this help!
A: Do you mean you have additional commits on your fork that aren't in the pull request, and you want to shift them over to the new master?
Use git-rebase, with the caveat that you should really only rebase if you know what it's doing:
git rebase --onto upstream/master A B
Here, A should be the last commit in your pull request, and B should be the name of your local branch (which is probably master).
This will iterate over all the commits that come after your pull request and "replay" them, one at a time, on top of upstream's new master. By "replay" I mean git is literally generating a patch from each commit, applying it to the code, and making a new commit with the same date/author/message as the original. You'll have the same changes arranged the same way, but the commit hashes will be different. (So don't do this if anyone else has branched off of your branch!)
Another way to do the same thing is to create a new branch based on upstream, then git cherry-pick the commits you want to keep. This does exactly the same thing, replaying the commits, except you bring arbitrary other commits into the current branch rather than moving the current branch somewhere else.
| |
doc_2768
|
<?xml version='1.0' encoding='windows-1252'?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.example.org" targetNamespace="http://www.example.org" elementFormDefault="qualified">
<xsd:complexType name="USAddress">
<xsd:sequence>
<xsd:element name="HouseNumber" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="OrderType">
<xsd:sequence>
<xsd:element name="orderID" type="xsd:string"/>
<xsd:element name="billTo" type="USAddress"/>
</xsd:sequence>
</xsd:complexType>
<xsd:element name="Customer">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="CustomerID" type="xsd:string"/>
<xsd:element name="Address" type="USAddress"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="Order" type="OrderType"/>
</xsd:schema>
TO
<?xml version='1.0' encoding='windows-1252'?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.example.org" targetNamespace="http://www.example.org" elementFormDefault="qualified">
<xsd:complexType name="USAddress">
<xsd:sequence>
<xsd:element name="HouseNumber" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="OrderType">
<xsd:sequence>
<xsd:element name="orderID" type="xsd:string"/>
<xsd:element name="billTo" type="USAddress"/>
</xsd:sequence>
</xsd:complexType>
<xsd:element name="Order" type="OrderType"/>
</xsd:schema>
<?xml version='1.0' encoding='windows-1252'?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.example.org" targetNamespace="http://www.example.org" elementFormDefault="qualified">
<xsd:complexType name="USAddress">
<xsd:sequence>
<xsd:element name="HouseNumber" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
<xsd:element name="Customer">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="CustomerID" type="xsd:string"/>
<xsd:element name="Address" type="USAddress"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
A: Using XSL 2.0 you can have multiple output documents and can define every file name, file content, etc. Default java support for XSL 2.0 is far from perfect, so I use the incredible Saxon (you can download saxon-he here, unzip it and add saxon9he.jar to your project).
This is the example XSL 2.0 I've made, it works using the idea that user laune has exposed in his comment. So it produces one output schema for every element, and a schema for everything that is not an element (types). Every new schema contains only a xs:element's and has a xs:include including the schema containing types. It is a quite simple (and very clever in my opinion) method and easy to understand if you're familiar with XSL (look at the xsl comments).
xsl.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:template match="/">
<xsl:for-each select="/*/*[local-name()='element']">
<xsl:variable name="currentElement" select="."/>
<!-- Create schema for every element containing only element, including types schema -->
<xsl:result-document method="xml" href="schema_element_{@name}.xsd">
<xsl:for-each select="/*[1]">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:element name="include" namespace="http://www.w3.org/2001/XMLSchema">
<xsl:attribute name="schemaLocation">schema_types.xsd</xsl:attribute>
</xsl:element> <!-- Include clause -->
<xsl:copy-of select="$currentElement"/> <!-- Only content is current xs:element -->
</xsl:copy>
</xsl:for-each>
</xsl:result-document>
</xsl:for-each>
<xsl:for-each select="/*[1]">
<!-- Create types document containing all but root xs:element's -->
<xsl:result-document method="xml" href="schema_types.xsd">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:copy-of select="node()[local-name()!='element']"/>
</xsl:copy>
</xsl:result-document>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
The only java code needed is for calling saxon to do the xsl transformation that produce the output files with the names dynamically derived in xsl.
Main.java
import java.io.File;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class Main {
public static void main(String[]args) throws Exception{
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(new StreamSource(new File("xsl.xsl")));
transformer.transform(new StreamSource(new File("schema.xsd")), new StreamResult(System.out));
}
}
Using your example schema, my xsl and running the java code these are the files that will be created with these filenames (note that indentation might be lost):
schema_element_Customer.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://www.example.org" targetNamespace="http://www.example.org"
elementFormDefault="qualified">
<include xmlns="http://www.w3.org/2001/XMLSchema"
schemaLocation="schema_types.xsd" />
<xsd:element name="Customer">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="CustomerID" type="xsd:string" />
<xsd:element name="Address" type="USAddress" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
schema_element_Order.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://www.example.org" targetNamespace="http://www.example.org"
elementFormDefault="qualified">
<include xmlns="http://www.w3.org/2001/XMLSchema"
schemaLocation="schema_types.xsd" />
<xsd:element name="Order" type="OrderType" />
</xsd:schema>
schema_types.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://www.example.org" targetNamespace="http://www.example.org"
elementFormDefault="qualified">
<xsd:complexType name="USAddress">
<xsd:sequence>
<xsd:element name="HouseNumber" type="xsd:string" />
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="OrderType">
<xsd:sequence>
<xsd:element name="orderID" type="xsd:string" />
<xsd:element name="billTo" type="USAddress" />
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
UPDATE: necessary changes to output to Map
Necessary changes to output to Map instead of files in the file-system:
Based on this answer I realized that you can add a setting to be notified by every result-document so you can writte the output where you want implementing an OutputUriResolver. So I've made this one that writes to a HashMap:
import java.io.StringWriter;
import java.util.Map;
import javax.xml.transform.Result;
import javax.xml.transform.TransformerException;
import javax.xml.transform.stream.StreamResult;
import net.sf.saxon.lib.OutputURIResolver;
public class HashMapSaverOutputUriResolver implements OutputURIResolver{
private Map<String, String> results; // We save here
public HashMapSaverOutputUriResolver(Map<String, String> map){
this.results = map; // Set map
}
public OutputURIResolver newInstance() {
return this;
}
public Result resolve(String href, String base) throws TransformerException { // We set to resolve the file to write to a stringResult that wraps a stringWritter
StringWriter sw = new StringWriter(); // StringWritter
StreamResult sr = new StreamResult(sw); // StreamResult
sr.setSystemId(href); // Id of the streamResult = href = fileName
return sr;
}
public void close(Result result) throws TransformerException { // End of result:document transformed
StreamResult sr = (StreamResult) result; // Get StreamResult
StringWriter sw = (StringWriter) sr.getWriter(); // Get StreamWritter
String href = sr.getSystemId(); // Get href (fileName)
String content = sw.toString(); // Get string file-content
this.results.put(href, content); // Save in map
}
}
In the main file you only need to add two new lines (create the map, and set the proper setting to the OutputUriResolver associated with the map).
public static void main(String[] args) throws Exception {
HashMap<String, String> results = new HashMap<String, String>(); // Your map
TransformerFactory tFactory = TransformerFactory.newInstance();
tFactory.setAttribute("http://saxon.sf.net/feature/outputURIResolver", new HashMapSaverOutputUriResolver(results)); // Set OutputURIResolver
Transformer transformer = tFactory.newTransformer(new StreamSource(new File("xsl.xsl")));
transformer.transform(new StreamSource(new File("schema.xsd")), new StreamResult(System.out));
// Once the transformation has finished the Map is filled
}
| |
doc_2769
|
printfn "Hello"
works as expected without errors, however, using pipe operator
"Hello" |> printfn
The type 'string' is not compatible with the type 'Printf.TextWriterFormat'
I understood the pipe operator behavior:
f(a) is equivalent to a |> f
Why does the latter generate the error?? Thanks.
A: Yes. The pipe operator does what you think it does. However, printfn is "special" that it takes a kind of "formattable string" (there are different kinds of these) and the compiler does its magic only when the format string appears as a direct argument.
In other words, your "Hello" in the first example is not really a string, it is a Printf.TextWriterFormat object, magically created by the compiler.
Still, you can do what you want by using an explict format string. This approach you'll see quite a bit in real-world code:
"Hello" |> printfn "%s"
Here, %s means: give me a string. The magic of F# in this case again takes the format string, here "%s", this time with an argument of type string, and turns it into a function.
Note 1: that this "surprise effect" is being considered and the community works towards adding a printn function (i.e., without the f which stands for format) to just take a simple string: https://github.com/fsharp/fslang-suggestions/issues/1092
Note 2: if you do want to pass arguments to printfn around, you can make the type explicit, but this is done very rarely:
let x = Printf.TextWriterFormat<unit> "Hello"
x |> printfn // now it's legal
Note 3: you might wonder why the compiler doesn't apply its magic to the lh-side of |> as well. The reason is that |> is not an intrinsic to the compiler, but just another overridable operator. Fixing this is therefor technically very hard (there can be any amount of operators on the lh-side), though it has been considered at certain times.
Other alternative
In the comments, the OP suggested that he/she/they didn't like the idea of having to use printfn "%i" and the like, and ended up writing print, printInt etc functions.
If you go that route, you can write your code in a class with only static methods, while using function-style naming. Then just open the static type (this is a new feature in F# 6).
module MyPrinters =
// create a static type (no constructors)
type Printers =
static member print x = printfn "%s" x // string
static member print x = printfn "%i" x // integer
static member print x = printfn "%M" x // decimal
static member print x = printfn "%f" x // float
module X =
// open the static type
open type MyPrinters.Printers
let f() = print 42
let g() = print "test"
| |
doc_2770
|
Example: aabaa -> aba -> b
And that is not the problem, so now I should replace the word 'aabaa' with 'b' in original string.
The only problem i have is when the sentence is given without spaces. For example:
Trust,is,all. -> rus,is,all.
Also to note characters such as (. , ! ? ; :) are to be ignored but have to be there in the final output.
So far I've wrote this but it doesn't satisfy the example above:
s1 = str(input())
sentence = s1.split()
news = []
ignorabelCharacters = ['.',',','!','?',';',':']
helpList = []
for i in range(len(s1)):
if s1[i] in ignorabelCharacters:
helpList.append([s1[i],i])
for i in sentence:
i = str(i)
j = 0
while j < len(i):
if i[j] in ignorabelCharacters:
i = i.replace(i[j],' ').strip()
j+=1
else:j+=1
news.append(i)
s2 =' '.join(news)
newSentence = s2.split()
def checkAgain(newSentence):
newNewSentance = []
count = []
x=0
for i in newSentence:
j = len(i)
while j > 2:
if i[0].lower() == i[-1] or i[0].upper() == i[-1]:
i = i[1:-1]
j-=2
x+=2
else:
break
count.append(x)
newNewSentance.append(i)
x=0
return [newNewSentance,count]
newNewSentence = checkAgain(newSentence)[0]
count = checkAgain(newSentence)[1]
def finalProcessing(newNewSentence,sentence,newSentence):
finalSentence = []
for i in range(len(sentence)):
if len(newNewSentence[i]) == len(sentence[i]):
finalSentence.append(newNewSentence[i])
else:
x = len(sentence[i]) - len(newSentence[i])
if x ==0:
finalSentence.append(newNewSentence[i])
else:
value = newNewSentence[i] + sentence[i][-x:]
finalSentence.append(value)
return finalSentence
finalSentence = finalProcessing(newNewSentence,sentence,newSentence)
def finalPrint(finalSentece):
for i in range(len(finalSentece)):
if i == len(finalSentece) -1:
print(finalSentece[i],end='')
else:
print(finalSentece[i],end= ' ')
finalPrint(finalSentence)
A: This approach is different from yours but here is how I would do it.
def condenseWord(w):
ln = len(w)
while ln >= 3:
if w[0].lower() == w[-1].lower():
w = w[1:-1]
ln = len(w)
else:
break
return w
def collapseString(s):
sep_chars = {' ', ',', '.', ';', ':', '!', '"', "'"}
out = r''
wdstrt = 0
lstltr = 0
for i in range(len(s)):
if s[i] in sep_chars:
ck = condenseWord(s[wdstrt:i])
out += ck
out += s[i]
wdstrt = i+1
lstltr = i+1
else:
lstltr = i
out += s[wdstrt:lstltr]
return out
Then
collapseString('aabaa') -> 'b', and
collapseString('Trust,is,all.' ) -> 'rus,is,all.'
| |
doc_2771
|
Thanks in advance.
A: It does, in several ways:
*
*Better support for streaming transfers. The conventional alternative is a combination of HTTP/1.1's chunked transfer encoding, connection header Voodoo and the willingness or not of any of the parts to implement HTTP pipelining (which, e.g., curl enables by default). In my experience it takes a lot more of work to get the three to work well together than to just slap HTTP/2. There is no need for chunked transfer-encoding with HTTP/2, and the protocol does not support it.
*With HTTP/2, you can have many requests in flight, REST or not, with zero time for establishing connections. This is a blessing both for the browser and for the server, which has to allocate less files descriptors per client.
*Header compression also applies to HTTP/2 REST requests, together with the associated bandwidth reduction.
So, if in doubt, go always for HTTP/2. There are also excellent tools out there to develop HTTP/2 applications. Some, like ShimmerCat, even remove the drudgery of setting up certificates and DNS alias, so that starting with HTTP/2 from day one becomes a no-brainer.
| |
doc_2772
|
To draw the breadcrumb of an url, lets say site.com/a/b/c/15 I do the following:
*
*Get the route of site.com/a/b/c/15 and get the pretty name associated to the route
*Get the route of site.com/a/b/c and get the pretty name associated to the route
*Get the route of site.com/a/b and get the pretty name associated to the route
*Get the route of site.com/a and get the pretty name associated to the route
So lets say I do have the following routes:
{ path: 'a', component: A, data:{prettyName: 'I am A'}}
{ path: 'b', component: B, data:{prettyName: 'I am B'}},
{ path: 'c', component: C, data:{prettyName: 'I am C'}},
The result of my process would be an array containing {"I am C", "I am B", "I am C"} and thanks to that I can display a nice breadcrumb "I am A > I am B > I am C" that explains the current route.
This use to work with the router-deprecated doing
this.router.recognize(url).then((instruction) => {
instruction.component.routeData.get('prettyName') // Would return 'I am ..'
However now; with the last router I am not able to process this recognize logic anymore.
How to get the route data associated to an url ?
A: Updated for RC5
Instead of starting with the current URL and trying to get the routes from the URL, you can get all of the activated routes (associated with the primary outlet) from the RouterState:
After the end of each successful navigation lifecycle, the router builds a tree of ActivatedRoutes, which make up the current state of the router. We can access the current RouterState from anywhere in our application using the Router service and the routerState property.
The router state provides us with methods to traverse up and down the route tree from any activated route to get information we may need from parent, child and sibling routes. -- reference
Subscribe to router events, then, after each NavigationEnd event, walk down the tree of ActivatedRoutes from the root:
import { Component } from '@angular/core';
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
import 'rxjs/add/operator/filter';
@Component({
selector: 'breadcrumbs',
template: `
<div>
breadcrumbs:
<span *ngFor="let breadcrumb of breadcrumbs; let last = last">
<a [routerLink]="breadcrumb.url">{{breadcrumb.label}}</a>
<span *ngIf="!last">></span>
</span>
</div>`
})
export class BreadcrumbsComponent {
breadcrumbs: Array<Object>;
constructor(private router:Router, private route:ActivatedRoute) {}
ngOnInit() {
this.router.events
.filter(event => event instanceof NavigationEnd)
.subscribe(event => { // note, we don't use event
this.breadcrumbs = [];
let currentRoute = this.route.root,
url = '';
do {
let childrenRoutes = currentRoute.children;
currentRoute = null;
childrenRoutes.forEach(route => {
if(route.outlet === 'primary') {
let routeSnapshot = route.snapshot;
console.log('snapshot:', routeSnapshot)
url += '/' + routeSnapshot.url.map(segment => segment.path).join('/');
this.breadcrumbs.push({
label: route.snapshot.data.breadcrumb,
url: url });
currentRoute = route;
}
})
} while(currentRoute);
})
}
}
Routes look like this:
{ path: '', component: HomeComponent, data: {breadcrumb: 'home'}}
Plunker - RC.5, router 3.0.0-rc.1
See also https://stackoverflow.com/a/38310404/215945 for a similar solution.
A: So far, the most feasable solution is (done):
*
*Make the routes export/importable
*Get the current url update from router.events subscribe
*On url change, loop on the routes's path, see if the pattern match the url
*If the patter match the url, get the data from the matching route
Pros: works
Cons: redoing url-route recognition manuall without using the ng2 router one
A: Any breadcrumb solution has to handle -
*
*declarative approach of defining breadcrumbs in Application routing.
*dynamic asynchronous way to update any route with a label from the server response.
*way to skip specific routes from displaying in breadcrumbs.
I have created an Angular library to handle all these, called xng-breadcrumbs - https://github.com/udayvunnam/xng-breadcrumb
feel free to check, An Angular app developed showing the breadcrumbs usage - https://xng-breadcrumb.netlify.com
Angular library planning, creation, and continuous release is well documented in this medium article
| |
doc_2773
|
Example:
CREATE procedure DISKBACKUP @location_dump varchar(255), @databasename varchar(255)
AS
backup Database @databasename to disk=@location_dump
...
Can I do the same in PostgreSQL?
A: No, it is not.
pg_dump must be used.
It's often requested, but it's not supported at present, and nobody who requests it ever goes on to do any work to actually make it happen.
| |
doc_2774
|
Do I understand this correctly? Or am I missing something that could help me confirm the transmission similarly to TCP?
A: From Laudenbach paper Continuous-Variable Quantum Key Distribution with Gaussian Modulation - The Theory of Practical Implementations:
Quantum key distribution is a method to generate a secret key between
two distant parties, Alice and Bob, based on transmitting
non-orthogonal quantum states. After the transmission and measurement
of these quantum states, Alice and Bob exchange classical messages and
perform post-processing to generate a secure key. In order to prevent
a man-in-the-middle attack, Alice and Bob need to authenticate these
classical messages in advance (so strictly speaking QKD is a
key-growing protocol).
So BB84 works only if you have an authenticate classical channel. I guess this assumption ends the Two Generals' Problem. Am I right?
| |
doc_2775
|
I know that noob questions are sometimes frowned upon here, but this is the only place I have to turn. The Pycharm forum is pretty inactive and the teacher is not accessible. Any help would be appreciated. MacOS 12.6, Pycharm 2022.2.2 (community edition)
Link to image since SO won't let me post it directly yet:
https://i.postimg.cc/mrZqbchp/Screen-Shot-2022-10-07-at-1-14-25-PM.png
| |
doc_2776
|
for (Product product : plist) {
JSONObject jo1 = new JSONObject();
jo1.put("image", product.getProductImages());
jo1.put("name", product.getName());
jo1.put("price", product.getPrice());
js1.add(jo1);
}
In the above code I can not use js1.add(jo1); because of I import these Libraries.
import org.json.JSONArray;
import org.json.JSONObject;
but if I import these
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
I can use add method.
So what is the difference between these org.json.simple. and org.json.
A: You have two different dependencies on your classpath.
import org.json.JSONArray;
import org.json.JSONObject;
Above two imports come from JSON-java
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
Above two imports come from json-simple
These are two different implementation of JSON processor. So, it's obvious that the contract of these two dependencies don't match. There are other JSON processor listed on json.org.
| |
doc_2777
|
In the above jsfiddle, the following three functions seem to be deprecated for React v0.13.1.
var View = React.DOM.div;
var Text = React.DOM.span;
....
React.renderComponent(<div style={{width: '100vw', height: '100vh'}}><StyleDemo /></div>, document.body);
It seems that the code after refactoring should be something like below for React 0.13.1:
var View = React.createElement('div');
var Text = React.createElement('span');
...
React.render(React.createElement("div", {style: {width: '100vw', height: '100vh'}}, React.createElement(StyleDemo, null)), document.body);
However, above refactoring doesn't seem to work - nothing renders in Chrome after refactoring. Since my knowledge of JS and React is quite limited, I will appreciate pointers on how to refactor above code for React 0.13.1.
To test the above code on my computer, I created index.html and test.js, both of which are attached below.
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
body {
padding: 0;
margin: 0;
font-family: Helvetica;
font-size: 14px;
font-weight: 100;
}
div, span {
box-sizing: border-box;
position: relative;
border: 0 solid black;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
align-items: stretch;
justify-content: flex-start;
flex-shrink: 0;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.1/JSXTransformer.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.1/react.js"></script>
</head>
<body>
<script type="text/jsx" src="test.js"></script>
</body>
</html>
test.js:
/** @jsx React.DOM */
var StyleSheet = { create: function(e) { return e; } };
var View = React.createElement('div');
var Text = React.createElement('span');
var StyleDemo = React.createClass({
render: function() {
return (
<View style={styles.card}>
<View style={styles.header}>
<View style={styles.profilePicture} />
<View style={{flex: 1}}>
<Text style={styles.name}>Christopher Chedeau</Text>
<Text style={styles.subtitle}>August 28 at 9:46pm · Paris, France</Text>
</View>
</View>
<View>
<Text>'react js' search on Twitter returns 96 results in the past 24 hours. I declare bankruptcy!</Text>
<Text style={styles.bling}>Like · Comment · Share</Text>
</View>
</View>
);
}
});
var styles = StyleSheet.create({
card: {
margin: 15,
padding: 8,
borderWidth: 1,
borderColor: '#cccccc',
borderRadius: 3
},
profilePicture: {
width: 40,
height: 40,
backgroundColor: '#cccccc',
marginRight: 8,
marginBottom: 8,
},
name: {
color: '#3B5998',
fontWeight: 'bold',
marginBottom: 2,
},
subtitle: {
fontSize: 12,
color: '#9197A3',
},
header: {
flexDirection: 'row',
},
bling: {
marginTop: 8,
color: '#6D84B4',
fontSize: 13,
},
});
React.render(React.createElement("div", {style: {width: '100vw', height: '100vh'}}, React.createElement(StyleDemo, null)), document.body);
A:
React.DOM provides convenience wrappers around React.createElement
for DOM components (Source)
So you can use React.createElement but for regular html elements it's easier with JSX: just replace <View /> with straight <div /> (and Text with span)
Then you just need to rename React.renderComponent() (deprecated) with React.render() and it works.
New jsfiddle: http://jsfiddle.net/Lt5skeab/1/
(External resources updated to use React 0.13.1)
| |
doc_2778
|
array = [['dog',5], ['cat',10]]
num = 10
puts num / array[0,1]
A: array = [['dog',5], ['cat',10]]
num = 10
puts num / array[0][1] # 10/5 = 2
puts num / array[1][1] # 10/10 = 1
| |
doc_2779
|
#include <iostream>
using namespace std;
#include<stdlib.h>
#include <cstdlib>
#include <cmath>
class Base //Allocate the memory space
{
protected:
int n;
typedef double Coord[2];
Coord* city_location;
Base(int ncities) : n(ncities), city_location(new Coord[n]) {}
~Base() { delete [] city_location; }
};
template <class T> class Map;
struct Flat;
template <> class Map<Flat> : public Base
{
public:
//int Path[n];
Map(int n) : Base(n)
{
int Path[n]; //Populate with random points for flat version
for (int i=0;i<n;i++)
{
city_location[i][0] = (static_cast <float> (rand()) / static_cast <float> (RAND_MAX))*80;
city_location[i][1] = (static_cast <float> (rand()) / static_cast <float> (RAND_MAX))*80;
Path[i] = i;
cout << "city " << i << " is at (" << city_location[i][0] << "," << city_location[i][1] << ")\n";
}
cout << "\nThe initial path is (";
for(int i=0;i<n;i++)
{
cout << Path[i]<< " ";
}
cout<< Path[0] <<")"<<endl;
pathdistance(Path, n, city_location); //Line 45
}
double distance(int i, int j) const //Pairwise distance function
{
double dx = city_location[i][0] - city_location[j][0];
double dy = city_location[i][1] - city_location[j][1];
return sqrt(dx*dx+dy*dy);
}
double pathdistance(double Path[],int n, double city_location) //total distance function
{
//cout<< city_location[0][1];
double total = 0;
for(int i=0; i<n-1;i++)
{
total += distance(Path[i],Path[i+1]);
}
total += distance(Path[n],Path[0]);
cout << "total distance is "<< total<<endl;
return total;
}
};
int main()
{
srand(1235);
Map<Flat> x(10);
cout << "distance between cities 3 and 7 is " << x.distance(3,7) << "\n";
}
I get the error msg:
45 error: no matching function for call to 'Map<Flat>::pathdistance(int [(((sizetype)(((ssizetype)n) + -1)) + 1)], int&, Base::Coord)'
I know that it has to do with how I pass the pointer but I can't seem to figure out the correct way to do it. Apologies if this looks very ugly to most of you but I'm very new to C++. Go easy on me. Thanks in advance.
A: Line 45 : The function pathdistance is being called. It asks for certain types of parameters that aren't matching with the arguments you are providing to it :
double pathdistance(double Path[],int n, double city_location)
in the constructor of map, where the line 45 is ...
pathdistance ask for his 3rd parameter to be a double, but city_location is a *Coord, or more precisely, a *double[2]
same for Path : the function asked for a double[], but received a int[]
A: First, the function signature of pathdistance
double pathdistance(double Path[],int n, double city_location);
doesn't conform to C++ standard. double Path[] isn't kosher.
As far as your error message goes:
45 error: no matching function for call to 'Map<Flat>::pathdistance(int [(((sizetype)(((ssizetype)n) + -1)) + 1)], int&, Base::Coord)'
I can immediately tell (without even looking at your source code) that the last argument city_location is of type Base::Coordinate, but your function definition requires it to be a double.
A: Here is a small program in C that treats the Travelling Salesman Problem. It is based on the branch-and-bound algorithm. To generate the tree two data structures are used : a stack and a circular queue. For the purpose of testing, the connection matrix is generated randomly. The departure city is 1.The initial solution is 1-n. But in practice, using a solution produced by a heuristic algorithm would improve very much the program.
#include <stdio.h>
int queue[100], stack[100], alt[100], v[100];
int sp,head,tail,i,n,g,j,s,path,module,map[100][100];
int main()
{
printf("Number of cities:");
scanf( "%d",&n);
printf("Max Segment:");
scanf( "%d",&module);
printf("Seed:");
scanf( "%d",&g);
srand(g);
// Generating the sysmetric connection matrix randomly
for (i=0 ; i<n ; i++) {
for (j=i+1 ; j<n ; j++) {
map[i][j]= rand() % (module+1);
map[j][i]=map[i][j];
}
for (j=0 ; j<n ; j++) printf("%3d ",map[i][j]);
printf("\n");
}
//Start with an initial solution from city 1
for (i=0 ; i<n ; i++) {
queue[i]=i;
}
// Set route length to high value
path=module*n;
stack[0]=queue[0];
alt[0]=0;
printf("running...\n");
sp=0;
head=0;
tail=n-1;
s=0;
// Explore a branch of the factorial tree
while(1) {
while(sp<n-1 && s<path) {
sp++;
head++; if (head==n) head=0;
stack[sp]=queue[head];
s=s+map[stack[sp]][stack[sp-1]];
alt[sp]=n-sp-1;
}
// Save a better solution
if (s+map[stack[sp]][stack[0]]<path) {
path=s+map[stack[sp]][stack[0]];
for (i=0 ; i<n ; i++) v[i]=stack[i]+1;
}
// Leaving nodes when there is no more branches
while (alt[sp]==0 && sp>=0) {
tail++; if (tail==n) tail=0;
queue[tail]=stack[sp];
s=s-map[stack[sp]][stack[sp-1]];
sp--;
}
// If Bottom of stack is reached then stop
if (sp<0) break;
tail++; if (tail==n) tail=0;
queue[tail]=stack[sp];
s=s-map[stack[sp]][stack[sp-1]];
// Explore an alternate branch
alt[sp]=alt[sp]-1;
head++; if (head==n) head=0;
stack[sp]=queue[head];
s=s+map[stack[sp]][stack[sp-1]];
}
printf("best route=%d\n",path);
for (i=0 ; i<n ; i++) printf("%d ",v[i]);
printf("%d\n",stack[0]+1);
return 0;
}
Now lets run the progam for n=10.
[oldache@localhost ~]$ ./bnb
Number of cities:10
Max Segment:345
Seed:4
0 199 171 200 244 241 95 71 71 274
199 0 15 114 252 72 238 7 258 118
171 15 0 237 305 343 151 28 274 191
200 114 237 0 197 158 198 216 342 76
244 252 305 197 0 292 147 248 98 45
241 72 343 158 292 0 95 194 116 167
95 238 151 198 147 95 0 122 83 233
71 7 28 216 248 194 122 0 28 155
71 258 274 342 98 116 83 28 0 126
274 118 191 76 45 167 233 155 126 0
running...
best route=735
1 7 5 10 4 6 2 3 8 9 1
| |
doc_2780
|
I call the updateUsers function with the callback but the updateDashboard function is not getting called at all even on successful completion of updateUsers function. The code blocks are below. There are no errors reported as well.
updateUsers(data,dashboardDayData.key,function(err,doc){
updateDashboard(dashboardYearData,data.type,1,doc,function(err){console.log("Got executed");});
});
function updateUsers(req,dateKey,callback){
var yyyy = parseInt(dateKey.toString().substring(0,4));
var mm = parseInt(dateKey.toString().substring(4,6));
var dd = dateKey.toString().substring(6,8);
switch(req.type){
case Collection["begin"]:
Model.User.findById(req.val.did,function(err,doc){
if(!err){
if(doc === null || !doc){
req.type = Collection["user"];
req.val.ts = 1;
req.val.tts = 0;
event = EventFactory.getEvent(req);
event.save(function (err) {
if (err) {
logger.error(common.getErrorMessageFrom(err));
return;
}
var push = {};
push['_'+yyyy] = JSON.parse('{"_id":'+parseInt(mm.toString().concat(dd))+',"tse":1,"tts":0}');
Model.User.findByIdAndUpdate(req.val.did,{$push:push},{upsert:true},function(err,doc){
console.log("err "+err);
console.log("doc "+doc);
if(err){
logger.error(common.getErrorMessageFrom(err));
return;
}
callback(err,1);
});
});
}
function updateDashboard(dashboardData,eventType,valueIncrement,newUserIncrement,callback){
switch(eventType){
case Collection["begin"]:
console.log(dashboardData);
Model.Dashboard.findByIdAndUpdate(dashboardData,{$inc:{'val.tse':valueIncrement,'val.tnu':newUserIncrement}},{upsert:true},function(err,doc){
if(err){
logger.error(err);
}
callback(err);
});
break;
A: I think the problem sleeps in the anonymous function called at your first updateUsers declaration. If I'm guessing right, JavaScript attends three objects as parameters for your function updateUsers(req,dateKey,callback), and I think this piece of code:
function(err,doc){
updateDashboard(dashboardYearData,data.type,1,doc,function(err) {console.log("Got executed");});
}
is not interpreted as an object. So he thinks you never call this function. Once again, I'm only trying to guess, but I think the problem is there. Try fo encapsulate your function in an object, then calling it ? Somethink like :
var subfunction = function(err, doc) { updateDashboard (...) };
updateUsers(req, database, subfunction);
| |
doc_2781
|
I try to reproduce values of this article (2014) as validation.
My result for % FFO seem ok but I struggle with AFFO... It seem to be almost the same thing but something is wrong and dont fit the article results.
nb_share = request.financial(syminfo.tickerid, "TOTAL_SHARES_OUTSTANDING", "FY")
CapitalExpenditures = request.financial(syminfo.tickerid, "CAPITAL_EXPENDITURES", "FY")*-1
divYrsRate = request.financial(syminfo.tickerid, "TOTAL_CASH_DIVIDENDS_PAID", "FY")/nb_share*-1
FFO = request.financial(syminfo.tickerid, "FUNDS_F_OPERATIONS", "FY")
FFOshare = FFO/nb_share
PFFOshare = close/FFOshare
PFFOratioShare = 1-divYrsRate/PFFOshare
AFFO = FFO-CapitalExpenditures
AFFOshare = AFFO/nb_share
PAFFOshare = close/AFFOshare
PAFFOratioShare = divYrsRate/PAFFOshare
| |
doc_2782
|
<table>
<thead>
<tr>
<th>Year</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>1990</td>
<td>-</td>
</tr>
...
</tbody>
</table>
and I want to make a GET request to World Bank API to fill out the values in this table.
My GET request is in a Meteor method
Meteor.methods({
getData: function () {
try {
const url = 'http://api.worldbank.org/countries/br/indicators/NY.GDP.MKTP.CD?date=1990:2000&format=json';
const request = HTTP.get(url);
return request;
} catch (e) {
console.log(e);
return false;
}
},
});
and I call my method from the client with
Meteor.call('getData', function(error, result) {
console.log(result);
});
So I get the values in the console, but I want to replace - in the html table with the correct values.
A: You would use the {{#each}} block helper to loop through the array. E.g.
<tbody>
{{#each getData}}
<tr>
<td>{{date}}</td>
<td>{{value}}</td>
</tr>
{{/each}}
</tbody>
Where getData is a template helper that fetches the data. However, because the data you're getting is async, you cannot simply do Meteor.call() directly in the helper.
One way to solve this is with a session variable ('meteor add session' to install the package).
First, you'd fetch the data when creating the template and set it to a session variable:
Template.your_template.onCreated(function() {
Meteor.call('getData', function(error, result) {
// result.data[1] is the array of objects with the data
Session.set('bankData', result.data[1]);
});
});
Then, use a template helper to pass the data to template:
Template.your_template.helpers({
getData: function(){
return Session.get('bankData');
}
});
| |
doc_2783
|
Something like a function
public function create_array($num_elements){
.....
}
that return me something like
//call the function....
create_array(3);
//and the output is:
array{
0 => null
1 => null
2 => null
}
I've already thought about array_fill and a simple foreach loop.
Are there any other solutions?
A: Actually a call to array_fill should be sufficient:
//...
public function create_array($num_elements){
return array_fill(0, $num_elements, null);
}
//..
var_dump(create_array(3));
/*
array(3) {
[0]=> NULL
[1]=> NULL
[2]=> NULL
}
*/
A: for ($i = 0; $i < $num_elements; $i++) {
$array[$i] = null;
}
A: Do array_fill and foreach not work?
Of course, the simplest solution that comes to mind is
function create_array($num_elements) {
$r = array();
for ($i = 0; $i < $num_elements; $i++)
$r[] = null;
return $r;
}
array_fill should also work:
function create_array($num_elements) {
return array_fill(0, $num_elements, null);
}
A: Simple use of array_fill sounds like the easiest solution:
$arr = array_fill($start_at, $num_elements, null);
A: array_fill(0, $element, null);
using this php function, you can create array with starting index 0, and all will have null value.
A: In foreach loop you can simply use range()
| |
doc_2784
|
FROM ubuntu
FROM python:3.6.3
FROM postgres
FROM gunicorn
...
I am thinking about having different base image because if someday I want to update one of these image, I only have to update base image and not to go into ubuntu and update them.
A: You can use multiple FROM in the same Dockerfile, provided you are doing a multi-stage build
One part of the Dockerfile would build an intermediate image used by another.
But that is generally use to cleanly separate the parents used for building your final program, from the parents needed to execute your final program.
A: No, you can not create your image like this, the only image that will treat as the base image in the Dockerfile you posted will be the last FROM gunicor. what you need is multi-stage builds but before that, I will clear some concept about such Dockerfile.
A parent image is the image that your image is based on. It refers to
the contents of the FROM directive in the Dockerfile. Each subsequent
declaration in the Dockerfile modifies this parent image. Most
Dockerfiles start from a parent image, rather than a base image.
However, the terms are sometimes used interchangeably.
But in your case, I will not recommend putting everything in one Dockerfile. It will kill the purpose of Containerization.
Rule of Thumb
One process per container
Each container should have only one concern
Decoupling applications into multiple containers makes it much easier to scale horizontally and reuse containers. For instance, a web application stack might consist of three separate containers, each with its own unique image, to manage the web application, database, and an in-memory cache in a decoupled manner.
dockerfile_best-practices
Apart from Database, You can use multi-stage builds
If you use Docker 17.05 or higher, you can use multi-stage builds to
drastically reduce the size of your final image, without the need to
jump through hoops to reduce the number of intermediate layers or
remove intermediate files during the build.
Images being built by the final stage only, you can most of the time
benefit both the build cache and minimize images layers.
Your build stage may contain several layers, ordered from the less
frequently changed to the more frequently changed for example:
*
*Install tools you need to build your application
*Install or update library dependencies
*Generate your application
use-multi-stage-builds
With the multi-stage build, The Dockerfile can contain multiple FROM lines and each stage starts with a new FROM line and a fresh context. You can copy artifacts from stage to stage and the artifacts not copied over are discarded. This allows to keep the final image smaller and only include the relevant artifacts.
A: Is it possible? Yes, Technically multiple base images (FROM XXXX) can appear in single docker file. But it is not for what you are trying to do. They are used for multi-stage builds. You can read more about it here.
The answer to your question is that, if you want to achieve this type of docker image, you should use one base image and install everything else in it with RUN commands like this.
FROM ubuntu
RUN apt install postgresql # install postgresql
...
Obviously it is not that simple. base ubuntu image is very minimal you have to install all dependencies and tools needed to install python, postgres and gunicorn yourself with RUN commands. For example, if you need to download python source code using
RUN wget https://www.python.org/ftp/python/3.7.4/Python-3.7.4.tgz
wget (most probably) is not pre installed in ubuntu image. You have to install it yourself.
Should I do it? I think you are going against the whole idea of dockerization of apps. Which is not to build a monolithic giant image containing all the services, but to divide services in separate containers. (Generally there should be one service per container) and then make these containers talk to each other with docker networking tools. That is you should use one container for postgres one for nginx and one for gunicorn, run them separately and connect them via network.There is an awesome tool, docker-compose, comes with docker to automate this kind of multi-container setup. You should really use it. For more practical example about it, please read this good article.
A: You can use official docker image for django https://hub.docker.com/_/django/ .
It is well documented and explained its dockerfile.
If you wants to use different base image then you must go with docker-compose.
Your docker-compose.yml will look like
version: '3'
services:
web:
restart: always
build: ./web
expose:
- "8000"
links:
- postgres:postgres
- redis:redis
volumes:
- web-django:/usr/src/app
- web-static:/usr/src/app/static
env_file: .env
environment:
DEBUG: 'true'
command: /usr/local/bin/gunicorn docker_django.wsgi:application -w 2 -b :8000
nginx:
restart: always
build: ./nginx/
ports:
- "80:80"
volumes:
- web-static:/www/static
links:
- web:web
postgres:
restart: always
image: postgres:latest
ports:
- "5432:5432"
volumes:
- pgdata:/var/lib/postgresql/data/
redis:
restart: always
image: redis:latest
ports:
- "6379:6379"
volumes:
- redisdata:/data
volumes:
web-django:
web-static:
pgdata:
redisdata:
follow this blog for details https://realpython.com/django-development-with-docker-compose-and-machine/
| |
doc_2785
|
print(re.sub(' ',"\n",(re.sub('\\{|\\}|\\[|\\]|\\\\|\\/|\\\"|\\\'|\\,|\\=|\\(|\\)|\\:|\\||\\-|\\*|\\!|\\;|\\<|\\>|\\,|\\?|//@'," ",str))))
Output:
America
Category
States
of
the
United
States
Category
Southern
United
States
Link
FA
mk
Many new lines being inserted. I'm trying to write an optimized code to remove all empty lines with regular expressions without going into each and everydetails. I'm really worried about the performance of the program. I've lines over 100 Billion. So, I'm bit worried about time of execution. Any suggessions?
I'm trying to make output as below:
America
Category
States
of
the
United
States
Category
Southern
United
States
Link
FA
mk
A: You can use join() and split() methods:
print " ".join(your_string.split())
Output:
America Category States of the United States Category Southern United States Link FA mk
Edit:
To get each word in a different line, use "\n" instead of " ":
print "\n".join(a.split())
A: re.sub('\n{2,}', '\n', str)
will remove empty lines
| |
doc_2786
|
I was able to find for a NSG but I can't do the same thing with public IP.
Is somebody has an idea about the Query that I can use ?
Thanks,
A: I tend to use that snippet. It is really worth learning KustoQL, as it is extremly useful to find resources or log entries.
resources
| where type == "microsoft.network/publicipaddresses"
| where isempty(properties.ipConfiguration)
| |
doc_2787
|
I display the output and want to display class name even though it shows <__NSArrayI ..... > on the output window, but I am getting an empty description as follows. How could I get class of dic1 ?
id dic1 =@[@{@"id":@"1",@"name":@"Test 1 "},@{@"id":@"2",@"name":@"Test 2"}];
(lldb) po dic1
<__NSArrayI 0x100300090>(
{
id = 1;
name = "Test 1 ";
},
{
id = 2;
name = "Test 2";
}
)
(lldb) po [dic1 isKindOfClass:[NSArray class]]
<object returned empty description>
UPDATE
(lldb) p [dic1 isKindOfClass:[NSArray class]]
error: no known method '-isKindOfClass:'; cast the message send to the method's return type
A: Here's an answer that summarizes all of the comments.
*
*Use po to print the result of an object type. Use p to print the result of a primitive type.
*isKindOfClass: returns a BOOL so you need to use p, not po.
*Since dic1 is an id, the debugger isn't sure what the isKindOfClass: method is so it doesn't know its return type. Add a cast to make it clear:
p (BOOL)[dic1 isKindOfClass:[NSArray class]]
or you can also do:
p [(NSObject *)dic1 isKindOfClass:[NSArray class]]
*Normally you wouldn't want to use id for dic1 but since this is a learning exercise, do what you want. :)
| |
doc_2788
|
.add sends a post request to the userController and returns the VIEW that is the email window.
.init is called and sets up the handlers for the email window.
.send is called when the send button is pressed in the email window to send the email.
var Email={
con:"../application/controllers/",
dialog:null,
init:function(){..
//add event handlers for email dialog
send:function(){
var emailType=$("#emailType").prop("value");
var email=$("#email").prop("value");
if(!email){this.error("Please provide a valid email address");return false}
var emailTitle=$("#emailTitle").prop("value");
if(!emailTitle){this.error("Please provide a valid email title");return false}
var emailBody=$("#emailBody").prop("value");
if(!emailBody){this.error("Please provide a valid email body");return false}
if(emailType && email && emailTitle && emailBody){
$.post(Email.con+"userController.php",{
sendMail:"true",
emailType:emailType,
email:email,
emailTitle:emailTitle,
emailBody:emailBody,
});
return true;
}
return false;
},
add:function(id){
$("#"+id).on("click",function(e){
$.post(Email.con+"userController.php",{
showMail:"true",
emailType:this.dataset.emailType,
},
function(data,status){
if(status==='success'){
$("body").append(data);
Email.init();
}
});
});
return this;
},
}
The problem is with the send function as the path in the $.post ajax call is not correct. When add is called it finds the userController which is in a folder system something like
*
*application
*
*controllers
-userController.php
*public
So the path "../application/controllers/userController.php" steps back one out of public and down the path to the controller.
In send the path is always appended to the site root or public folder and returns something like http://theSite/application/controllers/userController.php
Why is the send ajax call not using a relative path from the site root to the controller in the once case?
There must be 50 other ajax calls that work correctly on the site.
A: The ajax.post request goes to a Url, and not to a file path.
It depends on the rewrites active on the Apache, and the php router in place, which file is associated to which Url.
I don't know what framework you are using, but it's very unlikely to use requests like http://theSite/application/controllers/userController.php .
Most likely it should be something like http://theSite/user, or maybe http://theSite/user.php, or in your code
$.post(Email+"/user",{
...
}
A: My assumption is that the "email window" is loaded from a different URL therefore upon triggering send the path is interpreted differently by the browser. Try setting con to "/application/controllers/" to see if that solves the problem. If not, I would check the URL of the window that is popped up in the browser as it may be loading from a slightly different URL, hence, why the relative path works for add but not send.
| |
doc_2789
|
I put all the "titles" in a list View and what I have to do is:
when anyone click on the title, it should be redirected to its corresponding url. I have a logic but am getting problem to implement it.
I thought of getting Position of the title clicked, then fetching the particular url from database using its ID(primary key) and then redirect it. but I couldn't implement it. I couldn't understand how to relate ID, title's position from listView and the corresponding url.
can someone please help me to solve this, or if any better suggestion to solve, for this kind of problem?
A: I would recommend making a plain Java object of this format
public class WebLink {
int id;
String title, url;
public String toString() { return this.title; }
}
(Name the class what you wish, add setters, getters, etc.)
The important piece, in my opinion, is the toString method. Reason being that loading these objects into an ArrayAdapter<WebLink> will show the title without much extra work. For example, using the android.R.layout.simple_list_item_1 layout.
Then, if you can fill an Arraylist with these objects created from the full database row, then it's very straightforward to get the object from the adapter and have direct access to all that data.
All in all, don't query the database a second time (once for the list, and again to search for the title / id)
| |
doc_2790
|
What limitations exist to Forms Security and why would someone want to write their own authentication?
A: One of the limitations of the out-of-the-box providers is the ProfileProvider. It stores all of the profile information for a user in a single database field, making it difficult to query directly.
Luckily there is a good Table based provider described here in Scott Guthrie's blogg:
http://weblogs.asp.net/scottgu/archive/2006/01/10/435038.aspx
But generally, i would use the standard Membership provider and controls. They are well tested and they save a lot of coding.
Apart from that, the use of Guids foir all of the Ids annoys me as I prefer ints. I know, Guids are not limited to a couple of billion users, but none of my sites have had that many people register yet.
A: I've used ASP.NET Membership extensively and have written several website security schemes in .NET.
I don't know of any gaping security holes in .NET Membership. There are some various concerns such as storing login credentials in a database, but for most purposes you can configure the Membership options so it's relatively safe. You can add password salt, minimum/max pass length, complexity options, pass attempts, etc. In some larger companies they prefer to use ActiveDirectory or Kerberos authentication because the accounts can be controlled by domain or zone admins. .NET Membership DOES support those authentication methods.
The biggest issues I have run into using it are:
*
*The API itself isn't really abstracted to the level (and with the power) that it needs to be. If you need to programatically delete a user or reset a password, while completely possible, it's more work than you'd expect if you're not using the .NET login/account controls, which you probably won't be as they are geared towards the user and not toward account management.
*There's no built in web services to access the accounts, which isn't always necessary, but it would have been nice.
*Managing accounts is a bear as you have to write your own controls for it, and point #1 makes that a cumbersome task. There are several 3rd party controls you can purchase to make this more bearable.
*Extending the capabilities with things like subgroups/subaccounts, tiered roles, etc can be very hackish and challenging.
In agreement with Daniel, though, for most purposes it works fine and will save you a lot of work. It's tested, it has a truckload of options, and it works well.
A: Writing your own login controls has long been a recipe for disaster. In fact, I think it was flagged as an OWASP Top 10 (security) problem for a couple of years running.
| |
doc_2791
|
CACHE MANIFEST
NETWORK:
/
Similarly, using * wildcard allows all resources:
CACHE MANIFEST
NETWORK:
*
Empty NETWORK segment rejects all connections anywhere:
CACHE MANIFEST
NETWORK:
Such network policy rules would be neat. Especially the / domain-lock looks to be a sweet little roadblock for XSS attacks. Do the browser implementations differ in this aspect or is it by the book and safe to use this as a basic level network filter, an another layer of a web app's "firewall"?
| |
doc_2792
|
My approach is using replace. However, I am getting the following errors.
Uncaught SyntaxError: Unexpected string
I know
console.log(text.value[langID]) would output bunch of texts.
but I got the error when I changed my codes to this.
console.log(text.value[langID].replace('/\n|<br>|\s/g', ''));
I am not sure what went wrong here and if my rex pattern can filter my requirements.
Can anyone gives me a hint?
Thanks so much!
A: You missed the comma separator for replace parameters. Also, as @Ingo Bürk pointed out, quotes for regex expression are not valid so you have to remove them too
console.log(text.value[langID].replace(/\n|<br>|\s/g,''));
| |
doc_2793
|
object nullObj = null;
short works1 = (short) (nullObj ?? (short) 0);
short works2 = (short) (nullObj ?? default(short));
short works3 = 0;
short wontWork = (short) (nullObj ?? 0); //Throws: Specified cast is not valid
A: The result of the null-coalescing operator in the last line is a boxed int. You're then trying to unbox that to short, which fails at execution time in the way you've shown.
It's like you've done this:
object x = 0;
short s = (short) x;
The presence of the null-coalescing operator is a bit of a red-herring here.
A: Because 0 is an int, which is implicitly converted to an object (boxed), and you can't unbox a boxed int directly to a short. This will work:
short s = (short)(int)(nullObj ?? 0);
A boxed T (where T is a non-nullable value type, of course) may be unboxed only to T or T?.
| |
doc_2794
|
<?xml version="1.0" encoding="UTF-8"?>
<test>
<id>01O5</id>
<message codage="UUENCODE"><![CDATA[begin 644 encoder.bufM,C8W.SQ3S4[0S$Q,30Q,#8Q,#$P,3]]>CU#/U_SEY[]@]MY84)8[<J?IF^>8'6_Z(__N'7C+]\^.HO?U'SAZ]^P)APS"JMC>!>LIXX
]]>
</message>
</test>
as you can see inside message i have in the midlle a ]]> that means CDATA end! but end of cdata is later in the xml, so unmarshall not working with jaxb
How can i tell jaxb to find CDATA end at the end of the tag and not at the middle of the xml?
thanks for help
| |
doc_2795
|
# function that prompts the user for a name and returns it
def user():
name = input("Please enter your name: ")
return name
# function that receives the user's name as a parameter, and prompts the user for an age and returns it
def userAge(name):
age = input("How old are you, {}? ".format(name))
return age
# function that receives the user's name and age as parameters and displays the final output
def finalOutput(name, age):
age2x = int(age) * 2
print("Hi, {}. You are {} years old. Twice your age is {}.").format(name, age, str(age2x))
###############################################
# MAIN PART OF THE PROGRAM
# implement the main part of your program below
# comments have been added to assist you
###############################################
# get the user's name
user()
# get the user's age
userAge("name")
# display the final output
finalOutput("name", "age")
A: You're not storing the values the user supplies, or passing them back to your function calls, here:
user()
userAge("name")
finalOutput("name", "age")
Change the above lines to:
name = user()
age = userAge(name)
finalOutput(name,age)
A: Correction 1:
Don't pass arguments with double quotes, that means you are passing a string literal to the function not actual value of variable.
for example, if you assign variable name as "Jhon" and you pass it to the function as userAge("name") means you are passing string literal "name" to userAge() not variable value "Jhon".
def printName(name):
print(name)
name = "jhon"
printName("name")
output: name
def printName(name):
print(name)
name = "jhon"
printName(name)
output: jhon
Better assign the return value to some Valerie and pass without double quotes as mentioned by @TBurgis.
Correction 2:
Syntax mistake in print statement. Correct syntax should be
print("Hi, {}. You are {} years old. Twice your age is {}.".format(name, age, str(age2x)))
| |
doc_2796
|
Is there a method for accepting input from a user that can be a custom range of integers, such as 1-250?
I want to accept a range of workstation names from a user, like 1-250, where each number within the range can be looped through, and sent to a different command depending on the number.
Workstation names could be in the number format of 3 possiblities: w0001, w0010, or w0100. So if I entered 1-250, it could be any one of those 3 formats: 3 leading zeros for a single digit, 2 leading zeros for double digit, or 1 leading zeros for triple digits.
Something Like this, using the SC query command just as an example:
set "range="
set /p range="Please enter workstation range:"
DO(if %range% > 0)
(
IF %range% = 1
DO SC \\W000%range% query
IF %range% = 10
DO SC \\W00%range% query
IF %range% = 100
DO SC \\W0%range% query
)
I was looking into FOR /L or FOR /F but they only seem to be able to accept something like (1,1,10) or (filename.txt).in the "set" field. I need a user to be able to enter something simple like 1-250.
Thanks in advance.
A: It's not quite clear to me what you are asking.
To iterate a range outputting a number with four places try this:
@echo off & setlocal enabledelayedexpansion
set "range="
set /p range="Please enter workstation range:"
set "start="
set "stop="
for /f "tokens=1,2 delims=-" %%A in ("%range%") do Set /A "start=%%A+10000,stop=%%B+10000"
if defined stop if %start% leq %stop% for /l %%L in (%start%,1,%stop%) do (
set "L=%%L"
Echo Processing \\w!L:~-4!
Rem do whatever you like with the value
)
Sample run:
> SO_46410755.cmd
Please enter workstation range:1-120
Processing \\w0001
Processing \\w0002
Processing \\w0003
Processing \\w0004
Processing \\w0005
Processing \\w0006
Processing \\w0007
Processing \\w0008
Processing \\w0009
Processing \\w0010
Processing \\w0011
Processing \\w0012
...
Processing \\w0096
Processing \\w0097
Processing \\w0098
Processing \\w0099
Processing \\w0100
Processing \\w0101
Processing \\w0102
...
Processing \\w0117
Processing \\w0118
Processing \\w0119
Processing \\w0120
*
*The first for /f splits the var range content at the minus/hyphen into two parts and stores the 1st into start adding 10000 and the 2nd into stop also adding 10000.
*for /l iterates the range from start (with step 1) to stop.
*to use substrings we need a normal variable so the for variable %%Lis stored in the variable L
*as this happens in a (code block in parentheses) we need delayedexpansion
| |
doc_2797
|
I have this XML
<root>
<subscribers nullDays="5">
<subscriber>
<ThumbURL>
http://cs323321.userapi.com/v323321550/eea/iakdB20fx20.jpg
</ThumbURL>
</subscriber>
<subscriber>
<ThumbURL>
http://cs323321.userapi.com/v323321550/f24/CQ-Zm0_BWnQ.jpg
</ThumbURL>
</subscriber>
...
<subscriber>
<ThumbURL>...</ThumbURL>
</subscriber>
</subscribers>
</root>
After XSLT I get HTML where subscriber will be separated into each div with img tag inside.
Question
How I can generate div equals nullDays attribute using xsl:for-each? Following code requires subscriber nodes more than nullDays, but it cannot be exist:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output encoding="UTF-8" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"xml:base="http://www.w3.org/1999/xhtml" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" indent="yes"/>
<xsl:template match="root">
<xsl:element name="html">
<xsl:element name="head"/>
<xsl:element name="body">
<xsl:variable name="nullDays" select="subscribers/@nullDays"/>
<xsl:for-each select="subscribers/subscriber">
<xsl:if test="(position() mod $nullDays) = 0">
<xsl:element name="div">
<xsl:attribute name="class">empty-div</xsl:attribute>
</xsl:element>
</xsl:if>
</xsl:for-each>
</xsl:element>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
Thank you!
A: This XSLT 1.0 transformation:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="subscribers">
<html>
<xsl:apply-templates select="subscriber"/>
<xsl:call-template name="genEmpty">
<xsl:with-param name="pTimes" select="@nullDays - count(subscriber)"/>
</xsl:call-template>
</html>
</xsl:template>
<xsl:template match="subscriber">
<div><img src="{normalize-space(ThumbURL)}"/></div>
</xsl:template>
<xsl:template name="genEmpty">
<xsl:param name="pTimes" select="0"/>
<xsl:if test="$pTimes >= 0">
<div class="empty-div"/>
<xsl:call-template name="genEmpty">
<xsl:with-param name="pTimes" select="$pTimes -1"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
when applied on the provided XML document:
<root>
<subscribers nullDays="5">
<subscriber>
<ThumbURL>
http://cs323321.userapi.com/v323321550/eea/iakdB20fx20.jpg
</ThumbURL>
</subscriber>
<subscriber>
<ThumbURL>
http://cs323321.userapi.com/v323321550/f24/CQ-Zm0_BWnQ.jpg
</ThumbURL>
</subscriber>
...
<subscriber>
<ThumbURL>...</ThumbURL>
</subscriber>
</subscribers>
</root>
produces (what I guess is) the wanted result:
<html>
<div><img src="http://cs323321.userapi.com/v323321550/eea/iakdB20fx20.jpg"></div>
<div><img src="http://cs323321.userapi.com/v323321550/f24/CQ-Zm0_BWnQ.jpg"></div>
<div><img src="..."></div>
<div class="empty-div"></div>
<div class="empty-div"></div>
<div class="empty-div"></div>
</html>
| |
doc_2798
|
I need the following to be achieved
*
*Make the mail id that the user gave on registration available to the main page
My code for this
//Code in registration page for fetching mail id
protected void Page_Load(object sender, EventArgs e)
{
Session["txt1"] = TextBoxname.Text;
}
//code for displaying the mail id fetched from registration page
protected void Page_Load(object sender, EventArgs e)
{
WelcomeUsername.Text = (string)Session["txt1"];
}
I am not able to display the mail id because the registration page is used only for a single time that is during registration but if a regular user logs in the user will fill details in login page.So how can I make the registration details available to main page in case of regular user(one who is not using registration page each and every time).Please help.I am new to .Net.Thanks in advance
A: Be aware that Session won't last forever.
Pseudocode would be something considering that you want to do the way you mentioned:
*
*Store user data somewhere (database, file, etc.) and store ID in the Session
*Get ID from the Session
*Find the required ID in the database and retrieve the needed info (in your case e-mail)
A: its simple use, put the email textbox value below here
formsauthentication.setauthCookie(email.text,false)
and use asp:loginView for login thats it ,hope this helps you
| |
doc_2799
|
The original values look like this
802-2553
802-1753
802-5589
103-4569
103-54879
303-1542
303-6589
502-1236
What I'm trying to do is replace all cells with 802 as the first 3 characters with the Text Vehicle Loans, 103 with the text Home Loans and 303 with Saving Accounts, 502 with Other Loans
So the end result is
Vehicle Loans
Vehicle Loans
Vehicle Loans
Home Loans
Home Loans
Savings Accounts
Savings Accounts
Other Loans
I tried with the Substitute Function, but it seems that function won't work for something like this.
What other way to achieve this?
A: Try combining IF and LEFT:
=IF(LEFT(A1,3)="802","Vehicle loans", IF(LEFT(A1,3)="103","Home loans",IF(LEFT(A1,3)="303","Saving account",IF(LEFT(A1,3)="502","Other account","Unknown account"))))
Use in an adjoining cell and copy and paste values.
A: I wquld use a formula and a lookup table.
Construct your ReplacementTable
Then, with your data starting in A2, try this formula:
=VLOOKUP(--LEFT(A2,FIND("-",A2)-1),ReplacementTable,2,FALSE)
ReplacementTable Refers To: =Sheet1!$E$2:$F$6
Since I entered the "prefix" as a number in the lookup table, I have to use a number to do the lookup -- hence the double unary -- preceding the LEFT function in the formula.
A: Both the answers above are excellent.
Or you could just use search and replace. It's quick and dirty.
*
*Ctrl-H
*Find what: "802-"
Put the hyphen in so that it doesn't find values within the cell.
*Replace with: "Vehicle Loans"
*Repeat for the other codes you want to replace: 103, 303, etc
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.