text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Multiple ng-switch-when directives in a single HTML tag
Below is a simplified version of what I want to do.
<div ng-switch on='stepNumber' >
<div ng-switch-when="1" ng-switch-when="2" ng-switch-when="3" >One, Two, Three</div>
<div ng-switch-when="4" >Four</div>
<div ng-switch-when="5" ng-switch-when="10">Five, Ten</div>
</div>
The complex version doesn't seem to work, and the code would be confusing for people to review.
A:
You need to write separate element with ng-switch-when for each condition:
PLUNKER
Step Number: <input type="text" ng-model="stepNumber">
<div ng-switch on="stepNumber">
<div ng-switch-when="1">One, Two, Three</div>
<div ng-switch-when="2">One, Two, Three</div>
<div ng-switch-when="3">One, Two, Three</div>
<div ng-switch-when="4">Four</div>
<div ng-switch-when="5">Five, Ten</div>
<div ng-switch-when="10">Five, Ten</div>
</div>
Note: This requires AngularJS v1.1.3+
OR, if you're on AngularJS v.1.1.5+ than ngIf might be cleaner solution:
PLUNKER
Step Number:
Step Number: <input type="text" ng-model="stepNumber">
<div ng-if="stepNumberWithin(['1', '2', '3'], stepNumber)">One, Two, Three</div>
<div ng-if="stepNumberWithin(['4'], stepNumber)">Four</div>
<div ng-if="stepNumberWithin(['5', '10'], stepNumber)">Five, Ten</div>
myApp.controller('MyCtrl', function($scope) {
$scope.stepNumberWithin = function(arr, number){
console.log(arr, number);
return arr.indexOf(number) !== -1;
}
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to change column name in laravel?
I am a beginner of laravel. Now, I would like to retrieve data from database using this code:
$data = Model::select('col1', 'col2', 'col3')->get();
and return $data to another view.
However, I would like to change the name of the columns. For example, changing col1 to column_1 before returning the array to the view. How can I change the column names? I am now using laravel 5.5. Thank you very much!
A:
you can use selectRaw() method.
$data = Model::selectRaw('col1 as c1, col2 as c2, col3 as c3')->get();
Note that, all columns must be in the same string value.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Docker postgress User "postgres" has no password assigned
I keep getting
User "postgres" has no password assigned.
updated
.env
POSTGRES_PORT=5432
POSTGRES_DB=demo_db2
POSTGRES_USER=postgres
POSTGRES_PASSWORD=password
Even though the postgres password is set.
I'm trying to use the same variables from the following command
docker run --name demo4 -e POSTGRES_PASSWORD=password -d postgres
Could this be an issue with volumes ? im very confused.
I ran this command as well
docker run -it --rm --name demo4 -p 5432:5432 -e POSTGRES_PASSWORD=password -e POSTGRES_USER=postgress postgres:9.4
docker-compose.yml
# docker-compose.yml
version: "3"
services:
app:
build: .
depends_on:
- database
ports:
- 8000:8000
environment:
- POSTGRES_HOST=database
database:
image: postgres:9.6.8-alpine
volumes:
- pgdata:/var/lib/postgresql/pgdata
ports:
- 8002:5432
react_client:
build:
context: ./client
dockerfile: Dockerfile
image: react_client
working_dir: /home/node/app/client
volumes:
- ./:/home/node/app
ports:
- 8001:8001
env_file:
- ./client/.env
volumes:
pgdata:
A:
You are missing the inclusion of the .env file...
Docker composer:
database:
environment:
- ENV_VAR=VALUE
or
database:
env_file:
- .env
Plain Docker:
docker run options --env ENV_VAR=VALUE ...
or
docker run options --env-file .env ...`
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to implement zoom & pan in Libgdx Java?
I would like to add a zoom and pan mechanic to my game but everything I have looked up on the web has been complete and utter failure.
If you could give me a good example of implementing these functions that would be sweet.
Here is the class I'm trying to get it to work in.
package com.adam.finis.screens;
import com.adam.finis.Main;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.input.GestureDetector;
import com.badlogic.gdx.input.GestureDetector.GestureListener;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
public class Play extends ApplicationAdapter implements Screen, GestureListener, ApplicationListener{
//Core Variables
private Main game;
public static InputMultiplexer inputMultiPlex;
//Texture Variables
Texture Title;
private TmxMapLoader mapLoader;
private TiledMap map;
private OrthogonalTiledMapRenderer renderer;
//Sprite Variables
public static boolean spawnSprite = false;
//Font
private BitmapFont font;
//Window Variables
private OrthographicCamera gameCam;
private Viewport gamePort;
private PlayHud hudPlay;
private int mapX = 1952;
private int mapY = 1952;
private int mapHalfX = mapX / 2;
private int mapHalfY = mapY / 2;
public static boolean GAME_PAUSED = false;
//Random Variables
private Vector2 dragOld, dragNew;
public static Vector2 worldSize;
//DEBUG
private String message;
private Texture debugTexture;
private Sprite debugSprite;
public Play(Main game){
this.game = game;
gameCam = new OrthographicCamera();
gameCam.setToOrtho(false, Main.V_WIDTH, Main.V_HEIGHT);
gamePort = new FitViewport(Main.V_WIDTH, Main.V_HEIGHT, gameCam);
hudPlay = new PlayHud(game.sb);
mapLoader = new TmxMapLoader();
map = mapLoader.load("images/level1.tmx");
renderer = new OrthogonalTiledMapRenderer(map);
gameCam.position.set(mapHalfX, mapHalfY, 0);
GestureDetector gd = new GestureDetector(this);
inputMultiPlex = new InputMultiplexer();
inputMultiPlex.addProcessor(hudPlay.stage);
inputMultiPlex.addProcessor(hudPlay.debugStage);
inputMultiPlex.addProcessor(gd);
Gdx.input.setInputProcessor(gd);
debugTexture = new Texture(Gdx.files.internal("images/house.png"));
debugSprite = new Sprite(debugTexture);
worldSize = new Vector2(mapX, mapY);
font = new BitmapFont(Gdx.files.internal("fonts/lemonMilk.fnt"),false);
font.setColor(Color.RED);
}
@Override
public void show() {
}
public void handleInput(float dt){
//Keyboard Settings
if (Gdx.input.isKeyPressed(Input.Keys.W)) {
gameCam.position.y += 350 * dt;
}
if (Gdx.input.isKeyPressed(Input.Keys.A)) {
gameCam.position.x -= 350 * dt;
}
if (Gdx.input.isKeyPressed(Input.Keys.S)) {
gameCam.position.y -= 350 * dt;
}
if (Gdx.input.isKeyPressed(Input.Keys.D)) {
gameCam.position.x += 350 * dt;
}
//ZOOM
if (Gdx.input.isKeyPressed(Input.Keys.O)) {
gameCam.zoom += 1.5f * dt;
}
if (Gdx.input.isKeyPressed(Input.Keys.P)) {
gameCam.zoom -= 1.5f * dt;
}
//CAMERA BOUNDS
gameCam.zoom = MathUtils.clamp(gameCam.zoom, 0.1f, mapX / gameCam.viewportWidth);
//|
float camX = gameCam.position.x;
float camY = gameCam.position.y;
//|
Vector2 camMin = new Vector2(gameCam.viewportWidth, gameCam.viewportHeight);
Vector2 camMax = new Vector2(1952, 1952);
//|
camMin.scl(gameCam.zoom/2);
camMax.sub(camMin);
//|
camX = Math.min(camMax.x, Math.max(camX, camMin.x));
camY = Math.min(camMax.y, Math.max(camY, camMin.y));
gameCam.position.set(camX, camY, gameCam.position.z);
//------------------------------------------------------------------------------------
//Touch Settings
if (Gdx.input.justTouched()){
dragNew = new Vector2(Gdx.input.getX(), Gdx.input.getY());
dragOld = dragNew;
}
if (Gdx.input.isTouched()){
dragNew = new Vector2(Gdx.input.getX(), Gdx.input.getY());
if (!dragNew.equals(dragOld)){
gameCam.translate(dragOld.x - dragNew.x, dragNew.y - dragOld.y);
dragOld = dragNew;
}
}
}
public void update(float dt){
handleInput(dt);
gameCam.update();
renderer.setView(gameCam);
}
@Override
public void render(float delta) {
if(GAME_PAUSED == false){
update(delta);
//CLEAR SCREEN - BLACK
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//INIT ALL INPUT
Gdx.input.setInputProcessor(inputMultiPlex);
//RENDER MAP
renderer.setView(gameCam);
renderer.render();
//DRAW
if(spawnSprite == true){
game.sb.begin();
game.sb.draw(debugSprite, 1500, 500);
game.sb.end();
}
//DRAW HUD
hudPlay.stage.getViewport().apply();
hudPlay.stage.act();
hudPlay.stage.draw();
//debug DRAW HUD
hudPlay.debugStage.getViewport().apply();
hudPlay.debugStage.act();
hudPlay.debugStage.draw();
//PROJECTION
game.sb.setProjectionMatrix(gameCam.combined);
game.hudSb.setProjectionMatrix(hudPlay.debugStage.getCamera().combined);
game.hudSb.setProjectionMatrix(hudPlay.stage.getCamera().combined);
if(Main.zoomOut == true){
gameCam.zoom += 1.5f * delta;
}
if(Main.zoomIn == true){
gameCam.zoom -= 1.5f * delta;
}
}
if(GAME_PAUSED == true){
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
Gdx.input.setInputProcessor(inputMultiPlex);
game.sb.setProjectionMatrix(hudPlay.debugStage.getCamera().combined);
hudPlay.debugStage.getViewport().apply();
hudPlay.debugStage.act();
hudPlay.debugStage.draw();
}
}
@Override
public void resize(int width, int height) {
gamePort.update(width, height);
gameCam.viewportWidth = width/5f; //We will see width/32f units!
gameCam.viewportHeight = gameCam.viewportWidth * height/width;
hudPlay.stage.getViewport().update(width, height, true);
hudPlay.debugStage.getViewport().update(width, height, true);
}
@Override
public void pause() {}
@Override
public void resume() {}
@Override
public void hide() {}
@Override
public void dispose() {
game.sb.dispose();
renderer.dispose();
hudPlay.dispose();
font.dispose();
}
@Override
public boolean touchDown(float x, float y, int pointer, int button) {
return false;
}
@Override
public boolean tap(float x, float y, int count, int button) {
message = "TAP";
Gdx.app.log("INFO", message);
return false;
}
@Override
public boolean longPress(float x, float y) {
message = "LONG PRESS";
Gdx.app.log("INFO", message);
return false;
}
@Override
public boolean fling(float velocityX, float velocityY, int button) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean pan(float x, float y, float deltaX, float deltaY) {
message = "PAN";
Gdx.app.log("INFO", message);
return false;
}
@Override
public boolean panStop(float x, float y, int pointer, int button) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean zoom(float initialDistance, float distance) {
message = "Zoom performed";
Gdx.app.log("INFO", message);
return false;
}
@Override
public boolean pinch(Vector2 initialPointer1, Vector2 initialPointer2,
Vector2 pointer1, Vector2 pointer2) {
message = "Pinch performed";
Gdx.app.log("INFO", message);
return true;
}
}
A:
Your own answer is right, but here is an improved version where zooming a second time is performed upon the previous zoom.
Also, camera translation speed is proportional to the current camera zoom.
@Override
public boolean pan(float x, float y, float deltaX, float deltaY) {
message = "PAN";
Gdx.app.log("INFO", message);
gameCam.translate(-deltaX * currentZoom,deltaY * currentZoom);
gameCam.update();
return false;
}
@Override
public boolean zoom(float initialDistance, float distance) {
message = "Zoom performed";
Gdx.app.log("INFO", message);
gameCam.zoom = (initialDistance / distance) * currentZoom;
gameCam.update();
return true;
}
@Override
public boolean panStop(float x, float y, int pointer, int button) {
Gdx.app.log("INFO", "panStop");
currentZoom = gameCam.zoom;
return false;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Finding out where question views come from
Sometimes we get massive peaks in SO, such as this question: Using node.js as a simple web server
At the time of writing, it has 201K views, so I'm guessing it was posted in some site such as reddit, and that's driving the traffic.
I'm simply very curious where that'd be, and was wondering if there's any way to find out in SO, or, since I'm already asking, if anyone knows of any tool that would do the trick. Thanks!
A:
To find some sites that link to a specific URL, you can always just use Google search with the link search parameter, like so:
link: example.com
For example:
https://www.google.com/#q=link:+http:%2F%2Fstackoverflow.com%2Fquestions%2F6084360%2Fnode-js-as-a-simple-web-server
Probably won't list all the sites that link to a particular URL, but you can possibly narrow down your search to see where a majority of the views may be coming from.
A:
There's nothing public and not much more available to moderators:
Is there any analytics information that moderators can access for individual questions?
I don't know whether anything Google has would do the job.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
jQuery how to insert tag after every Semicolon
I am dumping some CSS into a div and I am looking to format it so it is more legible. Basically what I want to do is insert a break tag after every semicolon. I have searched around for a while but can't seem to find something that quite fits what I am trying to do.
I have something like this...
HTML
<div class='test'>
color:red;background-color:black;
</div>
jQuery
var test = $('.test').text();
var result = test.match(/;/g);
alert(result);
And I have tried..
var test = $('.test').text();
var result = test.match(/;/g);
result.each(function(){
$('<br/>').insertAfter(';');
});
alert(result);
Also I have started a fiddle here.. Which basically just returns the matched character...
http://jsfiddle.net/krishollenbeck/zW3mj/9/
That is the only part I have been able to get to work so far.
I feel like I am sort of heading down the right path with this but I know it isn't right because it errors out. I am thinking there is a way to insert a break tag after each matched element, but I am not really sure how to get there. Any help is much appreciated. Thanks...
A:
try it like this
var test = $('.test').text();
var result = test.replace(/\;/g,';<br/>');
$('.test').html(result);
http://jsfiddle.net/Sg5BB/
A:
You can use a normal javascript .replace() method this way:
$(document).ready(function(){
$(".test").html($(".test").html().replace(/;/g, ";<br />"));
});
Fiddle: http://jsfiddle.net/SPBTp/4/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Creating a table using mysqli and php
The table is not created in the database Users and there is no error message at all. PhpMyAdmin is set to allow no password, just to be clear on that point.
CREATE TABLE Users(
ID string(255) NOT NULL,
FirstName string(255) NOT NULL,
Surname string(255) NOT NULL,
DOB date(10) NOT NULL
)
A:
your query should be like this.
$mySql = CREATE TABLE Users(
ID VARCHAR(255) NOT NULL,
FirstName VARCHAR(255) NOT NULL,
Surname VARCHAR(255) NOT NULL,
DOB date NOT NULL
)";
MySQL can't understand string. pass varchar instead of a string.
you don't need to assign the length of date.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Transmit user password for a rest api
I'm designing a REST API and I have some problems in terms of security for authenticating the user.
For authentication I don't want the password to be send across the network in plain text.
To bypass this problem I could send a SHA-256 hash of the password (with the username as salt), so the password is never sent in plain text. In my database I will be storing the following hashes: SHA256(password + salt) and I'll compare if both of the hashes match.
The problem with this option is that I'll have a hash computed with a fast hash algorithm and the salt is not random.
In security the best practice is to use a slow signature algorithm, with a random salt (like bcrypt).
The slow algorithm is not a problem, i could use bcrypt on the client side, but for the salt i don't know what to do:
Bcrypt need a salt with a defined size so i can't put the username
If i'm using a random salt, how the client will know the value of this salt before computing the password's hash?
So i can see 3 options, but none are sastisfying:
I send the password in plain text (I'm using SSL) and i store bcrypt in the db => still vulnerable to man in the middle
I use SHA256 and send the hash where the salt is the username (still using SSL) => the hash in the db are less secure
I use bcrypt and I have a two step process: i ask for the saltfor a given user and then send the hash of this user (still using ssl) => by trying to log in with an other username i can obtain his salt, not awesome
Is anybody has a better solution or some advices?
A:
There a couple of advantages to the approach of hashing on the client side. One of them is the server never gets the real passwords, so if the server is compromised in any way, it still won't get the real password. The other one is, it can lighten the load on the server side if you're planning to use slow hashing.
However, hashing passwords is designed to protect you in case the database is breached and hashes are stolen. This means if someone gets a hold of the hashed passwords, they could still impersonate users by sending the hash. The implication is, even if you hash on the client side, you still need to re-hash on the server.
The other potential downside is that this could alienate part of your userbase that doesn't have JavaScript enabled.
To address your points:
Bcrypt need a salt with a defined size so i can't put the username
Don't use the username as a salt. Salts should be unique, and a username (and derivations thereof) is certainly not unique. By unique I don't mean just unique to the server, but unique everywhere. Use a cryptographic nonce instead.
If i'm using a random salt, how the client will know the value of this salt before computing the password's hash?
Just have the server send the salt (nonce) beforehand. You could do this on the client as well, but the Javascript doesn't have a CSPRNG as far as I know, and you'd still need to send the nonce back to the server.
I send the password in plain text (I'm using SSL) and i store bcrypt in the db => still vulnerable to man in the middle
SSL was designed to prevent man in the middle attacks. Unless it's broken somehow, that's not going to be a problem.
I use SHA256 and send the hash where the salt is the username (still using SSL) => the hash in the db are less secure
Don't use username as a salt. And like I said before, you have to hash on the server side regardless of whether or not you did it on the client side.
I use bcrypt and I have a two step process: i ask for the salt for a given user and then send the hash of this user (still using ssl) => by trying to log in with an other username i can obtain his salt, not awesome
Not awesome indeed.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Output random numbers by line
Alright, so I made this code:
lst1 = tuple(range(1, 13))
table1 = ""
x = 0
while x < len(lst1):
for y in range(0, 3):
table1 += str(lst1[x]) + "\t"
x += 1
table1 += "\n"
print(table1)
#Output in console is:
1 2 3
4 5 6
7 8 9
10 11 12
I would like to make 2 more tables that display other random numbers i.e.: from 0 to 48 lets say but still only 12 numbers from that range would be outputted in that format. I'm fairly new to python and can't seem to figure it out through the random module.
This is one of the lists with the random numbers:
lst3 = tuple(range(0, 48))
table3 = ""
x = 0
while x < len(lst3):
for y in range(0, 3):
table3 += str(lst3[x]) + "\t"
x += 1
table3 += "\n"
print(random.sample(lst3, 12))
#Output is: (so basically just 12 random numbers from 1 to 47 that don't repeat)
[28, 15, 35, 11, 30, 20, 38, 3, 31, 42, 9, 24]
A:
as per my understanding you want something like this:
import random
lst1 = tuple(range(1, 13))
lst2 = random.sample(range(0,48), 12) # increase this 12 as per your requirements
table1 = ""
table2 = ""
x = 0
while x < len(lst1):
for y in range(0, 3):
table1 += str(lst1[x]) + "\t"
x += 1
table1 += "\n"
x = 0
while x < len(lst2):
for y in range(0, 3):
table2 += str(lst2[x]) + "\t"
x += 1
table2 += "\n"
print(table1)
print (table2)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Database is locked -sqlite3
-(void) dropCategories{
if (deleteCategoryStmt == nil) {
const char *deleteSql = "delete from tb_category";
if (sqlite3_prepare_v2(database, deleteSql, -1, &deleteCategoryStmt, NULL) != SQLITE_OK)
NSAssert1(0,@"Error in preparing drop category statement with '%s'", sqlite3_errmsg(database));
else
NSLog(@"NO error in creating drop categories statement");
}
if(SQLITE_DONE != sqlite3_step(deleteCategoryStmt))
NSAssert1(0, @"Error while drop category data. '%s'", sqlite3_errmsg(database));
sqlite3_reset(deleteCategoryStmt);
//sqlite3_finalize(deleteCategoryStmt);
deleteCategoryStmt = nil;
}
Call to this function once works fine but whenever i calls it again it terminates giving the below exception.
Any suggestion Why is such happening?
*** Assertion failure in -[Category dropCategories], /Users/rsplmac/Documents/LiteApp2/Classes/Category.m:171
2010-08-17 14:01:06.648 LiteApp2[4335:207] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Error while drop category data. 'database is locked''
*** Call stack at first throw:
(
0 CoreFoundation 0x02429919 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x025775de objc_exception_throw + 47
2 CoreFoundation 0x023e2078 +[NSException raise:format:arguments:] + 136
3 Foundation 0x000ce8cf -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 116
4 LiteApp2 0x000043ce -[Category dropCategories] + 462
5 LiteApp2 0x00004ba3 -[RootViewController updateMe:] + 1297
6 UIKit 0x002d3e14 -[UIApplication sendAction:to:from:forEvent:] + 119
7 UIKit 0x004db14b -[UIBarButtonItem(UIInternal) _sendAction:withEvent:] + 156
8 UIKit 0x002d3e14 -[UIApplication sendAction:to:from:forEvent:] + 119
9 UIKit 0x0035d6c8 -[UIControl sendAction:to:forEvent:] + 67
10 UIKit 0x0035fb4a -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 527
11 UIKit 0x0035e6f7 -[UIControl touchesEnded:withEvent:] + 458
12 UIKit 0x002f72ff -[UIWindow _sendTouchesForEvent:] + 567
13 UIKit 0x002d91ec -[UIApplication sendEvent:] + 447
14 UIKit 0x002ddac4 _UIApplicationHandleEvent + 7495
15 GraphicsServices 0x02c15afa PurpleEventCallback + 1578
16 CoreFoundation 0x0240adc4 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
17 CoreFoundation 0x0236b737 __CFRunLoopDoSource1 + 215
18 CoreFoundation 0x023689c3 __CFRunLoopRun + 979
19 CoreFoundation 0x02368280 CFRunLoopRunSpecific + 208
20 CoreFoundation 0x023681a1 CFRunLoopRunInMode + 97
21 GraphicsServices 0x02c142c8 GSEventRunModal + 217
22 GraphicsServices 0x02c1438d GSEventRun + 115
23 UIKit 0x002e1b58 UIApplicationMain + 1160
24 LiteApp2 0x00002808 main + 102
25 LiteApp2 0x00002799 start + 53
)
terminate called after throwing an instance of 'NSException'
A:
Your call to sqlite3_finalize appears to be commented. A complete call to sqlite3_prepare_v2 is usually followed by sqlite_step then sqlite3_finalize. Can you try that, without sqlite3_reset?
EDIT: For posterity: asker found the real cause, the database was locked by another object. Above function was fine.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to change size of JTextArea
I have three radio buttons that I want to use to change the size of a JTextArea when I click the buttons.
if(rd_7inch.isSelected())
{
jScrollPane2.setSize(200,200);
txt_sysnp.setSize(5,20);
}if(rd_9inch.isSelected())
{
jScrollPane2.setSize(200,200);
txt_sysnp.setSize(5,25);
}if(rd_10inch.isSelected())
{
jScrollPane2.setSize(200,200);
txt_sysnp.setSize(5,30);
}
A:
It is likely that you components are under the control of a layout manager.
The only means by which you can suggest changes to the size would be to use setColumns and setRows and use a layout manager that respects the preferred size of its components
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TextAreaSize {
public static void main(String[] args) {
new TextAreaSize();
}
public TextAreaSize() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextArea ta;
public TestPane() {
setLayout(new GridBagLayout());
JRadioButton btnSmall = new JRadioButton(new SizeAction("Small", 2, 10));
JRadioButton btnMed = new JRadioButton(new SizeAction("Medium", 4, 15));
JRadioButton btnLarge = new JRadioButton(new SizeAction("Large", 12, 24));
ButtonGroup bg = new ButtonGroup();
bg.add(btnSmall);
bg.add(btnMed);
bg.add(btnLarge);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.NORTHWEST;
add(btnSmall, gbc);
gbc.gridy++;
add(btnMed, gbc);
gbc.gridy++;
add(btnLarge, gbc);
gbc.gridx++;
gbc.gridy = 0;
gbc.gridheight = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.CENTER;
ta = new JTextArea();
add(new JScrollPane(ta), gbc);
btnSmall.doClick();
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
public class SizeAction extends AbstractAction {
private int rows;
private int columns;
public SizeAction(String name, int rows, int columns) {
putValue(NAME, name);
this.rows = rows;
this.columns = columns;
}
@Override
public void actionPerformed(ActionEvent e) {
ta.setRows(rows);
ta.setColumns(columns);
revalidate();
}
}
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to change keyboard layout in Lubuntu 15.10?
I have recently upgraded my PC from Lubuntu 14.10 to 15.10. Before the upgrade my keyboard layout matched my Danish keyboard. But after the upgrade I probably have a standard English/US layout.
Preferences/Language Support, doesn't let me configure the keyboard layout.
Preferences/Keyboard and Mouse, only let me configure stroking delay and similar.
I don't know about iBus and fcitx, as far as the tooltip infomation tells me, its for more complex languages such as Chinese.
I don't have a US icon in the taskbar, no keyboard and/or language icon at all.
Things I have tried:
Running the following in a terminal works, but only until the next reboot:
setxkbmap -layout dk
I got the following parameter in the file /etc/default/keyboard:
XKBLAYOUT="dk"
Installing and running the app Lxkeymap changes the keyboard to Danish when I run it, but rebooting will change the layout back to US.
I don't want anything fancy, I just want to set my keyboard layout to Danish. How can I do that?
A:
Some googling and a test led me to this:
Right click the panel -> Add / Remove Panel Items -> Add -> Keyboard Layout Handler
That adds an icon to the panel, and by right clicking it and selecting "Settings", a GUI tool for managing keyboard layouts shows up.
To add languages, "keep system layout" should be unchecked.
A:
I believe this solution only works if systemd is implemented? It works for me in Lubuntu 16.04. Let's check first if this works.
Go to the terminal and type in
localectl status
You should have this (partically the VC Keymap and X11 layout). If there isn't a command or something, I'm out of ideas.
System Locale: LANG=en_AU.UTF-8
LANGUAGE=en_AU:en_GB:en
VC Keymap: us
X11 Layout: us
If so, the following should fix it.
localectl set-keymap dk
localectl set-x11-keymap dk
I had set the GB keyboard instead of the US keyboard myself so my situation is quite similar. Unfortunately I don't have much know-how so maybe the following has changed more than you would want, but I haven't experienced any problems myself.
Solution adapted from Meuh's answer: https://unix.stackexchange.com/a/307767
|
{
"pile_set_name": "StackExchange"
}
|
Q:
BigQuery select statement alias is not working in where clause
I tried given below query, but it throw error RANK is not defined.
SELECT
EmailAddress
, FirstName
, LastName
, RANK() OVER (ORDER BY BookingDate) AS RANK FROM `table_name`
WHERE RANK BETWEEN 5 AND 7
A:
Below is for BigQuery Standard SQL
WHERE clause is evaluated before output of query is formed and assigned aliases, which means that field rank is not available at a time when WHERE rank BETWEEN 5 AND 7.
You just need to use below
#standardSQL
SELECT * FROM (
SELECT
EmailAddress
, FirstName
, LastName
, RANK() OVER (ORDER BY BookingDate) AS rank
FROM `project.dataset.table`
)
WHERE rank BETWEEN 5 AND 7
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What part of speech is 'echoes' when not a noun plural?
For example in the sentence: "I will say it loud enough so that it echoes"
What part of speech is 'echoes'? Would it become a verb or an adverb?
A:
'Echoes' is not plural here; it is a third-person singular verb.
An adverb cannot take a plural marker in English:
(1) *They go hastilies.
In addition, an adverb modifies an adjective, adverb or verb in English. In this sentence, 'echoes' is a predicate and is not modifying an adjective, adverb or verb, thus we should not consider it an adverb.
By contrast, the verb is the only category in English which can head a predicate. It can also take the -s marker, which expresses the third person and singular number of the subject. This is a type of subject-verb agreement, which in turn is a kind of head-marking. It marks the grammatical relationship of 'subject' between the subject 'it' and the verb 'echo'.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Splitting an RGB uint into its separate R G B components
I have an RGB colour stored as a uint. I can create this from the RGB values using the bitwise left and bitwise or operator in an expression like this:
colour = r<<16 | g<<8 | b;
I want to do the opposite. I have the final number and I want the r, g and b values. Does anyone know how to do this?
A:
r = (colour >> 16) & 0xff;
g = (colour >> 8) & 0xff;
b = colour & 0xff;
A:
Something like this:
r = ( colour >> 16 ) & 0xFF;
g = ( colour >> 8 ) & 0xFF;
b = colour & 0xFF;
Assuming 8-bit component values. The bitwise-and hex 0xFF masks pick out just the 8-bits for each component.
A:
You use shift, and then the & operator to mask out unwanted bits:
r = color >> 16;
g = (color >> 8) & 255;
b = color & 255;
Alternatively:
b = color & 255;
color >>= 8;
g = color & 255;
r = color >> 8;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to use ILMerge to combine several assemblies into one
I've been looking for the way to combine multiple dlls into an exe, then I find that ILMerge is a good tool to do it. but after downloading ilmerge 3.0.40 nuget package, I don't know what to do next.
I have found a reference : ILMerge Best Practices(ILMerge Best Practices), but it didn't show specific steps for me.
what do I need to do?
A:
Finally, I find the solution:
After installing the package and building the application, I copy all files in net452(solution packages folder -> ILMerge folder -> tools -> net452).Then I paste it to the path my app built(\bin\Debug).
Then I open the command prompt and cd to my directory and insert the following code:
ILMerge.exe /target:winexe /target:exe /out:filepath nameofexe mydll
It works well!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Sails.js Can I add sort functionality to default find action without overriding it?
I was just curious to know if it's by any means possible to add a sort functionality to the default find action of a model without overriding the same in the controller ?
We do have beforeCreate and afterCreate features in the models which is quite useful in many cases. Similarly beforeFetch or something like that, if exists can be really useful when we want some pre/post processing on the result set while doing a get request.
A:
An example of this would be: localhost:1337/user?sort=id desc
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Custom URL for entity create and view
I am using ECK (Entity Construction Kit) to create my custom entities. Now I want to create custom url for various operation on my entities such as create (example.com/my-entity/create) or view (example.com/my-entity/view/custom-unique-field)
I have tried pathauto but it seems I cant define custom patterns for my own entities. Any help towards this step is highly appreciated.
Thanks,
Naveen
A:
You can use the path (url alias) module for the create path. Since that's a single url, you can create a single path alias to change that.
It's a bit harder for your custom entities. You would have to create a custom module and integrate with path auto module to be able to create path aliases for the view urls of your custom entities. It's a lot of code, you can see how the path auto module does it for the node module. But be warned, it's not easy as there are many parts.
The gist of it is that you need to make some tokens available for the path system you are going to make, like the entity label and such. Then you need to create a function that can create an alias when given an entity. This is, however, a bit harder since you need to use the path auto API functions for this.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Show that if $ |f( \frac{1}{n}) | \leq \frac{1}{n!}$ then $0$ is an essential singularity
Given holomorphic non-constant function $f:D(0,1) \smallsetminus \{0\} \rightarrow \mathbb{C}$ so $\forall n=2,3,...:\ |f(\frac{1}{n})| \leq \frac{1}{n!}$ I need do show that $0$ is an essential singularity.
I tried expanding $f$ to it's Laurent series near $z_0 = 0$ and compute coefficients by:
$$a_{-k} = \frac{1}{2 \pi i} \int_{|z|=r} z^{n-1}f(z)dz$$
and take $r= \frac{1}{n}$ so
$$a_{-k} = \frac{1}{2 \pi i} \int_{|z|=\frac{1}{n}} z^{n-1}f(z)dz $$
But I don't know how to if it's a fertile direction nor how to proceed if it is.
A:
Suppose the singularity is removable. Then $f(0) = \lim_{n\to\infty} f(1/n) = 0$, so we may write $f(z) = z^k g(z)$ for some $k\in \mathbb{N}$ and $g$ holomorphic with $g(0) \neq 0$. In a small enough neighborhood around $0$, we may assume $|g| > C > 0$. Thus, in this neighborhood, we have $|f(z)| > C |z|^k$. For large enough $n$, it follows that $Cn^{-k} < 1/n!$, contradiction.
Similarly: suppose the singularity is a pole. Write $f(z) = g(z)/z^k$ where $g(0)\neq 0$. Then in a small enough neighborhood of $0$, we have $|f(z)| > C|z|^{-k}$ so for large enough $n$, it must be true that $1/n! > Cn^k$, contradiction.
A:
Hint:
Does $$\lim_{z\to0}f(z)=L$$ exist? (For finite or infinite $L$)
Suppose it does, and because $1/n\to0$ then $|L|\leq0\to L=0$. Now, you must check that this value is possible.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Init Object with different parameters
I have an object and I call it many times in my page, but with different parameters.
var lazyLoad = (function () {
var CONFIG = {
block: '',
url: ''
}
function work(){
window.d = document
var buffer = ''
d.write = d.writeln = function(s){ buffer += s }
d.open = d.close = function(){}
s = d.createElement('script')
s.setAttribute('type','text/javascript')
s.setAttribute('src',CONFIG.url)
d.getElementById(CONFIG.block).appendChild(s)
s.onload = function () {
window.setTimeout(function() {
console.warn(CONFIG.block + ' ' + buffer)
d.getElementById(CONFIG.block).innerHTML += buffer
buffer = ''
}, 0)
}
}
return {
init: function (options) {
$.extend(CONFIG, options);
random = $('#'+CONFIG.block).attr('rel')
id = $('#'+CONFIG.block).attr('id').replace(random,'')
id = id.replace('DIV','')
size = id.split('X')
ele_width = size[0] || CONFIG.width
ele_height = size[1] || CONFIG.height
$('#'+CONFIG.block).css({
'width':ele_width+'px',
'height':ele_height+'px',
'background':'url(/static/i/ajax-loading-black.gif) no-repeat center center'
})
console.log(CONFIG.block)
$(window).load(function(){
work()
})
}
}
})();
I call it like this:
lazyLoad.init({
url: 'http://example.com/test1.js',
block: DIVID1
})
Than
lazyLoad.init({
url: 'http://test.com/test2.js',
block: DIVID2
})
And than:
lazyLoad.init({
url: 'http://testdomain.com/test3.js',
block: DIVID3
})
After loading the document I see that each div has width and height, which is applied with this script, but buffer was inserted only in last div.
A:
The problem is that CONFIG is declared in the outer function, since javascript is all single threaded(ignore WebWorkers here =)) at the timeyour work function is called the values in CONFIG are the right ones. But since every time you do $.extend(CONFIG, options); you change the same object by the time s.onload is fired the value left in CONFIG.block is the last one used. Try:
var lazyLoad = (function () {
//var CONFIG = {
// block: '',
// url: ''
//}
function work(options){
window.d = document
var buffer = ''
d.write = d.writeln = function(s){ buffer += s }
d.open = d.close = function(){}
s = d.createElement('script')
s.setAttribute('type','text/javascript')
//s.setAttribute('src',CONFIG.url)
//d.getElementById(CONFIG.block).appendChild(s)
s.setAttribute('src',options.url)
d.getElementById(options.block).appendChild(s)
s.onload = function () {
window.setTimeout(function() {
//console.warn(CONFIG.block + ' ' + buffer)
//d.getElementById(CONFIG.block).innerHTML += buffer
console.warn(options.block + ' ' + buffer)
d.getElementById(options.block).innerHTML += buffer
buffer = ''
}, 0)
}
}
return {
init: function (options) {
var CONFIG = {
block: '',
url: ''
}
$.extend(CONFIG, options);
random = $('#'+CONFIG.block).attr('rel')
id = $('#'+CONFIG.block).attr('id').replace(random,'')
id = id.replace('DIV','')
size = id.split('X')
ele_width = size[0] || CONFIG.width
ele_height = size[1] || CONFIG.height
$('#'+CONFIG.block).css({
'width':ele_width+'px',
'height':ele_height+'px',
'background':'url(/static/i/ajax-loading-black.gif) no-repeat center center'
})
console.log(CONFIG.block)
$(window).load(function(){
//work()
work(CONFIG)
})
}
}
})();
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Maximum and minimum value of a function.
Let us consider a function $f(x,y)=4x^2-xy+4y^2+x^3y+xy^3-4$. Then find the maximum and minimum value of $f$.
My attempt. $f_x=0$ implies $8x-y+3x^2y+y^3=0$ and $f_y=0$ implies $-x+8y+x^3+3xy²=0$ and $f_{xy}=3x^2+3y^2-1$. Now $f_x+f_y=0$ implies $(x+y)((x+y)^2+7)=0$ implies $x=-y$ as $x$ and $y$ are reals. Now putting it in $f_x=0$ get the three values of $x$ as $0$, $(-3+3\sqrt{5})/2$ and $(-3-3\sqrt{5})/2$. And then $f_{xy}(0,0)<0$ implies $f$ has maximum at $(0,0)$. But at other two points $f_{xy}$ gives the positive value. So how can I proceed to solve the problem.
Please help me to solve it.
A:
Note that $f(x,y)=(xy+4)(x^2+y^2-1)$ and therefore
$$\lim_{x\to+\infty}f(x,x)=\lim_{x\to+\infty}(x^2+4)(2x^2-1)=+\infty$$
and
$$\lim_{x\to+\infty}f(x,-x)=\lim_{x\to+\infty}(-x^2+4)(2x^2-1)=-\infty.$$
What may we conclude?
P.S. The critical point $(0,0)$ is a local minimum.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
vb.net scrollable content panel
Is there a control in vb.net that is specifically designed for displaying content larger than the control itself?
I know it's possible to code your own using a panel and two scrollbars, but is there an already existing method for this?
Thanks for your help
A:
All control containers, such as Panel, FlowLayoutPanel etc. have AutoScroll property, which does what you want.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can someone identify and list the actors in the preview for The Fall of Five?
There was this official video preview of The Fall of Five on August 23, four days before it was released. Does this mean that they are going to produce a movie from The Fall of Five when they haven't done the 2nd and 3rd books in the series?
Also, are any of the actors in the trailer from the I Am Number Four movie? Can someone list the names of people in the video and who they correspond with?
A:
I found the Facebook page of the company that produced it. It lists some of the actors:
Cyrus Salvia as Number Nine
Annie Baltic as Ella
Sarah Martinez as Number Six?
Bryant Lee
Brett Temple
Brett Austin Temple
If someone could figure out which of the other names corresponds to which number and edit it in, that would be great. There's also Malcolm , which I don't think is on this list.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I get the correct size of a char*?
New to C++, so apologies if this is an obvious question.
I have a char[], containing an AES key (the key here is for demo only):
char oldkey[] = {0x7c, 0x4f, 0xd7, 0xc2, 0xfb, 0x09, 0x1f, 0xef, 0x6d, 0x34, 0x1a, 0x78, 0x6d, 0xd7, 0xb5, 0x17};
I'm moving from storing the key in this format to storing a base64 encoded string, which is decoded using CryptStringToBinary:
int DecodeBase64( const BYTE * src, unsigned int srcLen, char * dst, unsigned int dstLen ) {
DWORD outLen;
BOOL fRet;
outLen = dstLen;
fRet = CryptStringToBinary( (LPCSTR) src, srcLen, CRYPT_STRING_BASE64, (BYTE * )dst, &outLen, NULL, NULL);
if (!fRet) outLen = 0; // failed
return( outLen );
}
void * key_mem;
unsigned char key[] = "fE/XwvsJH+9tNBp4bde1Fw=="; //base64 of old_key
unsigned int key_len = sizeof(key);
key_mem = VirtualAlloc(0, key_len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
DecodeBase64((const BYTE *) key, key_len, (char *) key_mem, key_len);
char* decoded_key = (char*)key_mem;
Calling sizeof on decoded_key and oldkey gives two different results:
printf("\n%i\n", sizeof(decoded_key)); //8
printf("\n%i\n", sizeof(oldkey)); //16
The data in decoded_key is correct. It works with my AES algorithm, if I pass the correct key length. How can I get the correct length of decoded_key (16)?
A:
DecodeBase64 returns a value.
int DecodeBase64(.... // <------------------------------- this int right here
{
return( outLen ); // <------------------------------- this variable right here
}
That's the length you need. Use it.
int decodedLen = DecodeBase64((const BYTE *) key, key_len, (char *) key_mem, key_len);
////////////// this one
You cannot use sizeof because the decoded key doesn't have to occupy the entire buffer. You cannot use strlen because the decoded key is not a string. That's why DecodeBase64 returns a value. You cannot ignore it because there is no other way to get the size.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Find $\lim_{n\to \infty}\int _0^{\frac{\pi}{2}} \sqrt{1+\sin^nx}$
Define
$$I_n=\int _0^{\frac{\pi}{2}} \sqrt{1+\sin^nx}\, dx$$
I have to show this sequence is convergent and find its limit. I proved it is decreasing: $\sin^{n+1} x \le \sin^n x \implies I_{n+1} \le I_n$. Also, it is bounded because:
$$0 \le \sin^n x \le 1 \implies \frac\pi{2} \le \int _0^{\frac{\pi}{2}} \sqrt{1+\sin^n x}\, dx\le \frac{\pi\sqrt{2}}{2}$$
so it is convergent. I'm stuck at finding the limit. I think it should $\frac{\pi}{2}$ but I'm not sure.
A:
Let's define the following sequence:
$$J_n=\int _0^{\frac{\pi}{2}} \sin^nx\, dx$$
Since $\sin^n x \geq 0$, for $x \in [0,\frac{\pi}{2}]$, we have:
$$|\sqrt{1+\sin^n x}-1|=\frac{\sin^n x}{\sqrt{1+\sin^n x}+1} \leq \frac{\sin^n x}{2}$$
Therefore
$$1-\frac{1}{2}\sin^n x\leq \sqrt{1+\sin^n x}\leq 1+\frac{1}{2}\sin^n x$$
and integrating:
$$\frac{\pi}{2}-\frac{1}{2}J_n \leq I_n \leq \frac{\pi}{2}+\frac{1}{2}J_n\ \ \ \ \ \ \ \ (*)$$
Now, integrating by parts, we can deduce that:
$$J_n=\frac{n-1}{n}J_{n-2}\Rightarrow nJ_nJ_{n-1}=(n-1)J_{n-1}J_{n-2}$$
Therefore
$$nJ_nJ_{n-1}=(n-1)J_{n-1}J_{n-2}=(n-2)J_{n-2}J_{n-3}=...=J_1J_0=\frac{\pi}{2}$$
Clearly $J_n$ is convergent, and its limit must be $0$. Therefore, squeezing in $(*)$:
$$\lim_{n\to \infty}I_n = \frac{\pi}{2}$$
A:
Hint: Use Dominated convergence theorem.
A:
DCT is the way to go if you have that at your disposal. Here's an elementary solution: Let $0<b<\pi/2.$ Then the $n$th integral, let's call it $I_n,$ satisfies
$$\pi/2 = \int_0^{\pi/2}1\,dx < I_n < b\cdot \sqrt {1+\sin^n b} + \sqrt 2(\pi/2-b).$$
Taking limits, we get
$$\pi/2 \le \lim_{n\to \infty} I_n \le b\cdot 1 + \sqrt 2(\pi/2-b).$$
Now let $b\to \pi/2^-$ to see $\pi/2 \le \lim I_n \le \pi/2.$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Checking in D if a string is in array?
How do I check for a string occurance in an array? I mean sure I can loop, but is there a standard function?
at first I did:
if(str in ["first", "second", "third"])
but it complained that in only works with associative arrays.
I tried to quickly lookup the phobos docs but didn't find any module related to arrays.
So is there anything, or do I just have to loop through it manually?
Edit:
I'm on D1, phobos.
A:
If your strings are constant (like in the example), you can use an associative array literal, but the syntax isn't pretty:
if (str in ["first"[]:0, "second":0, "third":0])
I don't think there's a library call you can use in D1's Phobos, but D2's std.algorithm has something you could use:
if (count(["first", "second", "third"][], str))
In Tango, you can use the generic contains function from tango.text.Util:
if (contains(["first", "second", "third"][], str))
Note that the [] at the end of array literals is required because we need to pass a memory slice of the static array, and not the actual static array by-value.
A:
With D1 Phobos, you'll have to do it yourself. But it's not too hard.
bool contains(T)(T[] a, T v)
{
foreach( e ; a )
if( e == v )
return true;
return false;
}
Plus, you should be able to use it like this:
auto words = ["first"[], "second", "third"];
if( words.contains(str) ) ...
Hope that helps.
Incidentally, you can modify the above to work as an "indexOf" function:
size_t indexOf(T)(T[] a, T v)
{
foreach( i, e ; a )
if( e == v )
return i;
return a.length;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
When was the Community Wiki Question capability restricted to moderators only?
Before, users could mark their own questions as Community Wiki. When was the change that restricted it to moderators?
A:
On or about October 14, 2010.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Split long commands in multiple lines through Windows batch file
How can I split long commands over multiple lines in a batch file?
A:
You can break up long lines with the caret ^ as long as you remember that the caret and the newline following it are completely removed. So, if there should be a space where you're breaking the line, include a space. (More on that below.)
Example:
copy file1.txt file2.txt
would be written as:
copy file1.txt^
file2.txt
A:
The rule for the caret is:
A caret at the line end, appends the next line, the first character of the appended line will be escaped.
You can use the caret multiple times, but the complete line must not exceed the maximum line length of ~8192 characters (Windows XP, Windows Vista, and Windows 7).
echo Test1
echo one ^
two ^
three ^
four^
*
--- Output ---
Test1
one two three four*
echo Test2
echo one & echo two
--- Output ---
Test2
one
two
echo Test3
echo one & ^
echo two
--- Output ---
Test3
one
two
echo Test4
echo one ^
& echo two
--- Output ---
Test4
one & echo two
To suppress the escaping of the next character you can use a redirection.
The redirection has to be just before the caret.
But there exist one curiosity with redirection before the caret.
If you place a token at the caret the token is removed.
echo Test5
echo one <nul ^
& echo two
--- Output ---
Test5
one
two
echo Test6
echo one <nul ThisTokenIsLost^
& echo two
--- Output ---
Test6
one
two
And it is also possible to embed line feeds into the string:
setlocal EnableDelayedExpansion
set text=This creates ^
a line feed
echo Test7: %text%
echo Test8: !text!
--- Output ---
Test7: This creates
Test8: This creates
a line feed
The empty line is important for the success. This works only with delayed expansion, else the rest of the line is ignored after the line feed.
It works, because the caret at the line end ignores the next line feed and escapes the next character, even if the next character is also a line feed (carriage returns are always ignored in this phase).
A:
(This is basically a rewrite of Wayne's answer but with the confusion around the caret cleared up. So I've posted it as a CW. I'm not shy about editing answers, but completely rewriting them seems inappropriate.)
You can break up long lines with the caret (^), just remember that the caret and the newline that follows it are removed entirely from the command, so if you put it where a space would be required (such as between parameters), be sure to include the space as well (either before the ^, or at the beginning of the next line — that latter choice may help make it clearer it's a continuation).
Examples: (all tested on Windows XP and Windows 7)
xcopy file1.txt file2.txt
can be written as:
xcopy^
file1.txt^
file2.txt
or
xcopy ^
file1.txt ^
file2.txt
or even
xc^
opy ^
file1.txt ^
file2.txt
(That last works because there are no spaces betwen the xc and the ^, and no spaces at the beginning of the next line. So when you remove the ^ and the newline, you get...xcopy.)
For readability and sanity, it's probably best breaking only between parameters (be sure to include the space).
Be sure that the ^ is not the last thing in a batch file, as there appears to be a major issue with that.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why didn't I get any bounty after the question was accepted?
I have answered a question, and after the bounty expired, I didn't get any bounty.
And the bounty was started by the question owner,
the question owner accepted an answer during the bounty period, but the bounty award period expired without an explicit award.
So why?
A:
As per the bountied question's timeline, you have answered before the bounty started. Hence, you have not received the bounty.
A:
It is up to the bounty owner to decide what to do about the bounty.
Sometimes they simply forget about it. You can't do anything about that. And as pointed out in comments: there is an additional grace period. Maybe the bounty owner simply wants to wait for the last minute before awarding the bounty. There is always a chance that another, better answer comes in. But it looks like the OP of that question just missed to award it.
It is sometimes helpful to write a polite comment to "not forget about awarding the bounty", but that is about it.
And yes, that leads to the fact that sometimes the bounty isn't awarded at all, because forgotten. But the system is designed like that on purpose (for answers given before the bounty was established).
And yes, that is a very annoying feeling. Happened to me twice that my accepted answer missed a bounty because "forgotten". Worst case, take it as one of those events in life that allow you to grow your personality.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Format of redirect is wrong in Rails
I want to send a :user_id to my index controller when it redirects:
format.html { redirect_to @employee_personal, notice: 'Personal was successfully updated.'}
In my index controller I have to send:
@user_id = @employee_personal.user_id
variable.
How can I send this? In the redirect I tried:
format.html { redirect_to @employee_personal(:user_id => @user_id), notice: 'Personal was successfully updated.' }
It is wrong.
format.html { redirect_to :action => :index, :user_id => @user_id }
is right.
How can I make that error right in that format?
A:
Try:
format.html { redirect_to @employee_personal, user_id: @user_id, notice: 'Personal was successfully updated.'}
Also, you can specify the path with params, something like this:
format.html { redirect_to employee_personal_path(@employee_personal, user_id: @user_id), notice: 'Personal was successfully updated.'}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Qt Creator - SFML Link to a console project
I am currently working on a project in console mode in which I wish to implement a sound. Our choice then turned to SFML, we get to install and use on OS X. However, we need to make it compatible with Qt project for rendering, I generate a.Profile and integrate our code and the library.
In OS X, no problem, installation and use possible. However, for this project, we need to integrate it into the code to make only archive. But every attempt to link our project with the aforementioned library, we run into errors.
Could you tell us exactly what files are to be included in the project? Working on protecting machines, we cannot install packages. Here is the screen of the integration window, the button exhilarating. We cannot select the Library.
A:
You just have to use the external library instead of the internal.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Disprove the statement $f(A \cap B) = f(A) \cap f(B)$
If someone could walk me through this I would greatly appreciate it.
Disprove the following statement:
If $f : X \rightarrow Y$ is a function and $A$, $B$
are subsets of $X$ then $f(A \cap B) = f(A) \cap f(B)$.
A:
$f(x) = x^2$, $A = [-1,0],B = [0,1]$.
$f(A\cap B) = f(\{0\}) = \{0\}$
But $f(A)\cap f(B) = [0,1]$
A:
The other answers find counterexample for $f(A\cap B) =f(A)\cap f(B)$, but it is easy to show that $f(A\cap B)\subseteq f(A)\cap f(B)$:
If $A\subseteq B$, then $f(A)\subseteq f(B)$.
Now, $A\cap B\subseteq A, B$, and thus $f(A\cap B)\subseteq f(A), f(B)\implies f(A\cap B)\subseteq f(A)\cap f(B)$.
Actually, equality holds if and only if $f$ is injective.
Let $f$ be injective and take $y\in f(A)\cap f(B)$. Then, by the definition of image there are $x_A\in A$ and $x_B\in B$ such that $y = f(x_A) = f(x_B)$. By injectivity $x_A = x_B\in A\cap B$. But then $y\in f(A\cap B)$. Hence, $f(A)\cap f(B) \subseteq f(A\cap B)$ and then by the above $f(A)\cap f(B) = f(A\cap B)$.
If $f$ is not injective, choose $x\neq y$ such that $f(x) = f(y)$. Then $f(\{x\}\cap\{y\}) \neq f(\{x\})\cap f(\{y\})$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can i access older RSS from Yahoo! News?
Yahoo! News
take this as a example,the current xml only show the newest 42 news
but i want to access to older feed, how can i do that?
A:
There are no parameters to do that. Some feeds like the weather do take a couple of parameters, for example what location are you interested in, but you are stuck with what Yahoo returns to you. Let Yahoo know what you need. Maybe in the future they will evolve their developer access.
If you want to read more about the evolution of Yahoo's offerings, you can start here. The news search API, which has been deprecated for 1.5 years did allow for a start and results parameter to specify how much information you got back.
I also urge you to examine YQL. You can play around with different "queries" here to see how you can customize your RSS retrieval experience. Note that the YQL query will yield the same number of results. If I try to change the number of results with my YQL query like so, I still only get back 40 hits so the news rss is limiting what I can get back.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Social network broadcast message algorithm (part 2)
This is new code and continue discussion from thread (Social network broadcast message algorithm), and this thread focus on build new graph from strong connected graph part. Let me post the problem again, this time I want to focus more on the 2nd step of the algorithm (i.e. code after replace nodes in a strongly connected component with a new node part). Appreciate for any comments in advance.
Major ideas of implementation,
Build a totally new graph (after finding strongly connected components), and build mapping between new old and old node
For a node in a strongly connected component, build out connection only between this node and nodes not in this strongly connected component;
For a node in a strongly connected component, build in connection only between this node and node not in this strongly connected components;
Deal with in/out connections for nodes not in any strongly connected components.
Wondering if more elegant ways to implement, my overhead of implementation is (1) a old/new node mapping and (2) a complete new graph
Problem,
Let's suppose that I'd like to spread a promotion message across all people in Twitter. Assuming the ideal case, if a person tweets a message, then every follower will re-tweet the message.
You need to find the minimum number of people to reach out (for example, who doesn't follow anyone etc) so that your promotion message is spread out across entire network in Twitter.
Also, we need to consider loops like, if A follows B, B follows C, C follows D, D follows A (A -> B -> C -> D -> A) then reaching only one of them is sufficient to spread your message.
Input: A 2x2 matrix like below. In this case, a follows b, b follows c, c follows a.
a b c
a 1 1 0
b 0 1 1
c 1 0 1
Output: List of people to be reached to spread out message across everyone in the network.
Let me quote the correct algorithm by Gareth.
Correct algorithm
The correct algorithm for finding the minimum number of sinks so that every node has a path to at least one sink is as follows:
Find the strongly connected components in the graph, for example
using Tarjan's algorithm. (A strongly connected component is a group
of nodes such that there is a path from every node in the component
to every other node in the component. For example, a cycle.)
In the graph, replace each strongly connected component with a new single
node (updating the edges so that if there was an edge between a node
n and any node in the component, there is a corresponding edge
between n and the new node).
If the graph has no nodes, stop.
Find a node of out-degree zero and add it to the set of sinks. (If the node
replaced a strongly connected component in step 2, then add any node
from the original component.)
Remove the sink from the graph, along with every node that has a path to the sink.
Go to step 3.
My code,
from __future__ import print_function
from collections import defaultdict
class Graph:
def __init__(self):
self.outConnections = defaultdict(set)
self.inConnections = defaultdict(set)
self.visited = set()
self.DFSOrder = []
def addEdge(self, fromx, toy):
self.outConnections[fromx].add(toy)
self.inConnections[toy].add(fromx)
def DFS(self, root, path):
if root in self.visited:
return
self.visited.add(root)
for node in self.outConnections[root]:
self.DFS(node, path)
self.DFSOrder.insert(0, root)
path.add(root)
def getNodes(self):
return self.outConnections.keys()
def getConnections(self):
for (k, v) in self.outConnections.items():
print (k, '=>', v)
for (k, v) in self.inConnections.items():
print (v, '=>', k)
def DFSReverse(self, root, path):
if root in self.visited:
return
self.visited.add(root)
for node in self.inConnections[root]:
self.DFS(node, path)
path.add(root)
if __name__ == "__main__":
g = Graph()
g.addEdge('A', 'B')
g.addEdge('A', 'C')
g.addEdge('B', 'A')
g.addEdge('C', 'D')
g.addEdge('D', 'C')
for node in g.getNodes():
if node not in g.visited:
path=set()
g.DFS(node, path)
g.visited=set()
SCs = []
for node in g.DFSOrder:
if node not in g.visited:
path=set()
g.DFSReverse(node, path)
SCs.append(path)
# replace nodes in a strongly connected component with
# a new node
baseName='SC-'
i = 0
newGraph = Graph()
oldNewGraphMapping = defaultdict(str) # key old node, value new node
for sc in SCs:
for node in sc:
oldNewGraphMapping[node]=baseName+str(i)
newGraph.inConnections[baseName+str(i)]
newGraph.outConnections[baseName+str(i)]
i+=1
# handle node not in any strongly connected graph
nonSCNode = set()
for node in g.inConnections.keys():
if node not in oldNewGraphMapping:
oldNewGraphMapping[node] = node
newGraph.inConnections[node]
nonSCNode.add(node)
for node in g.outConnections.keys():
if node not in oldNewGraphMapping:
oldNewGraphMapping[node] = node
newGraph.outConnections[node]
nonSCNode.add(node)
for sc in SCs:
for node in sc:
for outLink in g.outConnections[node]:
if outLink not in sc: # point to outside
newGraph.addEdge(oldNewGraphMapping[node], oldNewGraphMapping[outLink])
for inLink in g.inConnections[node]: # pointed from outside
if inLink not in sc:
newGraph.addEdge(oldNewGraphMapping[inLink], oldNewGraphMapping[node])
# deal with non-sc nodes
for node in nonSCNode:
for toNode in g.outConnections[node]:
newGraph.addEdge(oldNewGraphMapping[node], oldNewGraphMapping[toNode])
for fromNode in g.outConnections[node]:
newGraph.addEdge(oldNewGraphMapping[fromNode], oldNewGraphMapping[toNode])
#print (newGraph.getNodes())
#newGraph.getConnections()
A:
The code in my answer to your previous question had docstrings, but these have been removed in the version of the code posted here. I put the docstrings there for two reasons:
Without documentation, it's very hard to use code. You have to guess what it might do from the names, or read the source code and reverse-engineer it to figure out what it does. This applies not only to second-party users, but also to yourself when you come back to use code in six months or a year and have forgotten what you were thinking when you wrote it.
Without documentation, it's impossible to check that code is correct. If you spot something strange in the implementation, is it a bug, or is it a feature? You can't tell unless you know what the code is supposed to do.
The __init__ method lacks the convenient initialization from my answer to your previous question. I wrote there:
The constructor makes it very easy to create example graphs:
Graph('AB BA CD DC AC'.split())
(Compare this to the ten lines of code needed to create the graph in the post.)
In my reviews to three of your previous questions (1, 2, 3) I made this point:
The code is not fully organized into functions: most of it runs at the top level of the module. This makes it hard to understand and hard to test.
This problem is still present in the code in this post.
There is a bug in the addEdge method: it doesn't add toy to outConnections, meaning that getNodes may return an incomplete set of nodes. Note that this bug was not present in the add_edge method in my answer to your previous question.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
No Roo installation configured in workspace preferences
Downloaded latest eclipse (indigo 3.7) and the latest sts (SpringSourceTool 2.9.1.RELEASE) plugin.
I'm trying my luck with my first Roo project but when tryin to create the project getting:
No Roo installation configured in workspace preferences.
According to the manuals sts is all I need.
Have I missed something here?
Thanks in advance
A:
Try preferences, type "Roo" in the search field in order to find the Roo configuration option, and if it exists, you can choose the Roo installation path(s) from there.
Previously, you have to download and install Roo.
Alternatively, you can install the SpringSource Tool Suite directly, that comes with Eclipse, a couple of useful plugins, and with three programs: maven, Roo and VMWare TC server (a customized tomcat server)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Are tires symmetrical & are their material properties uniform?
I've heard that the part of a tire which is towards the inner side of a vehicle has material which is more wear resistant than the part of a tire on the outer side of the vehicle.
In short, I have difficulty with identifying the inner side of a tire. Is there a difference in the material properties of tires from the inner side to the outside?
A:
There are Tread pattern differences, which allows part of the tire to make good contact with the ground for performance (grip). Part of the tire with wide channels to evacuate water (typically called ribs), and sipes so the tire wears properly, etc.
An Asymmetrical tire is often referred to in the tire world as an inside outside tire, where a directional tires typically have a V pattern with the v point toward the hood of the car, and the 2 ends facing the rear. To answer the question of rubber on the surface or thread of the tire being different, this is incorrect it remains the same across the thread, while the rubber used for the sidewall in some cases is different. This describes the different terms typically used. while if you search for Goodyear you can find a tire with Kevlar in it which is stronger side wall. The inner side of the tire leads me to believe you might have a worn suspension part in the front causing premature tire wear, or that the alignment of the vehicle is off, I would post more links however I do not have the rep it appears.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Putting iPhone to sleep hides tableview cells
Very strange problem here.
Essentially what is happening is that our Tableview cells are becoming hidden in some cases when we simply put the app to sleep and then re-unlock. Our normal tableview looks like this:
And then when we re-open the app it will look like this:
All the rows and sections are set correctly, yet the cells are hidden.:
When this happens, our cellForRowAtIndexPath no longer gets called. This surely has to be the problem. Has anyone ever seen behavior like this? Here is how we set up the tableview. (sorry it is long)
//
// SPHomeViewController.m
// Spek
@interface SPHomeViewController () <UITableViewDataSource, UITableViewDelegate, MKMapViewDelegate, SPCreationViewDelegate, UIAlertViewDelegate, CLLocationManagerDelegate>
@property (nonatomic, strong) UITableView* tableView;
@property (nonatomic, strong) NSMutableArray* tableDatasource;
@property (nonatomic, strong) NSMutableArray* datasource;
@property (nonatomic, strong) NSMutableArray* friendsDatasource;
@property (nonatomic, strong) UISegmentedControl* userFilterSegment;
@property (nonatomic) BOOL isLoadingData;
@end
@implementation SPHomeViewController
@synthesize datasource = _datasource;
@synthesize friendsDatasource = _friendsDatasource;
@synthesize tableDatasource = _tableDatasource;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
//[[SPLocationManager locationManager] startUpdatingLocationForSig];
[self setNeedsStatusBarAppearanceUpdate];
self.view.backgroundColor = [UIColor colorWithRed:230.0f/255.0f green:230.0f/255.0f blue:230.0f/255.0f alpha:1.0];
self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - kTopBarHeight)];
self.tableView.separatorColor = [UIColor clearColor];
self.tableView.backgroundColor = [UIColor clearColor];
self.tableView.delegate = self;
self.tableView.dataSource = self;
[self.view addSubview:self.tableView];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
if (self.creationView.center.y > self.view.frame.size.height) {
self.creationView = nil;
}
NSLog(@"Mem warning");
}
//****************************************
//****************************************
#pragma mark - UITableViewDelegate/DataSource
//****************************************
//****************************************
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"INDEX PATH ROW: %d AND SECTION: %d", indexPath.row, indexPath.section);
if (indexPath.section == 0) {
UITableViewCell* cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"SPMapCellSpace"];
cell.backgroundColor = [UIColor clearColor];
cell.backgroundView = [[UIView alloc] init];
cell.selectedBackgroundView = [[UIView alloc] init];
return cell;
} else if (indexPath.section == self.tableDatasource.count + 1) {
UITableViewCell* cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"SPBottomCellSpace"];
cell.backgroundColor = [UIColor clearColor];
cell.backgroundView = [[UIView alloc] init];
cell.selectedBackgroundView = [[UIView alloc] init];
return cell;
}
SPMark* mark = self.tableDatasource[indexPath.section - 1];
NSString* reuseId = [SPHomeViewController cellIdentifierFromData:mark];
SPTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:reuseId];
if (cell == nil) {
cell = [SPTableViewCell cellFromMark:mark reuseID:reuseId];
[cell updateView:YES];
}
[cell addDataToCell:mark];
if (indexPath.section >= self.tableDatasource.count - 2 && !self.isLoadingData && self.pageNumber != -1) {
self.fetchNextPage = YES; // When the scrollview stops it will load more data if available.
}
return cell;
}
- (unsigned int)getPageNumber {
return (self.userFilterSegment.selectedSegmentIndex == 0) ? self.pageNumber : self.friendsPageNumber;
}
- (void)setCurrentPageNumber:(unsigned int)page {
if (self.userFilterSegment.selectedSegmentIndex == 0) {
self.pageNumber = page;
} else {
self.friendsPageNumber = page;
}
}
- (void)incrementCurrentPageNumber {
if (self.userFilterSegment.selectedSegmentIndex == 0) {
self.pageNumber++;
} else {
self.friendsPageNumber++;
}
}
// Every cell has a section header so this should be equal to the number of speks returned from the server
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSLog(@"section count is: %d",self.tableDatasource.count + 2 );
return self.tableDatasource.count + 2; // Add two because the mapview needs to go on the top and extra spacing at the bottom.
}
// There is a section for every cell, so there is only one cell per section
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.section == 0) {
return kMapHeight+2;
} else if (indexPath.section == self.tableDatasource.count + 1) {
return kExtraSpaceBelowHomeView;
}
SPMark* mark = self.tableDatasource[indexPath.section - 1];
return [SPTableViewCell cellHeightForMark:mark];
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.section == 0 || indexPath.section == self.tableDatasource.count + 1) {
cell.backgroundColor = [UIColor clearColor];
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.section == 0 || indexPath.section == self.tableDatasource.count + 1)
return;
SPMark* mark = self.datasource[indexPath.section - 1 ];
SPMarkViewController* markVC = [SPMarkViewController withMark:mark];
[markVC displayData];
[self.navigationController pushViewController:markVC animated:YES];
}
-(void)reloadTableview {
[self.tableView setDelegate:self];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
[self.tableView setNeedsDisplay];
});
}
- (void)showNoItems {
if (self.tableDatasource.count == 0 && self.accuracyBad == NO) {
self.opaqueIcon.hidden = NO;
self.noItems.hidden = NO;
self.beTheFirst.hidden = NO;
self.downArrow.hidden = NO;
self.noItemsBackround.hidden = NO;
[self.view bringSubviewToFront:self.noItemsBackround];
[self.view bringSubviewToFront:self.downArrow];
[self.view bringSubviewToFront:self.beTheFirst];
[self.view bringSubviewToFront:self.noItems];
[self.view bringSubviewToFront:self.opaqueIcon];
}
}
- (void)showTableView {
if (self.tableDatasource.count != 0) {
self.noItems.hidden = YES;
self.beTheFirst.hidden = YES;
self.downArrow.hidden = YES;
self.noItemsBackround.hidden = YES;
self.opaqueIcon.hidden = YES;
[self.view sendSubviewToBack:self.noItemsBackround];
[self.view sendSubviewToBack:self.downArrow];
[self.view sendSubviewToBack:self.beTheFirst];
[self.view sendSubviewToBack:self.noItems];
[self.view sendSubviewToBack:self.opaqueIcon];
}
}
//****************************************
//****************************************
#pragma mark - Setters/Getters
//****************************************
//****************************************
- (NSMutableArray*)datasource {
if (!_datasource) {
_datasource = [NSMutableArray array];
if (!self.firstLoad) {
[self loadDataForPagination:NO];
}
}
return _datasource;
}
- (NSMutableArray*)friendsDatasource {
if (!_friendsDatasource) {
_friendsDatasource = [NSMutableArray array];
if (!self.firstLoad) {
[self loadDataForPagination:NO];
}
}
return _friendsDatasource;
}
- (NSMutableArray*)tableDatasource {
if (!_tableDatasource) {
_tableDatasource = (self.userFilterSegment.selectedSegmentIndex == 0) ? self.datasource : self.friendsDatasource;
}
return _tableDatasource;
}
- (SPCreationView*)creationView {
if (!_creationView) {
UIView* window = [SPUtils getAppDelegate].window;
CGSize viewSize = window.frame.size;
CGRect startFrame = CGRectMake(0, viewSize.height, [SPUtils screenWidth], [SPUtils screenHeight]);
_creationView = [SPCreationView creationView:startFrame delegate:self];
[window insertSubview:_creationView belowSubview:self.creationButton];
_creationView.frame = startFrame;
}
return _creationView;
}
- (void)setTableDatasource:(NSMutableArray *)tableDatasource {
_tableDatasource = tableDatasource;
[self preFetchImages];
dispatch_async(dispatch_get_main_queue(), ^{
if(_tableDatasource == nil || _tableDatasource.count == 0) {
[self showNoItems];
} else {
[self showTableView];
}
[self reloadTableview];
});
}
- (void)setDatasource:(NSMutableArray *)datasource {
_datasource = datasource;
}
- (void)setFriendsDatasource:(NSMutableArray *)friendsDatasource {
_friendsDatasource = friendsDatasource;
}
@end
If you think it's a AppDelegate problem, we don't do anything with this controller in there, so I don't see how it could be.
A:
I've only seen this occur previously when I was reloading data (incorrectly) from a background thread. I see you're trying to push the reloads onto the main thread already.
It looks like you're flailing a bit trying to be sure updates are occurring on the main thread. You should probably just verify that your actions are occurring on main by checking [NSThread isMainThread] rather than making your code async to the main thread, making lots of async flow changes can lead to unexpected behavior.
That said, since this only happens on wake from sleep maybe you have some background mode on and you aren't updating the UI from the correct thread there?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I increase the maximum query time?
I ran a query which will eventually return roughly 17M rows in chunks of 500,000. Everything seemed to be going just fine, but I ran into the following error:
Traceback (most recent call last):
File "sql_csv.py", line 22, in <module>
for chunk in pd.read_sql_query(hours_query, db.conn, chunksize = 500000):
File "/Users/michael.chirico/anaconda2/lib/python2.7/site-packages/pandas/io/sql.py", line 1424, in _query_iterator
data = cursor.fetchmany(chunksize)
File "/Users/michael.chirico/anaconda2/lib/python2.7/site-packages/jaydebeapi/\__init__.py", line 546, in fetchmany
row = self.fetchone()
File "/Users/michael.chirico/anaconda2/lib/python2.7/site-packages/jaydebeapi/\__init__.py", line 526, in fetchone
if not self._rs.next(): jpype._jexception.SQLExceptionPyRaisable: java.sql.SQLException: Query failed (#20171013_015410_01255_8pff8):
**Query exceeded maximum time limit of 60.00m**
Obviously such a query can be expected to take some time; I'm fine with this (and chunking means I know I won't be breaking any RAM limitations -- in fact the file output I was running shows the query finished 16M of the 17M rows before crashing!).
But I don't see any direct options for read_sql_query. params seems like a decent candidate, but I can't see in the jaydebeapi documentation any hint of what the right parameter to give to execute might be.
How can I overcome this and run my full query?
A:
When executing queries, Presto restricts each query by CPU, memory, execution time and other constraints. You hit execution time limit. Please ensure that your query is sound, otherwise, you can crash the cluster.
To increase query execution time, define a new value in session variables.
SET SESSION query_max_execution_time=60m;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
RxJava BehaviorSubject and Consumer - is there a memory leak here?
first time using RxJava, remembered that I read a lot about memory leaks in RxJava, so afraid I might be creating a memory leak here - am I? And if I am, how do I fix it? Should I create a Consumer member object and do something with it upon onStop or onDestroy? (The lambdra in .subscribe is for a Consumer with an accept method
void onCreate() {
keyboardChangeSubject = BehaviorSubject.create();
keyboardChangeSubject
.debounce(300, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe(isKeyBoardOpen -> {
myButton.setVisibility(isKeyBoardOpen ? View.GONE : View.VISIBLE);
});
}
@Override
protected void onKeyboardChange(boolean isKeyboardOpen) {
keyboardChangeSubject.onNext(isKeyboardOpen);
}
A:
Yes, you should have it disposed when the Activity gets destroyed by adding the returned Disposable to a CompositeDisposable, which comes in handy when you have more than one flow to be tracked:
final CompositeDisposble cd = new CompositeDisposable();
void onCreate() {
keyboardChangeSubject = BehaviorSubject.create();
cd.add(
keyboardChangeSubject
.debounce(300, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe(isKeyBoardOpen -> {
myButton.setVisibility(isKeyBoardOpen ? View.GONE : View.VISIBLE);
})
);
}
@Override
protected void onKeyboardChange(boolean isKeyboardOpen) {
keyboardChangeSubject.onNext(isKeyboardOpen);
}
@Override
public void onDestroy() {
cd.clear();
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Missing actual argument when calling a subroutine with optional arguments
My IDE is Visual Studio 2010 with integrated Intel Fortran compiler. The version of compiler is: Intel Parallel Studio XE 2011.
I am not experienced programer in Fortran so I need a little help about using optional argument in public procedure from derived type. This is my example code:
MODULE DERIVED_TYPE
TYPE , PUBLIC :: SOME_TYPE
INTEGER , PRIVATE :: V_INT
CONTAINS
PROCEDURE , PUBLIC :: CALL_V_INT => CALL_DATA_V_INT
PROCEDURE , PUBLIC :: TAKE_V_INT => TAKE_DATA_V_INT
END TYPE SOME_TYPE
PRIVATE :: CALL_DATA_V_INT
PRIVATE :: TAKE_DATA_V_INT
CONTAINS
! PUBLIC PROCEDURES
SUBROUTINE CALL_DATA_V_INT( THIS , IA , IB , IC )
CLASS( SOME_TYPE ) :: THIS
INTEGER , INTENT( IN ) :: IA , IC
INTEGER , INTENT( IN ) , OPTIONAL :: IB
IF( .NOT. PRESENT( IB ) ) THEN
THIS%V_INT = IA + IC
ELSE
THIS%V_INT = IA + IB + IC
END IF
END SUBROUTINE CALL_DATA_V_INT
FUNCTION TAKE_DATA_V_INT ( THIS ) RESULT( RES )
CLASS( SOME_TYPE ) :: THIS
INTEGER :: RES
RES = THIS%V_INT
END FUNCTION TAKE_DATA_V_INT
END MODULE DERIVED_TYPE
PROGRAM OPTIONAL_ARG
USE , NON_INTRINSIC :: DERIVED_TYPE
IMPLICIT NONE
INTEGER :: I
INTEGER , PARAMETER :: N = 3
CLASS( SOME_TYPE ) , POINTER :: P_SOME_TYPE
TYPE( SOME_TYPE ) , DIMENSION( N ) , TARGET :: ARR_V_INT
DO I = 1 , N
P_SOME_TYPE => ARR_V_INT( I )
CALL P_SOME_TYPE%CALL_V_INT( I , 5 )
WRITE( * , * ) P_SOME_TYPE%TAKE_V_INT()
END DO
END PROGRAM OPTIONAL_ARG
At the end of compiling proces i got this kind of message in build window:
Missing actual argument for argument 'ic'
What is wrong with this example?
I also try to move optional argument to latest position in argument list and in that case there is no error message.
Can I get detail explanation for optional argument position in argument list?
A:
You should normally try to put optional arguments at the end of the argument list. What happens when you do call such as
subroutine sub (a, b, c)
real :: a, c
real, optional :: b
...
call sub(1.,2.)
is that the compiler must assume that the 1. is for a and the 2. is for b. Then the argument for c is missing.
Instead one can use named arguments after the missing optional one
call sub(1, c=2.)
So in your case you could do
CALL P_SOME_TYPE%CALL_V_INT( I , IC = 5 )
if you don't want to have the optional IB at the end of the argument list.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does Invisibly Sneak Attacking a target with Tremorsense leave them Flat Footed?
I need to know how tremor sense works with sneak attack and invisibility.
Normally when a something is invisible they have no problems walking upto someone else and getting a sneak attack. The thing getting attacked (assuming it is vulnerable to the sneak attack damage) remains vulnerable to the sneak attack until it acts much like a surprise round and initiative. So even when the invisibility wears off from the first attack, any following attacks are still sneak attack.
Now what happens when the person being attacked has tremor sense? It knows something walked upto it. Is it still flat footed to the attack?
If it matters, the person with tremor sense is a druid who has taken the cleric cave domain and is 8th level. The person attacking is a 5th level rogue who has taken ki pool, and ninja trick vanishing trick.
A:
Tremorsense reveals the location of invisible attackers; it doesn't offer protection from sneak attack damage
The extraordinary ability tremorsense says that it
can automatically pinpoint the location of anything that is in contact with the ground. Aquatic creatures with tremorsense can also sense the location of creatures moving through water. The ability’s range is specified in the creature’s descriptive text.
Pinpointing a target's location doesn't negate the concealment granted by an effect like the spell invisibility. A creature with tremorsense that pinpoints an invisible creature's location can make attacks against an invisible creature (albeit with a 50% miss chance) without first locating the invisible creature using other methods (like flailing around like an idiot). Being able to make such attack semi-accurately doesn't make the creature with tremorsense immune to sneak attacks. The creature with tremorsense still can't see what the invisible creature is doing.
Example 1
Abe, lacking tremorsense, is unaware of Bob because Bob is invisible through an invisibility spell.
Surprise Round: Bob stabs flat-footed Abe. Bob's invisibility spell ends.
Round 1: Initiative checks are made. Bob acts then Abe acts. Bob takes the full attack action and makes several attacks versus flat-footed Abe. Abe dies.
Example 2
Abe, having gained tremorsense 30 ft., is aware of Bob despite Bob's invisibility spell.
Round 1: Initiative checks are made. Bob acts then Abe acts. Bob takes a move action to get into position then takes a standard action to make a standard attack against flat-footed Abe. Bob's invisibility spell ends. Abe take a 5-ft. step away from Bob and takes a standard action to cast the spell finger of death on Bob. Bob makes a Fortitude saving throw, fails that saving throw, is dealt 200 points of damage, and dies.
Example 3
While affected by an invisibility spell Bob teleports adjacent to Abe. Abe, possessing tremorsense 30 ft., is aware of Bob's presence.
Round 1: Initiative checks are made. Bob acts then Abe acts. Bob takes the full-attack action to make several attacks against flat-footed Abe. After the first attack, Bob's invisibility spell ends. Abe, who has yet to act, remains flat-footed. Bob continues his full attack action, still his dealing sneak attack damage to flat-footed Abe. Abe dies.
Example 4
While affected by an invisibility spell Bob teleports adjacent to Abe. Abe, possessing tremorsense 30 ft., is aware of Bob's presence.
Round 1: Initiative checks are made. Abe acts then Bob acts. Abe can't target Bob with the spell finger of death because, while Abe knows Bob's location, Abe can't actually see Bob. Abe, instead, uses flame strike to affect an area so as to catch Bob in the spell's effect. Bob makes a Reflex saving throw, succeeds on the saving throw, and takes no damage because of his extraordinary ability evasion. Bob takes the full-attack action to make several attacks against Abe. The first attack (which must be at Bob's highest base attack bonus against Abe) deals sneak attack damage: although Abe is no longer flat-footed Bob still benefits from the spell invisibility. After that first attack, however, the invisibility spell ends, and Bob's remaining attacks don't deal sneak attack damage.
To be clear, I've omitted a host of things from these examples to make them concisely address the question, chief among them the Perception checks that Abe gets against Bob to help him survive the attack from the invisible ninja.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to determine which string in an array is most similar to a given string?
Given a string,
string name = "Michael";
I want to be able to evaluate which string in array is most similar:
string[] names = new[] { "John", "Adam", "Paul", "Mike", "John-Michael" };
I want to create a message for the user: "We couldn't find 'Michael', but 'John-Michael' is close. Is that what you meant?" How would I make this determination?
A:
This is usually done using the Edit distance / Levenshtein distance by comparing which word is the closest based on the number of deletions, additions or changes required to transform one word into the other.
There's an article providing you with a generic implementation for C# here.
A:
Here you have the results for your example using the Levenshtein Distance:
EditDistance["Michael",#]&/@{"John","Adam","Paul","Mike","John-Michael"}
{6,6,5,4,5}
Here you have the results using the Smith-Waterman similarity test
SmithWatermanSimilarity["Michael",#]&/@{"John","Adam","Paul","Mike","John-Michael"}
{0.,0.,0.,2.,7.}
HTH!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I find out the minimum version of Java that is safe to use across a large number of Android phones?
I recently found out at work we're limiting our Java target to 1.1, because there are supposedly still Android phones that only support up to that version. I've been trying to Google which versions of Java are installed on the different version of Android (unless they do get updated, then what is the minimum version that's included?), and have had no such luck in my search.
So, I'm trying to find out what is realistically the best minimum target for Java on Android. Know of any good sources detailing the versions of Java used across Android devices?
[Edit]
For clarification, we're using the Java SDK to build a jar, then packaging it into the apk. So I do need to know a specific Java SDK target, not the Android API level.
A:
You can support all major versions of Android (2.1 and above, possibly even lower) with Java 1.6.
Infact, as long as you compile with anything but 1.7 you'll be fine, though compiling with 1.5 and below gives a bunch of errors with @Override annotations. 1.6 is your safest bet. I've used it in all my apps so far, and haven't found a single device that was incompatible because of my Java version.
A:
Update: It's nowadays Java 7 without try-with-resource and without some newer methods & classes. Your IDE will complain if you use something you shouldn't.
The Android tools know Java 7 and are capable of transforming it into Android bytecode that runs on old devices.
One can also use the full set of Java 7 features (i.e. including try-with-resources) for apps targeting Android 4.4 and up.
Downloading and Building Android itself requires
JDK 6 if you wish to build Gingerbread or newer; JDK 5 for Froyo or older.
Building older versions with JDK 6 works in my experience since the class format generated by the Java compiler is still compatible with the class format of JDK 5.
The same applies to Apps. Android's internal Java implementation is not the same as the JDK so it has no comparable version numbers. But for example String#isEmpty() that was added in JDK 6 says Added in API level 9 in Android's documentation which is exactly the version after aforementioned Froyo.
Eclipse / Android Lint will also mark usage of those methods as error if your App has a lower minimum version than 9.
Using JDK 6 to build any app should work perfectly fine. Your code must not use core Java methods that did not exist on older Android versions just like any other method in the Android framework. It is also no problem to use @Override annotations for implemented interfaces since that annotation is not included in the .class file (see RetentionPolicy.SOURCE).
What actually matters in the end is that Android's dex compiler that turns all the .class files into an Android .dex file actually understands the class format and can produce a valid dex file. The dex format is the one has to be understood by whatever old Android phone you have and I'd assume that the dex compiler makes sure that it produces a valid format for any version of Android. (Here is AFAIK the problem with JDK 7 since the class format has changed)
I'd suggest that you use Java 6 as compile target to build any of your apps. That results in the most recent version of .class file that the dex compiler understands. Older versions do work but you might get warnings like the following
[dx] warning: Ignoring InnerClasses attribute for an anonymous inner class
[dx] (com.bubblesoft.org.apache.commons.logging.impl.LogFactoryImpl$1) that doesn't come with an
[dx] associated EnclosingMethod attribute. This class was probably produced by a
[dx] compiler that did not target the modern .class file format. The recommended
[dx] solution is to recompile the class from source, using an up-to-date compiler
[dx] and without specifying any "-target" type options. The consequence of ignoring
[dx] this warning is that reflective operations on this class will incorrectly
[dx] indicate that it is *not* an inner class.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
OpenFileDialog VBA (Powerpoint) Initial Directory
Please help me make my OpenFileDialog showing my PowerPoint project directory.
i tried .InitialDirectory = "C:\\" ,but it doesn't work. Can i adapt this to vba? Thanks.
A:
This is nearly copied from the Powerpoint VBA help. It uses FileDialog instead of OpenFileDialog(which I had difficulty finding in relation to PowerPoint). It sets the InitialFileName to C:\ so that it will prompt in that location. Just place this in a module, it should be easy to modify to your specific needs:
Sub fileDialogExample()
'Declare a variable as a FileDialog object.
Dim fd As FileDialog
'Declare a variable for the directory path.
Dim directory As String
'Set the directory path
directory = "C:\"
'Create a FileDialog object as a File Picker dialog box.
Set fd = Application.FileDialog(msoFileDialogFilePicker)
'Declare a variable to contain the path
'of each selected item. Even though the path is aString,
'the variable must be a Variant because For Each...Next
'routines only work with Variants and Objects.
Dim vrtSelectedItem As Variant
'Use a With...End With block to reference the FileDialog object.
With fd
'Change the initial directory\filename
.InitialFileName = directory
'Use the Show method to display the File Picker dialog box and return the user's action.
'The user pressed the button.
If .Show = -1 Then
'Step through each string in the FileDialogSelectedItems collection.
For Each vrtSelectedItem In .SelectedItems
'vrtSelectedItem is aString that contains the path of each selected item.
'You can use any file I/O functions that you want to work with this path.
'This example displays the path in a message box.
MsgBox "The path is: " & vrtSelectedItem
Next vrtSelectedItem
'The user pressed Cancel.
Else
End If
End With
'Set the object variable to Nothing.
Set fd = Nothing
End Sub
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Absolute-positioned div within a div that takes all remaining space
I'm trying to make a layout that seems simple. Despite looking at lots of examples, I can't crack it.
SideBar| .......MapContainer......
SideBar| ..........Map............
SideBar| .......MapContainer......
Both SideBar and MapContainer should be 100% height.
The tricky bit: Map must have a defined height and width, because the mapbox-gl-js library uses its dimensions to populate it. (Rather than adding content which then sizes it).
MapContainer exists because there will be other absolutely positioned overlay elements within it.
I'm trying to avoid having the sidebar width coded into the definition of MapContainer so I can hide/show the sidebar in JS, and have the MapContainer automatically fill the space.
This gets really, really close:
* {
box-sizing: border-box;
}
.sidebar, .mapcontainer, .container {
height: 200px;
}
.container {
width:100%;
border:1px solid;
display: flex
}
.sidebar {
width:200px;
background:lightblue;
}
.mapcontainer {
width:auto;
background:lightgreen;
position:relative;
flex-grow: 1;
}
.map {
width: 100%;
height: 100%;
position:absolute;
border: 20px dashed grey;
}
<div class="container">
<div class="sidebar"></div>
<div class="mapcontainer">
<div class="map">
</div>
</div>
</div>
But as soon as I change the "height: 200px" to "height: 100%", it collapses to nothing. What do I need to do?
A:
Use viewport units vh instead in the .sidebar, .mapcontainer, .container rule
* {
box-sizing: border-box;
}
html, body {
margin: 0;
}
.sidebar, .mapcontainer, .container {
height: 100vh;
}
.container {
border: 1px solid;
display: flex
}
.sidebar {
width: 200px;
background:lightblue;
}
.mapcontainer {
background:lightgreen;
position:relative;
flex-grow: 1;
}
.map {
width: 100%;
height: 100%;
position:absolute;
border: 20px dashed grey;
}
<div class="container">
<div class="sidebar"></div>
<div class="mapcontainer">
<div class="map">
</div>
</div>
</div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
writing List elements to excel
I'm just using a simple code to write a list of string to excel as following
Excel.Application excelApp = new Excel.Application();
string myPath = Environment.CurrentDirectory + path + "\\reselts.xlsx";
excelApp.Workbooks.Open(myPath);
List <string> allterms = new List<string>(alltext.Split(' '));
allterms= allterms.Distinct().ToList();
allterms.RemoveAll(String.IsNullOrEmpty);
for (int i = 1; i < allterms.Count + 1; i++ )
{
excelApp.Cells[i, 1] = allterms[i];
}
excelApp.Visible = true;
But I got an error "index was out of range" ! what is wrong with my procedure ? can any help please ?
A:
allterms.Count is the total number of items in the List. Your loop is trying to access Count + 1, which doesn't exist.
For example, say there are 10 items in allterms. The total count is equal to 10 and the index ranges from 0 - 9, which is 10 items. What you're doing in your for loop is accessing items at the index range 1 - 10, which is skipping the item at index 0 and attempting to access the item at index 10, which doesn't exist.
Try this:
for (int i = 0; i < allterms.Count; i++ )
{
excelApp.Cells[i + 1, 1] = allterms[i];
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to import the type-definition in typescript?
I tried use the type-definition for hammerjs. As:
import Hammer from 'hammerjs';
But i get this error:
Error TS2307: Cannot find module 'hammerjs'
I have two question. First, is necessary get all files of tile definition in github, our i can get the simples definition for hammerjs?
My package.json contains:
"dependencies": {
"git+https://[email protected]/DefinitelyTyped/DefinitelyTyped.git"
}
The second question, whats my error about import module?
A:
I resolve the problem after read: http://x-team.com/2016/06/include-javascript-libraries-in-an-ionic-2-typescript-project/
I installed hammerjs with the command:
typings install github:DefinitelyTyped/DefinitelyTyped/hammerjs/hammerjs.d.ts#de8e80dfe5360fef44d00c41257d5ef37add000a --global --save
Then still appeared the error:
Error TS2307: Cannot find module 'hammerjs'
I am development the app with ionic2, i found that the compiler of typescript look the file main.d.ts and not index.d.ts. After rename the file index.d.ts to main.d.ts and works fine! The file main.d.ts found in root-your-app/typings
For import in the project i use: import * as Hammer from 'hammerjs';
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Cardview - fix view - attach to bottom
my problem now:
I need to "attach" these two buttons to bottom - I do not want them to be available to be scrolled (only on bottom - always visible). But my Edittext needs to be scrollable, because there is long text. In android studio it looks good, but in APP not.
XML
<android.support.v7.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:cardBackgroundColor="#212121"
app:cardCornerRadius="8dp"
app:cardElevation="5dp"
app:cardMaxElevation="0dp"
app:cardPreventCornerOverlap="false"
app:cardUseCompatPadding="true">
<EditText
android:id="@+id/storyTextView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/choiceButton1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="@null"
android:cursorVisible="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:lineSpacingMultiplier="1.2"
android:paddingBottom="15dp"
android:paddingLeft="18dp"
android:paddingRight="18dp"
android:paddingTop="15dp"
android:text="You continue your course to Earth. Two days later, you receive a transmission from HQ saying that they have detected some sort of anomaly on the surface of Mars near an abandoned rover. They ask you to investigate, but ultimately the decision is yours because your mission has already run much longer than planned and supplies are low."
android:textColor="#9E9E9E"
android:textSize="16sp"
/>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardBackgroundColor="#212121"
app:cardCornerRadius="8dp"
app:cardElevation="5dp"
app:cardMaxElevation="0dp"
app:cardPreventCornerOverlap="false"
app:cardUseCompatPadding="true">
<Button
android:id="@+id/choiceButton1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:background="@null"
android:text="CONTINUE HOME TO EARTH"
android:textColor="#b71c1c"/>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardBackgroundColor="#212121"
app:cardCornerRadius="8dp"
app:cardElevation="5dp"
app:cardMaxElevation="0dp"
app:cardPreventCornerOverlap="false"
app:cardUseCompatPadding="true">
<Button
android:id="@+id/choiceButton2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:background="@null"
android:text="STOP AND INVESTIGATE"
android:textColor="#b71c1c"/>
</android.support.v7.widget.CardView>
Everything is in:
<LinearLayout
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:id="@+id/activity_story"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:orientation="vertical"
tools:context="com.project.StoryActivity">
</LinearLayout>
IN STUDIO - CLICK
IN APP - CLICK - scrollable, but it "doesnt fit"
I hope you understand my problem, thank you guys :)
A:
use RelativeLayout instead of LinearLayout.
to the bottom buttons,
android:layout_alignParentBottom="true"
second button
android:layout_above="@+id/bottom_button"
to make the EditText scrollable,
android:inputType="textMultiLine"
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Get the vocabulary ID by term or node
I am going to check whether a term belongs to a designated vocabulary.
Which function is used to get vocabulary by term or node?
A:
In Drupal 6, if you know the taxonomy term ID, you can get the vocabulary ID by using the following code:
$term = taxonomy_get_term($tid);
$vid = $term->vid;
If you have a node ID, then you can use the following code to get the vocabulary ID of all the taxonomy terms associated with the node using the following code:
$node = node_load($nid);
$vids = array();
if (!empty($node->taxonomy)) {
foreach ($node->taxonomy as $tid => $term) {
$vids[] = $term->vid;
}
}
In Drupal 7, the code would be the following:
$term = taxonomy_term_load($tid);
$vid = $term->vid;
In Drupal 7, the node property $node->taxonomy doesn't exist anymore. Instead, there is $node->field_<vocabulary_name>, which is an array with two different structures.
tags
other taxonomy terms
Using field_get_items(), you would get the taxonomy terms in the language they would be displayed, or in the language whose code is passed as argument to the function.
$items = field_get_items('node', $node, $field_name);
$node contains the node object, and $field_name the name of the taxonomy term field.
$items contains a simplified array, compared to the array contained in $node->field_<vocabulary_name>.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there an easy way to list out all sklearn implementations that take sparse training input?
As opposed to just trying them with sparse input and getting an error.
Something like the listing of classifiers shown here:
AdaBoostClassifier with different base learners
A:
ok, answering my own question for posterity, adapting original post with try as suggested by andreas. Def should have thought of that.
from scipy.sparse import csc_matrix
from sklearn.utils.testing import all_estimators
import numpy as np
import random
y = np.array([random.randrange(0,2) for i in xrange(1000)])
X = csc_matrix(np.array([[random.randrange(0,2) for i in xrange(1000)],
[random.randrange(0,2) for i in xrange(1000)],
[random.randrange(0,2) for i in xrange(1000)]])).T
for name, Clf in all_estimators(type_filter='classifier'):
try:
clf = Clf()
clf.fit(X,y)
print name
except:
pass
which gave this list:
BernoulliNB
DummyClassifier
KNeighborsClassifier
LabelPropagation
LabelSpreading
LinearSVC
LogisticRegression
MultinomialNB
NearestCentroid
NuSVC
PassiveAggressiveClassifier
Perceptron
RadiusNeighborsClassifier
RidgeClassifier
RidgeClassifierCV
SGDClassifier
SVC
I know this is quick and dirty and misses any that fail for errors other than TypeError: A sparse matrix was passed, but dense data is required. Use X.toarray() to convert to a dense numpy array., and just so everyone knows how conscientious I am, the only one that fails for some other reason is EllipticEnvelope. I checked. :) Also, the non-tree based ensemble methods like BaggingClassifier and AdaBoostClassifier can take sparse input if you change the base_estimator from the default to one that can take sparse input and has all the necessary methods/attributes and you use a sparse representation that can be indexed (csr_matrix or csc_matrix).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
NodeJS Humanized Multidimensional Array (Key Strings) like PHP
With Node JS, is it possible to set multi dimensional arrays separately, using key strings like in PHP ?
myArray[5]['age'] = 38;
myArray[5]['name'] = 'Jack';
myArray[5]['location'] = 'Australia';
I think this is confusing in Node JS:
var myArray = {};
myArray['usedId'] = new Array('Jack', 38, 'Australia');
because I had to do:
console.log (myArray[5]["0"]);
and I'd rather prefer to have a better control using:
console.log (myArray[5]['name']);
A:
PHP arrays are weird and represent many data structures at once. An Array in JavaScript is closer to an traditional array although it is heterogeneous because of JavaScript's dynamic typing and probably other reasons.
Arrays in JavaScript use integer indices, but Objects in JavaScript represent key value pairs. These are what you want to use. You can have Arrays of Objects, and Object properties can contain arrays (and other objects).
myArray = [];
myArray[5] = {name: "Jack", age: "38", location: "Australia"};
console.log(myArray[5].name); // could also use ["name"]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
cannot import name get_user_model
I use django-registrations and while I add this code in my admin.py
from django.contrib import admin
from customer.models import Customer
from .models import UserProfile
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth import get_user_model
class UserProfileInline(admin.StackedInline):
model = UserProfile
can_delete = False
class UserProfileAdmin(UserAdmin):
inlines=(UserProfileInline, )
admin.site.unregister(get_user_model())
admin.site.register(get_user_model(), UserProfileAdmin)
admin.site.register(Customer)
I receive an error:
" cannot import name get_user_model "
in admin.py
what am I doing wrong?
A:
get_user_model is available in Django version >= 1.5 you are probably running Django version < 1.5. Upgrade the Django and the problem will be gone.
Or use this instead for Django version < 1.5:
from django.contrib.auth.models import User
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to calculate “real” distance between cursor and distant object?
I don't really know how to formulate the title, but the problem is the following:
I'm using a scripting language called "SQF" which has been created by a company named "Bohemia Interactive" (no, I do not work for them) and it's for modding their games. So I won't fill up these lines with code. If somebody else knows it and wants to see, comment and I'll add what I've tried so far.
The issue anyway is rather abstract, so I'm going to explain it with an archer and his target. Ratios may not be correct as they are only for explanation.
Say I (as the player) am the archer (first person), the target is 10m away, has a diameter of 2m and appears 200px in diameter on the screen. Now I aim 50px left of the target edge, execute my desired function and and get the info that this is 1m away from the target (2m from its center).
Now, I move 90m back, so the target is 100m away and appears 100px in diameter (don't know if that's correct, but you get the idea). Now I am aiming 25px left of the target and again, execute my desired function and it should tell me again that the distance is 1m.
Now, the "real" distance was 1m in both cases, but on my screen it was 50px at the first aim and 25px at the second.
So, what I am looking for is a (mathematical/programmatical) model to get the "real" distance between the target and where I aimed, no matter how far away I was from the target. I do have the positions of both archer and target in 3D coordinates. Though SQF is a very special language, it does provides a function to calculate the distance in meters and to dertermine certain geometrical values:
https://community.bistudio.com/wiki/Category:Command_Group:_Math
... so there's no need for that.
I know, this is very abstract, but I am hoping, somebody could give a hint or knows a mathematical procedure to do that.
If somebody knows how to do it in C, C++ or Java, I can write these languages, so that would be great!
A:
You cannot count with px, px are irrelevant because of different resolutions.
Cast a ray onto plane at your target location perpendicular to the direction(target loc - actor loc) vector. Then calculate the distance between ray(aiming direction) intersection with that plane and your target location on the plane.
Note, this is one way of doing it. If you dont need exact results or have only one resolution or have the situation simplified in any other ways, there could be easier solution.
tl;dr you will have to do math and read some tutorials on ray casting. Code and step-by-step explanation would not fit few paragraphs.
EDIT: another solution could be using trigonometric functions. Because you know hypotenuse is distance / cos(th). Where th is angle between direction to target and aiming direction and distance is...distance. Now you only calculate the length of opposite: sqrt(dist^2 - hypotenuse ^2), and that is your result.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to auto start window service
I have a window service which i developed in c# (vs2008).
please tell me what should i do to make it auto start after installation and also auto start on every time when system gets restarted.
EDIT:
I am using setup & deployment project to install it.
Thanks
A:
Follow the instructions given here to add an installer to your Service application. Pay particular attention to step 5, where you set the StartType property.
To start the service after installation, see Automatically start a Windows Service on install
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Variable of type that conforms to protocol
I have a struct that conforms to a protocol. That protocol specifies a variable that needs to conform to another protocol. In my struct I want to declare that variable using a specific type that conforms to the needed protocol.
The code, which should make it a lot more clear:
protocol ViewModel {
var isActive: Bool { get }
}
struct TestViewModel: ViewModel {
var isActive = false
}
protocol View {
var viewModel: ViewModel { get }
}
struct TestView: View {
var viewModel: TestViewModel
}
Using the above code, I will get a compiler error saying that the type TestView does not conform to protocol View. I would have expected that since TestViewModel conforms to ViewModel, that this would be okay, but apparently not.
Is there any way I can do what I want? I need to have the viewModel type casted to TestViewModel when using it in my TestView.
A:
You need to work with generics (associatedtype in protocols)
protocol ViewModel {
var isActive: Bool { get }
}
struct TestViewModel: ViewModel {
var isActive = false
}
protocol View {
associatedtype V: ViewModel
var viewModel: V { get }
}
struct TestView: View {
var viewModel: TestViewModel
}
This should works, you are telling to the struct that viewModel should be some class that implements ViewModel protocol
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Sharpen an image with a linear filter in PHP
I would like to read an image and sharpen it using a linear filter, which is this matrix:
H = [-0.5 -0.5 -0.5; -0.5 5 -0.5; -0.5 -0.5 -0.5]
I know about ImageMagick, is there any possibility to do just that?
A:
What you are after is applying a Convolution filter to an image, for that you can use PHP's built in imageconvolution() php.net function.
For usage, see Magilvia's example on php.net modified for your purpose:
<?php
$sharpenMatrix = array
(
array(-0.5, -0.5, -0.5),
array(-0.5, 5, -0.5),
array(-0.5, -0.5, -0.5)
);
// calculate the sharpen divisor
$divisor = array_sum(array_map('array_sum', $sharpenMatrix));
$offset = 0;
// apply the matrix
imageconvolution($img, $sharpenMatrix, $divisor, $offset);
?>
$img is a PHP image the convolution matrix (sharpening filter) is applied on
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is it necessary to pass iterator by const reference
class T
{
unordered_map<string, int> table;
...
void updateA(const unordered_map<string, int>::iterator& iter)
{
iter->second = 100;
}
void updateB(unordered_map<string, int>::iterator iter)
{
iter->second = 100;
}
};
Question> Which function is better(i.e. updateA or updateB)? If you have a better one, please propose.
Thank you
A:
1) First, to answer the question in the title, is it necessary to pass iterators by (const) reference: No. An iterator acts as a proxy for the data item in the container, regardless of whether or not the iterator itself is a copy of or a reference to another iterator. Also in the case when the iterator gets invalidated by some operation performed on the container, whether you maintain it by copy or reference will not make a difference.
2) Second, which of the two options is better.
I'd pass the iterator by copy (i.e. your second option).
The rule of thumb is: Pass by reference if you either want to modify the original variable passed to the function, or if the object you pass is large and copying it involves a major effort.
Neither is the case here: Iterators are small, lightweight objects, and given that you suggested a const-reference, it is also clear that you don't want to make a modification to it that you want reflected in the variable passed to the function.
3) As a third option, I'd like you to consider adding const to your second option:
void updateC(const unordered_map<string,int>::iterator iter)
{
iter->second = 100;
}
This ensures you won't accidentally re-assign iter inside the function, but still allows you to modify the original container item referred to by iter. It also may give the compiler the opportunity for certain optimizations (although in a simple situation like the one in your question, these optimizations might be applied anway).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
my Sprite isnt drawing on screen XNA
What am i missing here
Sprite Class
private Texture2D m_tex;
public Rectangle rect;
private bool m_travellingRight;
private int x_pos;
//constructor
public LightSaber(Texture2D tex, int xpos, int ypos)
{
m_tex = tex;
rect = new Rectangle(xpos, ypos, m_tex.Width, m_tex.Height);
m_travellingRight = true;
}
public void drawme(SpriteBatch sb)
{
if (m_travellingRight)
sb.Draw(m_tex, rect, Color.White);
else
sb.Draw(m_tex, rect, null, Color.White, 0, Vector2.Zero, SpriteEffects.FlipHorizontally, 0);
}
public void updateme(GamePadState pad)
{
x_pos = rect.X;
if (pad.ThumbSticks.Left.X < 0 && x_pos > 0)
{
m_travellingRight = false;
rect.X -= 4;
}
else if (pad.ThumbSticks.Left.X > 0 && x_pos < 800 - rect.Width)
{
m_travellingRight = true;
rect.X += 4;
}
}
}
}
Game1:
LightSaber lightSaber;
lightSaber = new LightSaber(Content.Load<Texture2D>("Textures\\Lightsaber"), 300, 500);
lightSaber.drawme(spriteBatch);
Thanks for your help.
A:
I miss a lot of code in the Game1.class, it would be nice to see the whole class to look if you're missing anything.
So for now, I'll give you a few tips:
I don't see any spritebatch.begin() or spritebatch.End() in the game1 class, since it's so shortened up, those should be required in order to draw anything.
You can also try putting a breakpoint on the moment it should be drawing the texture. and check if it actually does draw it, or at least can reach it.
Another possibility, it does draw the sprite, but it's location is out of bounds, (outside the game window), I prefer putting the position on 0 untill I'm sure it can draw the texture
Also, be aware when you're using statements without braces. Because without them, it can only read one line of code after the statement. if you add a new line or comment out the statement, then you'll get unexpected behaviour. (I had that mistake made before).
That's it for now, hope this helps
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PHP New Line : \n Not Working
Let's say I have this variable :
$Include = "Line 1;
//some Line 2 here";
and I want to write that variable into file and get exactly 2 lines like this :
Line1;
//some Line 2 here
but when I try to do it by using this code :
$Filename = 'somefile.php';
$Handle = fopen($Filename, "r");
$Contents = fread($Handle, filesize($Filename));
fclose($Handle);
$Contents = str_replace ('replace this', $Include, $Contents);
I see only one line like this :
Line 1; //some Line 2 here
how to make 2 lines using 1 variable? thanks
A:
If you are displaying the content using echo as an html content, you need to use nl2br() function.
echo nl2br($file_content);
This function will transform all \n into <br /> html tags which will be displayed on an html page as intended.
A:
Try this:
$Include = "Line 1; \r\n" .
" //some Line 2 here";
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Strange formulas that gave rise to Koszul duality
According to p.8 of the note KOSZUL DUALITY AND APPLICATIONS IN
REPRESENTATION THEORY by Geordie Williamson.
Let $M(\eta)$ be the Verma module of weight $\eta$, $L(\eta)$ be its unique simple quotient and $w_0$ be the longest element in $W$.
The strange formula in our notation is
$$[M(x\cdot 0):L(y\cdot 0)]=\sum_{i\ge 0}\dim\mathrm{Ext}_{\mathcal{O}}^i(M(w_0x\cdot 0):L(w_0y\cdot 0))$$ for $x,y\in W$.
Let $\mu$ be an integral, antidominant weight, $\Delta$ be the set of simple roots, $\Sigma=\{\alpha\in\Delta:\langle\mu+\rho,\alpha^\lor\rangle=0\}$ and $W^{\Sigma}=\{w\in W:w<ws_\alpha,\forall \alpha\in\Sigma\}$.
Do we still have $$[M(x\cdot \mu):L(y\cdot \mu)]=\sum_{i\ge 0}\dim\mathrm{Ext}_{\mathcal{O}}^i(M(w_0x\cdot \mu):L(w_0y\cdot \mu))$$
for $x,y\in W^\Sigma$?
A:
No. If the left-hand side is in the singular block, the right hand-side should be in the regular parabolic block, i.e. its Koszul dual.
(The regular block for the Borel subalgebra is Koszul-self-dual.)
See Beilinson-Ginzburg-Soergel: Koszul Duality Patterns in Representation Theory, J. Amer. Math. Soc. 9 (1996), 473-527.
EDIT: A counterexample to your question is in my answer to your previous similar question: https://mathoverflow.net/a/339679/15292
A:
This is a more concrete explanation for what Rafael Mrđen had said.
Let $x,w\in W^\Sigma$ and $\ell(x,w)=\ell(w)-\ell(x)$.
It is well-known that $\mathrm{ch}L(w\cdot\mu)=\sum_{x\in W^\Sigma}(-1)^{\ell(x,w)}P^{\Sigma}_{x,w}(1)\mathrm{ch}M(x\cdot\mu)$, where $P^\Sigma_{x,w}(q)=\sum_{i\ge 0}q^{\frac{\ell(x,w)-i}{2}}\dim\mathrm{Ext}_{\mathcal{O}}^i(M(x\cdot\mu),L(w\cdot\mu))$.
Let $P_{u,v}(q)$ be the Kazhdan Lusztig polynomial of $W$.
Let $P_{u,v}^{\Sigma,q}(q)$ be the parabolic Kazhdan Lusztig polynomial of $W^\Sigma$ of type $q$.
Let $P_{u,v}^{\Sigma,-1}(q)$ be the parabolic Kazhdan Lusztig polynomial of $W^\Sigma$ of type $-1$.
By Section 8.2 of KOSTANT MODULES IN BLOCKS OF CATEGORY $\mathcal{O}_S$ (taking $S=\emptyset$, $J=\Sigma$), it holds that
$P^\Sigma_{x,w}(q)=\sum_{t\in W_\Sigma}(-1)^{\ell(t)}P_{xt,w}(q)$.
Note that $W_\Sigma=\{w\in W: w\cdot\mu=\mu\}=\langle s_\alpha\in W: \alpha\in\Sigma\rangle$. It is well-known that $P_{x,w}^{\Sigma,q}(q)=\sum_{t\in W_\Sigma}(-1)^{\ell(t)}P_{xt,w}(q)$. Hence, $P^\Sigma_{x,w}(q)=P_{x,w}^{\Sigma,q}(q)$.
Let $w_\Sigma$ be the longest element in $W_\Sigma$.
It is well-known that $P_{x,w}^{\Sigma,-1}(q)=P_{xw_\Sigma,ww_\Sigma}(q)$.
Now we try to compute $[M(x\cdot\mu):L(y\cdot\mu)]$ by using inverse parabolic Kazhdan Lusztig polynomials.
By Corollary 3.7 (iii) of Hiroyuki Tagawa---Some Properties of Inverse Weighted Parabolic Kazhdan Lusztig Polynomials.
It holds that
$\sum_{x\le w\le y, w\in W^\Sigma}(-1)^{\ell(x)+\ell(w)}P_{x,w}^{\Sigma,q}(q)P_{w_0yw_\Sigma,w_0ww_\Sigma}^{\Sigma,-1}(q)=\delta_{x,y}=\begin{cases}
1, x=y\\
0, x\neq y\\
\end{cases}$.
Since $x\not\le w\implies P_{x,w}^{\Sigma,q}(q)=0$, $w\not\le y\iff w_0yw_\Sigma\not\le w_0ww_\Sigma\implies P_{w_0yw_\Sigma,w_0ww_\Sigma}^{\Sigma,-1}(q)=0$ and $(-1)^{\ell(x)+\ell(w)}=(-1)^{\ell(x,w)}$. It holds that
$\sum_{w\in W^\Sigma}(-1)^{\ell(x,w)}P_{x,w}^{\Sigma}(q)P_{w_0y,w_0w}(q)=\delta_{x,y}$.
Then $$\sum_{w\in W^\Sigma}P_{w_0y,w_0w}(1)\mathrm{ch}L(w\cdot\mu)$$
$$=\sum_{w\in W^\Sigma}\sum_{x\in W^\Sigma}(-1)^{\ell(x,w)}P^{\Sigma}_{x,w}(1)P_{w_0y,w_0w}(1)\mathrm{ch}M(x\cdot\mu)$$
$$=\sum_{x\in W^\Sigma}\sum_{w\in W^\Sigma}(-1)^{\ell(x,w)}P^{\Sigma}_{x,w}(1)P_{w_0y,w_0w}(1)\mathrm{ch}M(x\cdot\mu)$$
$$=\sum_{x\in W^\Sigma}\delta_{x,y}\mathrm{ch}M(x\cdot\mu)$$
$$=\mathrm{ch}M(y\cdot\mu).$$
Hence
$$[M(y\cdot\mu):L(w\cdot\mu)]=P_{w_0y,w_0w}(1)$$
and then
$$[M(x\cdot\mu):L(y\cdot\mu)]$$
$$=P_{w_0x,w_0y}(1)$$
$$=\sum_{i\ge 0}\dim\mathrm{Ext}_\mathcal{O}^i(M(w_0x\cdot(-2\rho)),L(w_0y\cdot(-2\rho))).$$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
LAG() and timestamps
Possible BigQuery bug here? I'm running a query that uses the LAG() function to get the previous timesamp value. Example:
schema:
id: STRING
time: TIMESTAMP
query:
SELECT id,
time as current_time, LAG(time,1) OVER (PARTITION BY id, order by time) as previous_time
FROM dataset.table
While "current_time" comes back as a timestamp value, "previous_time" comes back as an integer value. e.g.:
"12345", "2014-04-09 00:19:01 UTC", 1396992237000000
Any ideas on how to get LAG() return a TIMESTAMP?
A:
Yes, this is indeed a bug (I've filed it internally). This is leaking the internal representation of the timestamp, which is in microseconds.
You can work around this by using the USEC_TO_TIMESTAMP() function. As in:
SELECT id,
time as current_time,
USEC_TO_TIMESTAMP(LAG(time,1) OVER (PARTITION BY id, order by time)) as previous_time
FROM dataset.table
That said, this will break once we fix the bug. If you want to be notified when it is fixed, you can file it at the BigQuery public issue tracker here.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Nivo slider matrix photoframe
<div id="slider" class="nivoSlider">
{exp:channel:entries channel="properties" dynamic="no" limit="10" disable="categories|member_data|category_fields|member_data|pagination"}
Start matrix- {property_photos limit="1" sort="asc"}
Photo frame- {photo_images size="slider"}
<a href="{title_permalink="/properties/view"}"><1mg src="{photo:url}" alt="" title="#htmlcaption" /></a>
{/photo_images} {/property_photos} - close matrix
<div id="htmlcaption" class="nivo-html-caption">
<strong>{property_address}</strong><span>{rooms} rooms,{bathrooms} Baths,{beds} beds, House size:{house_size} sq.ft., Price $ {price} <a href="#"> View Property</a></span>
</div>{/exp:channel:entries} </div></div>
Could anyone give me some advice on how to improve this? When validating html, it warns that's the html caption div is repeated twice. Is there anyway to slim this down ?
A:
I'm not sure how you've implemented that or what else is surrounding it but if you had 10 entries, you'd repeat the div 10 times - if you're getting this error repeating twice - you have 2 entries.
If that is expected behavior then I'd imagine the issue is that because you're calling id='htmlcaption' and ID's MUST be unique - you simply need to append the entry ID so that it's unique
<div id="htmlcaption-{entry_id}" class="nivo-html-caption">
If you require that div only once then you should use the simple conditional…
{if count==1}
<div id="htmlcaption" class="nivo-html-caption">...stuff here</div>
{/if}
If you need that div at the very end, use this instead:
{if count == '{absolute_results}'}
<div id="htmlcaption" class="nivo-html-caption">...stuff here</div>
{/if}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Select URL from an attribute using XPath
I would like to retrieve the file url from a HTML meta-tag, given in the content attribute.
Here is the example HTML code:
<meta content="https://www.domain.com/player/player-viral.swf?config=
https://www.domain.com/configxml?id=133291&logo.
link=http://www.domain.org/Amin+Rostami/-/Havam+Toei&
image=https://www.domain.com/img/3lv68bc5w-1396897306.jpeg&provider=audio&
file=http://s10.domain.me/music/A/[one]/test-msusic.mp3" property="og:video"/>
I would like to get the file url, in this case http://s10.domain.me/music/A/[one]/test-msusic.mp3
A:
You can use substring-after() to extract the link after the file= from the content attribute of a meta tag:
substring-after(//meta/@content, "file=")
Demo (using xmllint):
$ cat input.xml
<meta content="https://www.domain.com/player/player-viral.swf?config=
https://www.domain.com/configxml?id=133291&logo.
link=http://www.domain.org/Amin+Rostami/-/Havam+Toei&
image=https://www.domain.com/img/3lv68bc5w-1396897306.jpeg&provider=audio&
file=http://s10.domain.me/music/A/[one]/test-msusic.mp3" property="og:video"/>
$ $ xmllint input.xml --xpath 'substring-after(//meta/@content, "file=")'
http://s10.domain.me/music/A/[one]/test-msusic.mp3
|
{
"pile_set_name": "StackExchange"
}
|
Q:
R Markdown: How do I make text float around figures?
I made a flowchart with R which I included in my R Markdown file.
How it looks like right now:
The code:
```{r flowchart-data, echo = FALSE, message = FALSE, fig.cap = "Ablauf der Datenverarbeitung", fig.align = "right", fig.width = 7, fig.height = 6, out.extra = 'trim = {0 1.1cm 0 0}, clip', out.width=".7\\textwidth"}
library(grid)
library(Gmisc)
# grid.newpage()
# set some parameters to use repeatedly
leftx <- .2
midx <- .5
rightx <- .8
myBoxGrob <- function(text, ...) {
boxGrob(label = text, bjust = "top", box_gp = gpar(fill = "lightgrey"), ...)
}
# create boxes
(Pharmazie <- myBoxGrob("Verbrauchsdaten von der\n Spitalpharmazie (Excel-Tabelle)", x=leftx, y=1, width = 0.36))
(Finanzen <- myBoxGrob("Belegzahlen vom Ressort\n Finanzen (Excel-Tabelle)", x=rightx, y=1, width = 0.36))
(A <- myBoxGrob("Import der Daten aus Excel ins\n Microsoft Access (Datenbanksoftware)", x=midx, y=0.83, width = 0.45))
(B <- myBoxGrob("Zusammenführen der Informationen\n und erstellen neuer, berechneter Tabellen", x=midx, y=.66, width = 0.45))
(C <- myBoxGrob("Export der neu erstellten Tabellen\n in Form von Excel-Tabellen", x=midx, y=.49, width = 0.45))
(D <- myBoxGrob("Import der neuen Tabellen in R", x=midx, y=.32, width = 0.45))
(E <- myBoxGrob("Berechnung und grafische Darstellung\n der Grafiken und Tabellen", x=midx, y=.19, width = 0.45))
connectGrob(Pharmazie, A, "L")
connectGrob(Finanzen, A, "L")
connectGrob(A, B, "N")
connectGrob(B, C, "N")
connectGrob(C, D, "N")
connectGrob(D, E, "N")
```
What I would like:
I want the text to use the space on the left of the figure.
I would like for the figure caption to align with the center of the figure. Right now the caption is in the middle of the page, ignoring if the figure is centered, right or left aligned.
How can I achieve those things?
EDIT 1: I want to knit to pdf.
EDIT 2: As requested in the comments, how my page looks now:
A:
There is a chunk option called fig.env with which one can switch from the figure to the marginfigure environment.
Unfortunetly, the list of possible environments does not include wrapfigure. Therefore we will alter the plot chunk:
defOut <- knitr::knit_hooks$get("plot") # save the default plot hook
knitr::knit_hooks$set(plot = function(x, options) { # set new plot hook ...
x <- defOut(x, options) # first apply the default hook
if(!is.null(options$wrapfigure)) { # then, if option wrapfigure is given ...
# create the new opening string for the wrapfigure environment ...
wf <- sprintf("\\begin{wrapfigure}{%s}{%g\\textwidth}", options$wrapfigure[[1]], options$wrapfigure[[2]])
x <- gsub("\\begin{figure}", wf, x, fixed = T) # and replace the default one with it.
x <- gsub("{figure}", "{wrapfigure}", x, fixed = T) # also replace the environment ending
}
return(x)
})
The comments should clarify what we are actually doing here. Notice, that the expected value of wrapfigure is a list of two elements. The first one tells LaTeX to move the figure to either side of the page. The second element tells LaTeX the width of the wrapped figure. To move a figure with a width of 0.7\\textwidth to the right you set wrapfigure = list("R", 0.7) (as you might have guessed, L moves it to the left).
All we have to do now is to include the wrapfig package in the YAML and set this chunk option. Here is a reproducible example:
---
header-includes:
- \usepackage{wrapfig}
- \usepackage{lipsum}
output:
pdf_document:
keep_tex: true
---
```{r, include = F}
defOut <- knitr::knit_hooks$get("plot") # save the default plot hook
knitr::knit_hooks$set(plot = function(x, options) { # set new plot hook ...
x <- defOut(x, options) # first apply the default hook
if(!is.null(options$wrapfigure)) { # then, if option wrapfigure is given ...
# create the new opening string for the wrapfigure environment ...
wf <- sprintf("\\begin{wrapfigure}{%s}{%g\\textwidth}", options$wrapfigure[[1]], options$wrapfigure[[2]])
x <- gsub("\\begin{figure}", wf, x, fixed = T) # and replace the default one with it.
x <- gsub("{figure}", "{wrapfigure}", x, fixed = T) # also replace the environment ending
}
return(x)
})
```
Vivamus vehicula leo a justo. Quisque nec augue. Morbi mauris wisi, aliquet vitae, dignissim eget, sollicitudin molestie, ligula. In dictum enim sit amet risus. Curabitur vitae velit eu diam rhoncus hendrerit. Vivamus ut elit. Praesent mattis ipsum quis turpis. Curabitur rhoncus neque eu dui. Etiam vitae magna. Nam ullamcorper. Praesent interdum bibendum magna. Quisque auctor aliquam dolor. Morbi eu lorem et est porttitor fermentum. Nunc egestas arcu at tortor varius viverra. Fusce eu nulla ut nulla interdum consectetuer. Vestibulum gravida.
```{r echo = F, warning = F, message = F, fig.width=7, fig.height = 6, out.width = ".7\\textwidth", fig.cap = "My Flowchart", fig.align="right", wrapfigure = list("R", .7)}
plot(mpg ~ hp, data = mtcars)
```
Morbi mattis libero sed est. Vivamus vehicula leo a justo. Quisque nec augue. Morbi mauris wisi, aliquet vitae, dignissim eget, sollicitudin molestie, ligula. In dictum enim sit amet risus. Curabitur vitae velit eu diam rhoncus hendrerit. Vivamus ut elit. Praesent mattis ipsum quis turpis. Curabitur rhoncus neque eu dui. Etiam vitae magna. Nam ullamcorper. Praesent interdum bibendum magna. Quisque auctor aliquam dolor. Morbi eu lorem et est porttitor fermentum. Nunc egestas arcu at tortor varius viverra. Fusce eu nulla ut nulla interdum consectetuer. Vestibulum gravida. Morbi mattis libero sed est.
Notice, that this solution most probably only works with a chunk creating a single plot. It should be possible to extent that to a chunk containing several figures.
A:
I struggled a lot with this as well, but for html-output.
There is an argument to the r chunk that solved the problem for me:
out.extra='style="float:right; padding:10px"'
|
{
"pile_set_name": "StackExchange"
}
|
Q:
vscode python refactor failed
When I tried to rename myset in the following code, I saw the following message.
class NumberGenerator:
def __init__(self):
self.__myset__ = set()
def uncount(self, i):
self.__myset__.add(i)
Refactor failed. module 'rope.base.ast' has no attribute 'Str'
[<FrameSummary file refactor.py, line 294 in watch>, <FrameSummary file refactor.py, line 274 in _process_request>, <FrameSummary file refactor.py, line 206 in _rename>, ...
It's so long, if you want to see I can show you. Is this code wrong? It works, though. Why does refactor not work?
A:
It doesn't work because Rope has some bugs in it. If you install Pylance then you may have better success (it will automatically prompt you to update your settings appropriately).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
"@" Decorator (in Python)
Possible Duplicate:
Understanding Python decorators
What function does the "class decorator"/"method decorator" (@) serve? In other words, what is the difference between this and a normal comment?
Also, what does setter do when using @previousMethod.setter before a method? Thank you.
A:
@decorator
def function(args):
#body
is just syntactic sugar for:
def function(args):
#body
function = decorator(function)
That's really it.
As you see, the decorator gets called, so it's by no means a comment.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Error Element '' cannot be located in parent view
Why I am getting this error:
Element '<xpath expr="//form/footer/button[@name='create_payment']"
name="">' cannot be located in parent view
Error context:
View `account.register.payments.wizard.from.invoices.inherited`
[view_id: 660, xml_id:
account_bankgiro_payment_file.view_account_payment_from_invoices_inherit_account_bankgiro, model: account.register.payments, parent_id: 384]
None" while parsing /home/prachh/odoo-new/11/apps/account_bankgiro_payment_file/views/inherited_account_register_payments.xml:11, near
while everything seems correct? Here is my code:
<record id="view_bankgiro_transfer_download" model="ir.ui.view">
<field name="name">account.payment.bankgiro.download</field>
<field name="model">account.payment.bankgiro</field>
<field name="arch" type="xml">
<form string="Download BankGiro Transfer File" version="7.0">
<group>
<p class="oe_grey" colspan="4">
Click on the file to save it somewhere on your computer. Then upload that file on your bank's homebanking website.
</p>
<field name="file" filename="filename"/>
<field name="filename" invisible="True"/>
</group>
<group>
</group>
<footer>
<button string="Cancel" class="oe_link" special="cancel" invisible="1"/>
</footer>
</form>
</field>
</record>
<record id="inv_bankgiro_pay_tree" model="ir.ui.view">
<field name="name">account.bankgiro.pay.tree</field>
<field name="model">account.payment.bankgiro</field>
<field name="arch" type="xml">
<form string="Invoices to be paid via BankGiro">
<field name="vendor_invoice">
<tree editable="bottom" delete="true" create="false" decoration-danger="(recip_bankgiro_acct == False) or (memo == '') or (bool_red == True)">
<field name="id" invisible="1"/>
<field name="partner_id"/>
<field name="recip_bankgiro_acct"/>
<field name="number"/>
<field name="ocr_number"/>
<field name="memo"/>
<field name="date_due" invisible="1"/>
<field name="pay_date"/>
<field name="origin"/>
<field name="residual" string="Payment Amount" sum="Total"/>
<field name="state"/>
<field name="currency_id"/>
<field name="bool_red" invisible="1"/>
</tree>
</field>
<footer>
<button name="btn_generate_bankgiro" string="Generate BankGiro Payment File"
type="object" class="btn btn-primary"/>
<button string="Cancel" class="btn-default" special="cancel"/>
</footer>
</form>
</field>
</record>
<record id="inv_tree" model="ir.ui.view">
<field name="name">account.invoice.pay.tree</field>
<field name="model">account.invoice</field>
<field name="arch" type="xml">
<tree>
<field name="id" invisible="1"/>
<field name="partner_id"/>
<field name="recip_bankgiro_acct"/>
<field name="number"/>
<field name="ocr_number"/>
<field name="memo"/>
<field name="date_due" invisible="1"/>
<field name="pay_date"/>
<field name="origin"/>
<field name="pay_amt" string="Payment Amount" sum="Total"/>
<field name="state"/>
<field name="currency_id"/>
<field name="bool_red" invisible="1"/>
</tree>
</field>
</record>
<record id="view_account_bankgiro_payment_tree" model="ir.ui.view">
<field name="name">account.payment.bankgiro.tree</field>
<field name="model">account.payment.bankgiro</field>
<field name="arch" type="xml">
<tree create="false">
<field name="name"/>
<field name="currency_id" invisible="1"/>
<field name="date"/>
<field name="total_amount" options="{'currency_field': 'currency_id'}"/>
</tree>
</field>
</record>
<record id="view_account_bankgiro_payment_form" model="ir.ui.view">
<field name="name">account.payment.bankgiro.form</field>
<field name="model">account.payment.bankgiro</field>
<field name="arch" type="xml">
<form create="false" edit="false">
<sheet>
<div class="oe_button_box" name="button_box">
<button class="oe_stat_button" name="button_invoices"
string="Invoices" type="object"
icon="fa-bars"/>
<button class="oe_stat_button" name="button_payments"
string="Payments" type="object"
icon="fa-bars"/>
</div>
<div class="oe_title">
<h1><field name="name"/></h1>
</div>
<group>
<group>
<field name="filename" invisible="1"/>
<field name="file" filename="filename" readonly="True"/>
</group>
<group>
<field name="currency_id" invisible="1"/>
<field name="date" readonly="True"/>
<field name="total_amount" options="{'currency_field': 'currency_id'}" readonly="True"/>
</group>
</group>
</sheet>
</form>
</field>
</record>
<record id="account_payment_method_bankgiro_transfer" model="account.payment.method">
<field name="name">BankGiro Transfer</field>
<field name="code">bankgiro_tr</field>
<field name="payment_type">outbound</field>
</record>
<record id="view_account_payment_from_invoices_inherit_account_bankgiro" model="ir.ui.view">
<field name="name">account.register.payments.wizard.from.invoices.inherited</field>
<field name="model">account.register.payments</field>
<field name="inherit_id" ref="account.view_account_payment_from_invoices"/>
<field name="arch" type="xml">
<xpath expr="//field[@name='payment_date']" position="attributes">
<attribute name="attrs">{'invisible':[('payment_method_code','=','bankgiro_tr')]}</attribute>
</xpath>
<xpath expr="//field[@name='communication']" position="attributes">
<attribute name="attrs">{'invisible':[('payment_method_code','=','bankgiro_tr')]}</attribute>
</xpath>
<xpath expr="//field[@name='amount']" position="attributes">
<attribute name="attrs">{'invisible':[('payment_method_code','=','bankgiro_tr')]}</attribute>
</xpath>
<xpath expr="//form/footer/button[@name='create_payment']" position="attributes" name="" >
<attribute name="attrs">{'invisible':[('payment_method_code','=','bankgiro_tr')]}</attribute>
</xpath>
<xpath expr="//form/footer/button[@special='cancel']" position="before">
<button string='Validate' name="create_bankgiro_payment" type="object" class="btn-primary" attrs="{'invisible': [('payment_method_code','!=','bankgiro_tr')]}"/>
</xpath>
</field>
</record>
A:
xpath doesn't have the attribute name, just remove it from your view.
You have this:
<xpath expr="//form/footer/button[@name='create_payment']" position="attributes" name="" >
<attribute name="attrs">{'invisible':[('payment_method_code','=','bankgiro_tr')]}</attribute>
</xpath>
You need to write this:
<xpath expr="//form/footer/button[@name='create_payment']" position="attributes">
<attribute name="attrs">{'invisible':[('payment_method_code','=','bankgiro_tr')]}</attribute>
</xpath>
EDIT
Comment those lines which are modifying create_payment button:
<!-- <xpath expr="//form/footer/button[@name='create_payment']" position="attributes">
<attribute name="attrs">{'invisible':[('payment_method_code','=','bankgiro_tr')]}</attribute>
</xpath> -->
Then restart Odoo and update through the interface the module account_bankgiro_payment_file. After that, tell me if the error disappears or you have another one.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
C# Lambda performance issues/possibilities/guidelines
I'm testing performance differences using various lambda expression syntaxes. If I have a simple method:
public IEnumerable<Item> GetItems(int point)
{
return this.items.Where(i => i.IsApplicableFor(point));
}
then there's some variable lifting going on here related to point parameter because it's a free variable from lambda's perspective. If I would call this method a million times, would it be better to keep it as it is or change it in any way to improve its performance?
What options do I have and which ones are actually feasible? As I understand it is I have to get rid of free variables so compiler won't have to create closure class and instantiate it on every call to this method. This instantiation usually takes significant amount of time compared to non-closure versions.
The thing is I would like to come up with some sort of lambda writing guidelines that would generally work, because it seems I'm wasting some time every time I write a heavily hit lambda expression. I have to manually test it to make sure it will work, because I don't know what rules to follow.
Alternative method
& example console application code
I've also written a different version of the same method that doesn't need any variable lifting (at least I think it doesn't, but you guys who understand this let me know if that's the case):
public IEnumerable<Item> GetItems(int point)
{
Func<int, Func<Item, bool>> buildPredicate = p => i => i.IsApplicableFor(p);
return this.items.Where(buildPredicate(point));
}
Check out Gist here. Just create a console application and copy the whole code into Program.cs file inside namespace block. You will see that the second example is much much slower even though it doesn't use free variables.
A contradictory example
The reason why I would like to construct some lambda best usage guidelines is that I've met this problem before and to my surprise that one turned out to be working faster when a predicate builder lambda expression was used.
Now explain that then. I'm completely lost here because it may as well turn out I won't be using lambdas at all when I know I have some heavy use method in my code. But I would like to avoid such situation and get to the bottom of it all.
Edit
Your suggestions don't seem to work
I've tried implementing a custom lookup class that internally works similar to what compiler does with a free variable lambda. But instead of having a closure class I've implemented instance members that simulate a similar scenario. This is the code:
private int Point { get; set; }
private bool IsItemValid(Item item)
{
return item.IsApplicableFor(this.Point);
}
public IEnumerable<TItem> GetItems(int point)
{
this.Point = point;
return this.items.Where(this.IsItemValid);
}
Interestingly enough this works just as slow as the slow version. I don't know why, but it seems to do nothing else than the fast one. It reuses the same functionality because these additional members are part of the same object instance. Anyway. I'm now extremely confused!
I've updated Gist source with this latest addition, so you can test for yourself.
A:
What makes you think that the second version doesn't require any variable lifting? You're defining the Func with a Lambda expression, and that's going to require the same bits of compiler trickery that the first version requires.
Furthermore, you're creating a Func that returns a Func, which bends my brain a little bit and will almost certainly require re-evaluation with each call.
I would suggest that you compile this in release mode and then use ILDASM to examine the generated IL. That should give you some insight into what code is generated.
Another test that you should run, which will give you more insight, is to make the predicate call a separate function that uses a variable at class scope. Something like:
private DateTime dayToCompare;
private bool LocalIsDayWithinRange(TItem i)
{
return i.IsDayWithinRange(dayToCompare);
}
public override IEnumerable<TItem> GetDayData(DateTime day)
{
dayToCompare = day;
return this.items.Where(i => LocalIsDayWithinRange(i));
}
That will tell you if hoisting the day variable is actually costing you anything.
Yes, this requires more code and I wouldn't suggest that you use it. As you pointed out in your response to a previous answer that suggested something similar, this creates what amounts to a closure using local variables. The point is that either you or the compiler has to do something like this in order to make things work. Beyond writing the pure iterative solution, there is no magic you can perform that will prevent the compiler from having to do this.
My point here is that "creating the closure" in my case is a simple variable assignment. If this is significantly faster than your version with the Lambda expression, then you know that there is some inefficiency in the code that the compiler creates for the closure.
I'm not sure where you're getting your information about having to eliminate the free variables, and the cost of the closure. Can you give me some references?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Implementing/specifying permutation groups in coq
I am trying to implement/specify the permutation groups (symmetric groups) in coq. This went well for a bit, until I tried to prove that the identity is actually the identity. My proof gets stuck on proving that the proposition "x is invertible" is exactly the same as the proposition "id * x is invertible".
Are these two propositions actually the same? Am I trying to prove something that is not true? Is there a better way of specifying the permutation group (as a type)?
(* The permutation group on X contains all functions between X and X that are bijective/invertible *)
Inductive G {X : Type} : Type :=
| function (f: X -> X) (H: exists g: X -> X, forall x : X, f (g x) = x /\ g (f x) = x).
(* Composing two functions preserves invertibility *)
Lemma invertible_composition {X : Type} (f g: X -> X) :
(exists f' : X -> X, forall x : X, f (f' x) = x /\ f' (f x) = x) ->
(exists g' : X -> X, forall x : X, g (g' x) = x /\ g' (g x) = x) ->
exists h : X -> X, forall x : X, (fun x => f (g x)) (h x) = x /\ h ((fun x => f (g x)) x) = x.
Admitted.
(* The group operation is composition *)
Definition op {X : Type} (a b : G) : G :=
match a, b with
| function f H, function g H' => function (fun x => f (g x)) (@invertible_composition X f g H H')
end.
Definition id' {X : Type} (x : X) : X := x.
(* The identity function is invertible *)
Lemma id_invertible {X : Type} : exists g : X -> X, forall x : X, id' (g x) = x /\ g (id' x) = x.
Admitted.
Definition id {X : Type} : (@G X) := function id' id_invertible.
(* The part on which I get stuck: proving that composition with the identity does not change elements. *)
Lemma identity {X: Type} : forall x : G, op id x = x /\ @op X x id = x.
Proof.
intros.
split.
- destruct x.
simpl.
apply f_equal.
Abort.
A:
I believe that your statement cannot be proved without assuming extra axioms:
proof_irrelevance:
forall (P : Prop) (p q : P), p = q.
You need this axiom to show that two elements of G are equal when the underlying functions are:
Require Import Coq.Logic.ProofIrrelevance.
Inductive G X : Type :=
| function (f: X -> X) (H: exists g: X -> X, forall x : X, f (g x) = x /\ g (f x) = x).
Arguments function {X} _ _.
Definition fun_of_G {X} (f : G X) : X -> X :=
match f with function f _ => f end.
Lemma fun_of_G_inj {X} (f g : G X) : fun_of_G f = fun_of_G g -> f = g.
Proof.
destruct f as [f fP], g as [g gP].
simpl.
intros e.
destruct e.
f_equal.
apply proof_irrelevance.
Qed.
(As a side note, it is usually better to declare the X parameter of G explicitly, rather than implicitly. It is rarely the case that Coq can figure out what X should be on its own.)
With fun_of_G_inj, it should be possible to show identity simply by applying it to each equality, because fun a => (fun x => x) (g a) is equal to g for any g.
If you want to use this representation for groups, you'll probably also need the axiom of functional extensionality eventually:
functional_extensionality:
forall X Y (f g : X -> Y), (forall x, f x = g x) -> f = g.
This axiom is available in the Coq.Logic.FunctionalExtensionality module.
If you want to define the inverse element as a function, you probably also need some form of the axiom of choice: it is necessary for extracting the inverse element g from the existence proof.
If you don't want to assume extra axioms, you have to place restrictions on your permutation group. For instance, you can restrict your attention to elements with finite support -- that is, permutation that fix all elements of X, except for a finite set. There are multiple libraries that allow you to work with permutations this way, including my own extensional structures.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Circumscribed ellipsoid of minimum Hilbert-Schmidt norm
Let $K\subseteq \mathbb{R}^n$ be a full-dumensional convex body. The Löwner ellipsoid of $K$ is the unique ellipsoid of smallest volume containing $K$. My question is about a related object: the ellipsoid containing $K$ that minimizes the sum of squared axis lengths (the square root of this sum is what I called the Hilbert-Schmidt norm of the ellipsoid).
My question is a reference request: has the circumscribed ellipsoid of minimum Hilbert-Schmidt norm been studied?
Let me, for context, say briefly what I know about this ellipsoid. It is not hard to use convex duality to derive a characterization of this ellipsoid which is similar to John's decomposition of the identity. I can show that the minimizing ellipsoid is $E = FB_2^n$, for a linear map $F$ and $B_2^n$ the Euclidean $n$-dimensional ball, if and only if there exist contact points $v_1, \ldots, v_m \in K \cap E$ and positive reals $\mu_1, \ldots, \mu_m$, such that
$$
\sum_{i=1}^m{\mu_i v_i} = 0 \ \text{ and }\ \sum_{i=1}^m{\mu_i v_i \otimes v_i} = (FF^T)^2.
$$
The minimizer is unique because the objective is strictly convex. The only difference with John's theorem is that $(FF^T)^2$ has replaced $FF^T$.
It follows that the minimizer $E$ is a ball if and only if the Löwner ellipsoid of $K$ is a ball, although this fact has a more direct proof using the arithmetic mean-geometric mean inequality.
A:
One reference that I could locate is the following Minimum norm ellipsoids as a measure in high-cycle fatigue criteria by Nestor Zouain, presented at a conference in 2005 (see $\S5$ of that pdf). However, I believe this question must have been considered earlier---if I find something older I'll update my answer.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Write/Read command to the specified port
I use this usb gpio device. It uses some command to send/receive data from input/output channel. There is a guide that explains how commands send on numato website. There are some sample code for C on Windows. But I use fedora and my code is below for read/write gpio. I can't read data.
Code sample for Windows
#include "stdafx.h"
#include "windows.h"
#include "string.h"
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hComPort;
char cmdBuffer[32];
char responseBuffer[32];
DWORD numBytesWritten;
DWORD numBytesRead;
/*
Lookup the port name associated to your GPIO device and update the
following line accordingly. The port name should be in the format
"\\.\COM<port Number>". Notice the extra slaches to escape slashes
themselves. Read http://en.wikipedia.org/wiki/Escape_sequences_in_C
for more details.
*/
wchar_t PortName[] = L"\\\\.\\COM14";
/*
Open a handle to the COM port. We need the handle to send commands and
receive results.
*/
hComPort = CreateFile(PortName, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
if (hComPort == INVALID_HANDLE_VALUE)
{
printf("Error: Unable to open the specified port\n");
return 1;
}
/* EXAMPLE 1 - MANIPULATE GPIO0 BY SENDING COMMAND */
/**************************************************************************
Send a command to output a logic high at GPIO 0. The command that is
used to accomplish this acton is "gpio set 0". It is important to send
a Carriage Return character (ASCII value 0x0D) to emulate the ENTER
key. The command will be executed only when the GPIO module detects
Carriage Return character.
**************************************************************************/
/* Write a Carriage Return to make sure that any partial commands or junk
data left in the command buffer is cleared. This step is optional.
*/
cmdBuffer[0] = 0x0D;
if(!WriteFile(hComPort, cmdBuffer, 1, &numBytesWritten, NULL))
{
CloseHandle(hComPort);
printf("Error: Unable to write to the specified port\n");
return 1;
}
/* Copy the command to the command buffer */
strcpy(cmdBuffer, "gpio set 0");
/* Append 0x0D to emulate ENTER key */
cmdBuffer[10] = 0x0D;
/* Write the command to the GPIO module. Total 11 bytes including 0x0D */
printf("Info: Writing command <gpio set 0> to the GPIO module\n");
if(!WriteFile(hComPort, cmdBuffer, 11, &numBytesWritten, NULL))
{
CloseHandle(hComPort);
printf("Error: Unable to write to the specified port\n");
return 1;
}
printf("Info: <gpio set 0> Command sent successfuly\n");
/* EXAMPLE 2 - MANIPULATE GPIO10 BY SENDING COMMAND */
/**************************************************************************
Send a command to output a logic high at GPIO 0. The command that is
used to accomplish this acton is "gpio set 0". It is important to send
a Carriage Return character (ASCII value 0x0D) to emulate the ENTER
key. The command will be executed only when the GPIO module detects
Carriage Return character.
**************************************************************************/
/* Write a Carriage Return to make sure that any partial commands or junk
data left in the command buffer is cleared. This step is optional.
*/
cmdBuffer[0] = 0x0D;
if(!WriteFile(hComPort, cmdBuffer, 1, &numBytesWritten, NULL))
{
CloseHandle(hComPort);
printf("Error: Unable to write to the specified port\n");
return 1;
}
/*
Copy the command to the command buffer. GPIO number 10 and beyond are
referenced in the command by using alphabets starting A. For example
GPIO10 willbe A, GPIO11 will be B and so on. Please note that this is
not intended to be hexadecimal notation so the the alphabets can go
beyond F.
*/
strcpy(cmdBuffer, "gpio set A");
/* Append 0x0D to emulate ENTER key */
cmdBuffer[10] = 0x0D;
/* Write the command to the GPIO module. Total 11 bytes including 0x0D */
printf("Info: Writing command <gpio set A> to the GPIO module\n");
if(!WriteFile(hComPort, cmdBuffer, 11, &numBytesWritten, NULL))
{
CloseHandle(hComPort);
printf("Error: Unable to write to the specified port\n");
return 1;
}
printf("Info: <gpio set A> Command sent successfuly\n");
/* EXAMPLE 3 - READ ADC 1 */
/**************************************************************************
Write "adc read 1" comamnd to the device and read back response. It is
important to note that the device echoes every single character sent to
it and so when you read the response, the data that is read will
include the command itself, a carriage return, the response which you
are interested in, a '>' character and another carriage return. You
will need to extract the response from this bunch of data.
/*************************************************************************/
/* Write a Carriage Return to make sure that any partial commands or junk
data left in the command buffer is cleared. This step is optional.
*/
cmdBuffer[0] = 0x0D;
if(!WriteFile(hComPort, cmdBuffer, 1, &numBytesWritten, NULL))
{
CloseHandle(hComPort);
printf("Error: Unable to write to the specified port\n");
return 1;
}
/* Flush the Serial port's RX buffer. This is a very important step*/
Sleep(10);
PurgeComm(hComPort, PURGE_RXCLEAR|PURGE_RXABORT);
/* Copy the command to the command buffer */
strcpy(cmdBuffer, "adc read 1");
/* Append 0x0D to emulate ENTER key */
cmdBuffer[10] = 0x0D;
/* Write the command to the GPIO module. Total 11 bytes including 0x0D */
printf("Info: Writing command <adc read 1> to the GPIO module\n");
if(!WriteFile(hComPort, cmdBuffer, 11, &numBytesWritten, NULL))
{
CloseHandle(hComPort);
printf("Error: Unable to write to the specified port\n");
return 1;
}
printf("Info: <adc read 1> Command sent successfuly\n");
/*Read back the response*/
if(!ReadFile(hComPort, responseBuffer, 16, &numBytesRead, NULL))
{
CloseHandle(hComPort);
printf("Error: Unable to write to the specified port\n");
return 1;
}
/* Add a null character at the end of the response so we can use the buffer
with string manipulation functions.
*/
responseBuffer[numBytesRead] = '\0';
printf("Info: ADC value read from the device = %.*s", 4, responseBuffer + 12);
/* Close the comm port handle */
CloseHandle(hComPort);
return 0;
}
My code for Ubuntu
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <unistd.h>
#define MAXBUFFER 32
int main(int argc, char* argv[])
{
struct termios serialSettings;
char *deviceName = "/dev/ttyACM0";
char bufferRecv[MAXBUFFER], bufferSend[MAXBUFFER];
int readInt, sendInt;
int fd = open(deviceName, O_RDWR | O_NOCTTY | O_NDELAY);
if(fd == -1) {
printf("\n %s\n", deviceName);
perror("unable to open port");
}
else {
printf("port is opened!\n");
bufferSend[0] = 0x0D; /* clear buffer */
strcpy(bufferSend, "gpio set 0"); /* */
sendInt = write(fd, bufferSend, strlen(bufferSend));
if(sendInt <= 0){
printf("Unable to write to the port\n");
return -1;
}
printf("<gpio set 0> : Command sent successfuly\n");
strcpy(bufferSend, "gpio read 0"); /* */
sendInt = write(fd, bufferSend, strlen(bufferSend));
if(sendInt <= 0){
printf("Unable to write to the port\n");
return -1;
}
printf("<gpio read 0> : Command sent successfuly\n");
readInt = read(fd, bufferRecv, sizeof(bufferRecv));
if(readInt < 0){
printf("Unable to read to the port\n");
return -1;
}
bufferRecv[strlen(bufferRecv)] = '\0';
printf("read=%c-\n", bufferRecv[0]);
}
close(fd);
return 0;
}
The output
port is opened!
<gpio set 0> : Command sent successfuly
<gpio read 0> : Command sent successfuly
Unable to read to the port
A:
The "successful" write() s are false positives. The data was output, but not properly received by the device.
Your program has not properly configured the serial port using termios after the open() and before any write() or read(). You should configure the port for canonical rather than raw mode. You also need to configure the baud rate, character length, parity and number of stop bits.
Use the Serial Programming Guide for POSIX Operating Systems.
Workable(?) configuration code might look like (for 115200 baud rate, 8N1 and canonical input, i.e. read terminates on NL character):
#include <termios.h>
struct termios serialSettings;
speed_t spd;
int fd;
int rc;
fd = open(deviceName, O_RDWR | O_NOCTTY);
if (fd == -1) {
printf("\n %s\n", deviceName);
perror("unable to open port");
return -1;
}
rc = tcgetattr(fd, &serialSettings);
if (rc < 0) {
perror("unable to get attributes");
return -2;
}
spd = B115200;
cfsetospeed(&serialSettings, spd);
cfsetispeed(&serialSettings, spd);
serialSettings.c_cflag &= ~CSIZE;
serialSettings.c_cflag |= CS8;
serialSettings.c_cflag &= ~PARENB;
serialSettings.c_cflag &= ~CSTOPB;
serialSettings.c_cflag &= ~CRTSCTS; /* no HW flow control? */
serialSettings.c_cflag |= CLOCAL | CREAD;
serialSettings.c_iflag &= ~(PARMRK | ISTRIP | IXON | IXOFF | INLCR);
serialSettings.c_iflag |= ICRNL;
serialSettings.c_oflag &= ~OPOST;
serialSettings.c_lflag &= ~(ECHO | ECHONL | ISIG | IEXTEN);
serialSettings.c_lflag |= ICANON;
rc = tcsetattr(fd, TCSANOW, &serialSettings);
if (rc < 0) {
perror("unable to set attributes");
return -2;
}
/* serial port is now configured and ready */
...
Additional comments on your code:
bufferRecv[strlen(bufferRecv)] = '\0';
This is illogical code. If you could actually determine the string length of what's in bufferRecv, then that text would already be null terminated, and this assignment would not be necessary.
Secondly and much worse, the read() does not terminate the receive data with a null byte, so the strlen() could scan past the buffer end.
The read() does return the number of bytes stored in the buffer, and that value can be used to locate where a null byte should be written.
Workable code would look like (note the reduction in requested read length):
readInt = read(fd, bufferRecv, sizeof(bufferRecv) - 1);
if (readInt < 0){
perror("Unable to read from the port\n");
return -3;
}
bufferRecv[readInt] = '\0';
printf("ADC value read = %s\n", bufferRecv);
The strings that you send to the USB device should be preceded and terminated with a carriage return just like the Win examples:
strcpy(bufferSend, "\rgpio set 0\r");
...
strcpy(bufferSend, "\rgpio read 0\r");
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Python OS - check if file exists, if so rename, check again, then save
I have a script that takes a file from a form, renames it and uploads it to a folder and inserts record into a database. I would like to add the functionality where before the file is saved, it checks the upload folder to determine if the filename exists. If it does exist, renames the file in a loop and then saves the file.
What I have currently:
file = request.files['xx']
extension = os.path.splitext(file.filename)[1]
xx = str(uuid.uuid4()) + extension
## if xx exists .. xx = str(uuid.uuid4()) + extension.. loop endlessly.
file.save(os.path.join(app.config['UPLOAD_FOLDER'], xx)
A:
Haven't tested this yet but you can use os.path.isfile() to check if a file already exists (for directories, use os.path.exists).
import os
def save():
file = request.files['xx']
extension = os.path.splitext(file.filename)[1]
xx = generate_filename(extension)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], xx))
def generate_filename(extension):
xx = str(uuid.uuid4()) + extension
if os.path.isfile(os.path.join(app.config['UPLOAD_FOLDER'], xx)):
return generate_filename(extension)
return xx
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Solving algebraic equation system with partial derivatives
I have a list of equations. Some of them are algebraic equations like 2x == y / (y+1), others contains derivatives in them(e.x. df/dx == 0). Note they are not differential equations. As they can be simplified from other algebraic equations before taking the (partial) derivative. After taking the partial derivative, they will all be algebraic equations themselves. For example, I have the following three equations:
x^2 + y = 8
z = 9x + 4y
dz/dx = 0
After replacing y with 8 - x^2. dz/dx is 9-8x. Letting 9-8x equals to 0 we get x = 9/8, hence the solution.
My question is how to do this in Mathematica? In reality, I have dozens of equations like that, it's possible to solve manually, but I need to learn this skill to solve using software, if it's possible.
A:
One possibility is to use Dt on your equations:
eq1 = x^2 + y == 0;
eq2 = z == 9 x + 4 y;
Solve[
{
eq1, Dt[eq1, x],
eq2, Dt[eq2, x],
Dt[z,x]==0
},
{x,y,z,Dt[y,x],Dt[z,x]}
]
{{x -> 9/8, y -> -(81/64), z -> 81/16, Dt[y, x] -> -(9/4), Dt[z, x] -> 0}}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to Upload Multiple file in AngularJS
I use ngFileUpload for upload files but it can upload only 1 file.
I want to upload and Image File and PDF File. How to upload multi file?
Help me please.
(function () {
'use strict';
var app = angular.module('pageApp', ['ngFileUpload']);
app.controller('MyCtrl', ['$scope', 'Upload', '$timeout', function ($scope, Upload, $timeout) {
$scope.uploadPic = function (file) {
file.upload = Upload.upload({
url: 'save_form.php',
data: {
file: file,
username: $scope.username
},
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}
};
}]);
})();
<form name="myForm">
Profile Picture: <input type="file" ngf-select="" ng-model="picFile" name="file" ngf-accept="'image/*'">
<br>
Resume(.pdf): <input type="file" ngf-select="" ng-model="resumeFile" name="fileResume">
<br>
<button ng-disabled="!myForm.$valid" ng-click="uploadPic(picFile)">Submit</button>
</form>
A:
If you want to upload multiple files at the same time you can combine those 2 input field and add multiple attribute to the input tag. Make sure your backend can accept multiple files / support the following features.
<form name="myForm">
Picture & Resume: <input type="file" ngf-select=""
ng-model="picFile" name="file" ngf-pattern="'image/*,application/pdf'" multiple>
<br>
<button ng-disabled="!myForm.$valid" ng-click="uploadPic(picFile)">Submit</button>
</form>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to determine if there are foreign characters (not from English alphabet) in a string?
I am storing google maps result in my database and google sometimes return special characters so I tried doing the encodeURI(string) first before storing to database. However, it includes the spaces when encoding so it makes it difficult to read the values in the database.
As you can see, the spaces in some rows are also encoded as %20. How can identify which strings have special characters so only those rows will be encoded and the other rows using the same alphabet will remain the same? Is there any efficient approach to that?
Edited on March 10, 2014:
This is what I just did to solve this:
$unreadable_characters = array("%20", "%27", "%2E", "%2C", "_");
$readable_characters = array(" ", "'", ".", ",", " ");
//and then use str_replace to change all those characters to their readable formats:
$keyword = str_replace($unreadable_characters, $readable_characters, $value[0]);
Using urldecode() when retrieving values from database still outputs the correct strings in the UI :)
A:
I think you can use a regex to check the alphabets:
var st = $('#id').val();
if(/^[a-zA-Z0-9- ]*$/.test(st) == false) {
alert('string contains non english characters');
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do i work with objects in Self-Executing Anonymous Functions?
Q1 - I have
(function (document,window) {
var shelf = window.shelf = function (foo) {
var init = function () {
console.log("in init" + foo);
};
alert("in shelf.js "+ foo + "type" + typeof init);
};
})(document, window);
I want to call the init function in shelf in my HTML page in the style
var api=shelf("1234");
api.init();
Or
shelf().init;
How do i get this to work?, I read on anonymous self executing functions at,
Self-executing anonymous functions and closures ,
what is self-executing anonymous function or what is this code doing? ,
Why do you need to invoke an anonymous function on the same line? ,
http://markdalgleish.com/2011/03/self-executing-anonymous-functions/
I need the document and window objects as i will be using this to add components dynamically to my html page
Q 2 - Is this the better way or should I use anything else to ensure modularity + reuse?
A:
In your code, init is not available to be called externally. I believe you're looking for something like this:
(function (document,window) {
var shelf = window.shelf = function (foo) {
this.init = function () {
console.log("in init" + foo);
};
alert("in shelf.js "+ foo + "type" + typeof this.init);
};
})(document, window);
var api = new shelf("1234");
api.init();
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Interval average of 1D data
I have two 1D arrays, one for measured data and the other one for location. For example, the measured data could be temperature and the other array the heights of the measurement:
temp = np.asarray([10, 9.6, 9.3, ..., -20.3, -21.0]) # Temperature in celsius
height = np.asarray([129, 145, 167, ..., 5043, 5112]) # Height in meters
As you can see, the height of the measurements is not regularly spaced.
I want to compute the mean temperature in regularly spaced height intervals. This is some kind of moving average, but the window size is variable, because the data points inside the interval of interest is not always the same.
This could be done with a for loop in the following way:
regular_heights = np.arange(0, 6000, 100) # Regular heights every 100m
regular_temps = []
for i in range(len(regular_heights)-1):
mask = np.logical_and(height > regular_heights[i], height < regular_heights[i+1])
mean = np.mean(temp[mask])
regular_temps.append(mean)
regular_temps = np.hstack((regular_temps))
I don't like this approach that much and I was wondering if there would be a more "numpy-style" solution.
A:
You are probably looking for UnivariateSpline. For example:
from scipy.interpolate import UnivariateSpline
temp = np.asarray([10, 9.6, 9.3, 9.0, 8.7]) # Temperature in celsius
height = np.asarray([129, 145, 167, 190, 213]) # Height in meters
f = UnivariateSpline(height, temp)
Now you can evaluate f wherever you want:
regular_heights = np.arange(120, 213, 5) # Regular heights every 5m
plot(height, temp, 'o', regular_heights, f(regular_heights), 'x')
|
{
"pile_set_name": "StackExchange"
}
|
Q:
derivative vanishes
I'm seeing from the Professor's notes that the that the derivative of the Euclidean scalar product squared $||y(x)||^2 = \langle y(x), y(x)\rangle$ simply vanishes. That is $\frac{d}{dx} ||y(x)||^2=0$. I've got no clue why.
Here $y(x)$ is the solution of the DGL $y(x)'=Ay(x)$. $A$ is a $n\times n$-matrix in this case and $y(x)$ is a function from $\mathbb{R}$ to $\mathbb{R}^n$. Anyone can help me?
A:
$\newcommand{\Brak}[1]{\left\langle #1\right\rangle}\newcommand{\Transp}[1]{#1^{\mathsf{T}}}$If $y' = Ay$, then
\begin{align*}
\frac{d}{dt} \Brak{y(t), y(t)}
&= \Brak{y'(t), y(t)} + \Brak{y(t), y'(t)} \\
&= 2\Brak{y(t), y'(t)} \\
&= 2\Brak{y(t), Ay(t)}
= 2\Brak{\Transp{A}y(t), y(t)}.
\end{align*}
If $\Transp{A} = -A$, the last expression is equal to $-2\Brak{y(t), Ay(t)}$, implying
$$
\frac{d}{dt} \Brak{y(t), y(t)} = 0.
$$
Conversely, if $y' = Ay$ and
$$
0 = \frac{d}{dt}\bigg|_{t = 0} \Brak{y(t), y(t)}
= 2\Brak{y(0), Ay(0)}
= 2\Brak{y(0), \Transp{A}y(0)}
$$
for every initial condition $y(0) = y_{0}$, then
$$
0 = \Transp{y_{0}}\bigl[\tfrac{1}{2}(A + \Transp{A})\bigr] y_{0}\quad\text{for every $y_{0}$.}
$$
By the spectral theorem, $\tfrac{1}{2}(A + \Transp{A})$ (the symmetric part of $A$) has real eigenvectors; letting $y_{0}$ run through an eigenbasis shows $\frac{1}{2}(A + \Transp{A}) = 0$, i.e., $A = -\Transp{A}$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Тире между подлежащим и сказуемым
В каком случае между подлежащим и сказуемым ставится тире, а в каком - не ставится?
A:
Тире ставится между подлежащим и сказуемым, если оба они являются существительными и второе определяет качество первого. Проще говоря, если между этими словами можно поставить союз "это".
Пример: Москва - столица, фрегат - корабль.
Тире не ставится, если между подлежащим и сказуемым стоит отрицательная частица "не".
Пример: Работа не волк, курица не птица.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Something Powerful
Underground
Is where I'm found
Markets rise and fall with me
As do actions of countries
Who am I?
Hint:
You will find me on the driver's lips, attached to the car, and part of the road in cold parts of the US.
These hints are very specific and literally true without any logical stretches. Looking for correct reasoning.
A:
Is it:
Oil
Underground
Is where I'm found
To get to oil, you have to dig underground for this resource
Markets rise and fall with me
Depending on OPEC (world's biggest distributor of oil) prices its oil, the markets can fall (when the price is really low like now) or rise (when the price gets high)
As do actions of countries
Countries can react in many different ways depending on the oil industry
According to the hints...
Oil might be seen when splashed onto the driver's face when fixing the engine, in the fuel tank of the car, and sometimes spilled on the road. The road might be the ocean as it serves as a road for ships and there are unfortunately, lots of oil spills
A:
This is just a Guess...
Salt
Underground Is where I'm found
Salt is found underground.
Markets rise and fall with me
Salt is a much needed material for markets/stores.
As do actions of countries
Many countries have taken the initiative to try to reduce salt consumption in their specific country. Also there are many countries very dependent on salt as it used for so many things.
A:
Another possibility:
Iron (or Steel - works either way)
Underground
Is where I'm found
Iron comes from mines underground
Markets rise and fall with me
Iron is a major commodity in markets
As do actions of countries
Iron is traded between countries. It could also be used metaphorically to refer to warfare.
You will find me on the driver's face
A driver is a type of golf club, typically made from iron (or wood)
attached to the car
Many parts of a car are made from steel, which is an alloy of iron
and on the road in cold parts of the US.
When it gets cold, some drivers put chains or iron-studded winter tires on their cars for traction.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Dark theme project and others view at Eclipse under Windows 7
I'm using the default color theme @ Eclipse under Windows 7, but I've got following problem: in my project explorer and others view looks terrible. I've tried some solutions - changing colors in eclipse, changing some windows colors, but neither works. Do you have any suggestions how to fix it?
Here are examples how it is displayed:
ps: I cannot install plugins in eclipse in this machine :/
Same problem is with the project explorer view.
A:
If you using Eclipse Luna - it's very hard to change this specific colors, you need a theme. Just updated the version to Mars and everything is perfect!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Split line with multiple delimiters in Unix
I have the below lines in a file
id=1234,name=abcd,age=76
id=4323,name=asdasd,age=43
except that the real file has many more tag=value fields on each line.
I want the final output to be like
id,name,age
1234,abcd,76
4323,asdasd,43
I want all values before (left of) the = to come out as separated with a , as the first row and all values after the (right side) of the = to come below for in each line
Is there a way to do it with awk or sed? Please let me know if for loop is required for the same?
I am working on Solaris 10; the local sed is not GNU sed (so there is no -r option, nor -E).
A:
FILE=yourfile.txt
# first line (header)
cat "$FILE" | head -n 1 | sed -r "s/=[^,]+//g"
# other lines (data)
cat "$FILE" | sed -r "s/[^,]+=//g"
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does git-svn support different revisions for each subdirectory?
I have a repository that is currently using Subversion, but I'd like to use Git locally. So I've checked it out with git-svn:
git svn clone http://localserver/svn/repo
Now, inside repo, I have a few directories:
repo/
trunk/
A/
B/
C/
tags/
branches/
The repository is currently at revision 100. I'd like to checkout revision 90 inside repo/trunk/B and then make a tag for the whole repo, so that repo/trunk/A is rev 100, repo/trunk/B is rev 90, and repo/trunk/C is rev 100.
In svn I'd do
cd repo/trunk/B
svn update -r90 .
Is there an equivalent using git-svn, and can I then make a tag that captures the state of the entire repository at that moment?
I tried this:
cd repo/trunk/B
git svn find-rev r90 # yields 18376729f51b71212d94dcba239a2482cda9f3c8
git checkout 18376729f51b71212d94dcba239a2482cda9f3c8 .
And as far as I can tell, the files in repo/trunk/B have changed according to git status, but files in other subdirectories have not changed. Is this the right way to go about it, or is there a more "correct" way?
A:
As you have mentioned above, you can use git checkout to do this manually for the files in trunk/B. The file contents will now show as modified, though, and if you ran git commit, you would be resubmitting the old files' contents as new files.
This is generally not how git operates, and I'd venture to say that this is generally not what you really want to do with svn either. With git, you want the whole work tree to move together in lockstep, and as a result, support for partial checkouts or updating a subtree to a different version is nonexistent for the most part.
When this sort of scenario comes up, you should ask yourself whether A, B, and C are really different "projects". When you tag, do you tag them together, or would you just tag A's files separately from B's? What about branching? I've found that git repos work best when you include all the files that are necessary a project but no more than that. Limiting repositories to the project level increases some bookkeeping but also helps with flexibility. This is why you'll see many posts around StackOverflow discussing the use of git submodules and subtrees (two distinct concepts) for managing groups of repositories.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I search for a specific value in a string in a JSON object?
I am trying to pull data from this API: https://data.medicare.gov/resource/ax9d-vq6k.json
My front end has an input field where I want the users to be able to search for their zip code.
$('#searchClick').on("click", function() {
// collecting the value from the input field.
var zipCode = $('#zipCode').val().trim();
// This is our API call using the name from the input box to make the call for all surgeons with a last name of something specific.
var queryURL = "https://data.medicare.gov/resource/ax9d-vq6k.json?human_address=" + zipCode;
console.log("Click Is Working");
// Clearing the main Div after every search
$(".resultsDiv").empty();
// This is the Actual API call.
$.ajax({
url: queryURL,
method: "GET"
}).done(function(response) {
// console.log(response);
The JSON object in my API call returns this:
{
"rn_staffing_rating": 4,
"federal_provider_number": "015009",
"health_inspection_rating": 5,
"processing_date": "2017-12-01T00:00:00",
"provider_state": "AL",
"staffing_rating": 4,
"qm_rating": 5,
"location": {
"latitude": "34.514971",
"human_address": "{\"address\":\"701 MONROE STREET NW\",\"city\":\"RUSSELLVILLE\",\"state\":\"AL\",\"zip\":\"35653\"}",
"needs_recoding": false,
"longitude": "-87.736372"
},
"overall_rating": 5,
"provider_name": "BURNS NURSING HOME, INC."
}
I just want to request where the Human_address contains the zip code that the user searches.
Any help would be appreciated. Thanks.
A:
The zip you want to find is stored within JSON data in the location.human_address property, so you'll need to parse that before comparing the values to the ZIP you want to find. You can use filter() to do that:
var response = getData();
var zip = '35150';
var zipMatches = response.filter(function(o) {
return JSON.parse(o.location.human_address).zip == zip;
});
console.log(zipMatches);
function getData() {
// proxy for your AJAX call...
return [{
"rn_staffing_rating": 4,
"federal_provider_number": "015009",
"health_inspection_rating": 5,
"processing_date": "2017-12-01T00:00:00",
"provider_state": "AL",
"staffing_rating": 4,
"qm_rating": 5,
"location": {
"latitude": "34.514971",
"human_address": "{\"address\":\"701 MONROE STREET NW\",\"city\":\"RUSSELLVILLE\",\"state\":\"AL\",\"zip\":\"35653\"}",
"needs_recoding": false,
"longitude": "-87.736372"
},
"overall_rating": 5,
"provider_name": "BURNS NURSING HOME, INC."
}, {
"rn_staffing_rating": 5,
"federal_provider_number": "015010",
"health_inspection_rating": 2,
"processing_date": "2017-12-01T00:00:00",
"provider_state": "AL",
"staffing_rating": 5,
"qm_rating": 5,
"location": {
"latitude": "33.164666",
"human_address": "{\"address\":\"315 WEST HICKORY STREET\",\"city\":\"SYLACAUGA\",\"state\":\"AL\",\"zip\":\"35150\"}",
"needs_recoding": false,
"longitude": "-86.254598"
},
"overall_rating": 4,
"provider_name": "COOSA VALLEY NURSING FACILITY"
}]
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
237V seen across terminals of a dimmer switch when 'off'
I have a household, dual module dimmer switch. One module is working and dims a 3A sidelight loop, the downlight loop with 4 drivers doesn't work and I'm fault finding.
I noticed on the working module that the voltage across the terminals is 237V when off and then reduces when on - it's a push on/off and turn dim. The voltage changes when turned as expected.
But I was expecting to see 0V on my tester when off, what am I misunderstanding?
Is the tester and the way the dimmer work showing a potential difference even though no current is flowing?
A:
There is always voltage across the circuit, supplied by the power company. By Kirchhoffs's Voltage Law, the sum of the voltages across the individual components must always equal the supply voltage. When the light is on, there is little or no voltage across the switch and all of the voltage appears across the light. But when the light is off, all of the voltage appears across the switch and there is no voltage across the light (and no current through it).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why Ansi_nulls does not work?
Assume that I have 2 tables named aTable1, aTable2
aTable1 has userID set to identity and contains the following data:
userID email FirstName LastName
1 NULL C CC
2 NULL D DD
3 [email protected] A AA
4 [email protected] B BB
5 [email protected] E EE
6 [email protected] NULL NULL
7 [email protected] NULL NULL
aTable2 contains the following data:
userID email FirstName LastName Title
3 [email protected] A AA student
4 [email protected] B BB student
5 [email protected] E EE student
NULL NULL C CC dean
NULL NULL D DD advisor
NULL [email protected] NULL NULL student2
NULL [email protected] NULL NULL student3
I want to update aTable2.userID based on aTable1, but knowing that 2 tables have null values in it, so i do like this:
set ANSI_NULLS off
update aTable2
set aTable2.userID = a.userID
from aTable a, aTable2 b
where a.FirstName = b.FirstName and a.LastName = b.LastName and a.email = b.email
However, what this update does not update all the userID, in fact, it only updates those that have email not equal to null, but I already set ANSI_NULLS to off.
What did I do wrong?
A:
It is documented that it won't work:
SET ANSI_NULLS ON affects a comparison only if one of the operands of the comparison is either a variable that is NULL or a literal NULL. If both sides of the comparison are columns or compound expressions, the setting does not affect the comparison.
A:
To get your update query to work, you can try something like this:
UPDATE a2
SET
userId = a.UserId
FROM
aTable2 a2
JOIN aTable1 a ON
ISNULL(a.Email,'NULL') = ISNULL(a2.Email,'NULL') AND
ISNULL(a.FirstName,'NULL') = ISNULL(a2.FirstName,'NULL') AND
ISNULL(a.LastName,'NULL') = ISNULL(a2.LastName,'NULL')
When the values are NULL, I've arbitrarily set the value to 'NULL' -- use some distinct value that will not appear in your data to ensure you won't receive false positives.
I've also seen other solutions using OR criteria in the JOIN and checking both values for NULL:
((a.Email = a2.Email) OR (a.Email IS NULL AND a2.Email IS NULL)) ...
Good luck.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What event to call when ListView selected item changed?
I'd like to run a procedure--once--whenever the selected item in a ListView changes. The obvious choice would be OnSelectItem, but it's called twice when the user moves from one selected item to another (using mouse or arrow keys). Similarly, OnChange is called three times when moving between items.
Is there an event generated only once under these conditions? OnClick is generated once, but doesn't cover moving between items using arrow keys, etc.
A:
You can do it like this using OnSelectItem.
Remember the last selected item.
When the OnSelectItem fires, check if the current selected item differs from the one you remembered.
If so, perform your task, and make a note of the new selected item.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Dividing day times into intervals in R for NYC Taxi data
I am working with the NYC taxi data. So, I am trying to divide the pickup times into 1 hour intervals using R . Could anyone help me an efficient way of doing it?
head(data$dropoff_datetime)
[1] 2013-01-01 15:18:10 2013-01-06 00:22:54 2013-01-05 18:54:23 2013-01-07 23:58:20 2013-01-07 23:34:24 2013-01-07 15:38:37
So, in the present state, the data is of the form , "day time". What I want to do is that trim off the date and make a new column in the dataframe data with values from {0,1,...,23} depending on the time.
A:
You can use the function hour of the package lubridate like that
require(lubridate)
hour(ymd_hms(data$dropoff_datetime))
hour taking as argument any date time objects.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Data binding an Enum stored in an object into a Winforms ComboBox?
Anyone knows how to do this?
I tried this, but it just populates this ComboBox which I already do.
What I need is a way to get the combobox updated whenever the enum property on my object changes:
DataObject.DataEnum
but also get the above Enum updated whenever I change the selected item in the combobox.
Is it possible to do this?
Normally I am used to do the binding this way:
this.TextBox.DataBindings.Add ( "Text", this.DataObject, "Name", false, DataSourceUpdateMode.OnPropertyChanged );
which works great.
A:
You can use a two-way binding on the SelectedItem property of the ComboBox. When adding values to the combo box, be sure to add the enum values and not just strings that match their display name.
comboBox.Items.Add(ConsoleColor.Red);
comboBox.Items.Add(ConsoleColor.Blue);
// ... etc
Now SelectedItem can be set or get as the enum instead of as a string.
EDIT
It sounds like maybe your object doesn't raise property change notifications which Windows Forms requires to detect that changes to the underlying object need to be refreshed in the UI. Here is an article about how to do that.
EDIT 2
Here's a code sample. I verified this works correctly.
public partial class Form1 : Form {
private Person p = new Person( );
public Form1( ) {
InitializeComponent( );
comboBox1.DataSource = Enum.GetValues( typeof( Gender ) );
textBox1.DataBindings.Add( "Text", p, "Name", false, DataSourceUpdateMode.OnPropertyChanged );
comboBox1.DataBindings.Add( "SelectedItem", p, "Gender", false, DataSourceUpdateMode.OnPropertyChanged );
label1.DataBindings.Add( "Text", p, "Name", false, DataSourceUpdateMode.Never );
label2.DataBindings.Add( "Text", p, "Gender", false, DataSourceUpdateMode.Never );
}
private void Form1_Load( object sender, EventArgs e ) {
// yeah, that's right i voted for him,
// go ahead and downvote me
p.Name = "John McCain";
p.Gender = Gender.Male;
}
private void Form1_Click( object sender, EventArgs e ) {
p.Name = "Sarah Palin";
p.Gender = Gender.Female;
}
}
public enum Gender {
Male,
Female
}
public class Person : INotifyPropertyChanged {
private string name;
private Gender gender;
public string Name
{
get { return name; }
set {
name = value;
PropertyChanged( this, new PropertyChangedEventArgs( "Name" ) );
}
}
public Gender Gender {
get { return gender; }
set {
gender = value;
PropertyChanged( this, new PropertyChangedEventArgs( "Gender" ) );
}
}
public event PropertyChangedEventHandler PropertyChanged = delegate {};
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Как протестировать метод, который меняет буквы в слове?
Начал вникать в unit test, потренировался на всяких простых арифметических операциях, все понятно.
Есть конкретный метод который меняет буквы в слове:
private static char[] exchangeCharInWord(char[] charArray, int first, int last ){
char tmp;
tmp=charArray[first];
charArray[first]=charArray[last];
charArray[last]=tmp;
return charArray;
}
никак не могу понять что мне здесь проверять.Вот начал писать...
public class TestMyClass {
@Test
public void test() {
MyClass c = new MyClass();
char[] word = {'h', 'e', 'l', 'o'};
int first = 0;
int last = word.length-1;
}
}
A:
Необходимо выделить возможные входные данные метода и результаты работы метода с этими данными. Например, такие тесты:
Тест метода на корректных данных (проверяем, что метод правильно меняет местами символы массива):
public void validInput_shouldSwap() {...}
Тест метода при отрицательных значениях индексов (индекса):
public void negativeIndex_shouldThrow() {...}
Тест метода, если индексы выходят за границы массива:
public void outOfBoundIndexValues_shouldThrow() {...}
В зависимости от реализации метода 2 и 3 тесты можно объединить в один.
Соответственно внутри каждого теста проверяете результаты работы метода с ожидаемыми.
A:
Немного обобщу ответ от Pavel Parshin. Для практически любого метода должны быть юнит-тесты нескольких типов:
Проверить, что метод корректно работает с корректными входными данными. В вашем случае -- действительно меняет символы в позициях first и last местами.
Проверить "угловые случаи". В вашем случае -- когда значения first и last совпадают. Строка при этом измениться не должна.
Проверить работу метода с некорректными данными. В вашем случае -- когда один из индексов (или оба) выходят за пределы массива. Обычно метод должен падать с исключением типа ArgumentException.
Второй случай может вам "подсказать" добавить проверку: если индексы совпадают, то можно просто выйти из метода.
Третий случай выявляет одно из преимуществ написания тестов -- вы забыли проверить входные данные на валидность. Упавший тест "напомнит" вам об этом.
Причем я бы рекомендовал писать тесты в "обратном" порядке -- от некорректных случаев к корректным. Это позволит сразу указать все нужные проверки и обойти самые простые ошибки.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SQLAlchemy: @property mapping?
I have following models:
class Details(db.Model):
details_id = db.Column(db.Integer, primary_key=True)
details_main = db.Column(db.String(50))
details_desc = db.Column(db.String(50))
class Data(db.Model):
data_id = db.Column(db.Integer, primary_key=True)
data_date = db.Column(db.Date)
details_main = db.Column(db.String(50))
@property
def details_desc(self):
result = object_session(self).\
scalar(
select([Details.details_desc]).
where(Details.details_main == self.details_main)
)
return result
Now, I would like to run query using filter which depends on defined property. I get empty results (of course proper data is in DB). It doesn't work because, probably, I have to map this property. The question is how to do this? (One limitation: FK are not allowed).
Data.query\
.filter(Data.details_desc == unicode('test'))\
.all()
A:
You can implement this with a regular relationship and an association proxy:
class Data(db.Model):
data_id = db.Column(db.Integer, primary_key=True)
data_date = db.Column(db.Date)
details_main = db.Column(db.String(50))
details = relationship(
Details,
primaryjoin=remote(Details.details_main) == foreign(details_main))
details_desc = association_proxy('details', 'details_desc')
Since there are no foreign keys in the schema, you need to tell SQLAlchemy yourself what the join condition for the relationship should be. This is what the remote() and foreign() annotations do.
With that in place, you can use an association_proxy "across" the relationship to create a property on Data which will work the way you want.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
About type definition of Hyperledger Fabric SDK for node.js
Sorry for the machine translation
Is type ByteBuffer in the type definition file index.d.ts of @ types / fabric-client the same as Buffer?
index.d.ts link
Please tell me if you have any other good inquiries.
A:
No, a ByteBuffer and Buffer are different objects. The Buffer is native to node.js and ByteBuffer is an npm package (see https://www.npmjs.com/package/bytebuffer). For example, see https://github.com/dcodeIO/ByteBuffer.js/issues/1 for converting a ByteBuffer to Buffer.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Pyqt5 to interface Arduino servo ErrorType " object has no attribute 'ser'"
I have a problem with interfacing the Arduino. I can communicate with the Arduino with a simple program like reading the data and writing them. I have created an interface using PyQt5 to control a servo motor and I get the error:
'Ui_MainWindow' object has no attribute 'ser'
The code I used is:
from PyQt5 import QtCore, QtGui, QtWidgets
import serial
import time
import sys
class Ui_MainWindow(object):
def setupUi(self, MainWindow, ser):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(318, 309)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton("pushButton", self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(120, 40, 85, 27))
self.pushButton.clicked.connect(self.OpenShutter)
self.pushButton_2 = QtWidgets.QPushButton("pushButton_2", self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(120, 150, 85, 27))
self.pushButton_2.clicked.connect(self.CloseShutter)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 318, 20))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "Open"))
self.pushButton_2.setText(_translate("MainWindow", "Close"))
def CloseShutter(self):
print("Shutter Closed")
self.ser.write(int(0))
def OpenShutter(self):
print("Shutter Opened")
self.ser.write(int(77))
if __name__ == "__main__":
ser = serial.Serial()
ser.port = '/dev/ttyACM0'
ser.timeout = 1
ser.baudrate = 9600
if ser.isOpen() == False:
ser.open()
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow, ser)
MainWindow.show()
sys.exit(app.exec_())
A:
The problem is that ser is not a member of the class so it will only exist in the context of the method, not in the context of the class.
The most recommended is not to modify the design and create a class that implements the logic, and in that class make a member of the class to the serial object. So I recommend not to modify the Ui_MainWindow class and restore it to the initial state.
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
QtWidgets.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.ser = serial.Serial()
self.ser.port = '/dev/ttyACM0'
self.ser.timeout = 1
self.ser.baudrate = 9600
if self.ser.isOpen() == False:
self.ser.open()
def CloseShutter(self):
print("Shutter Closed")
self.ser.write(int(0))
def OpenShutter(self):
print("Shutter Opened")
self.ser.write(int(77))
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Compute a hash from a stream of unknown length in C#
What is the best solution in C# for computing an "on the fly" md5 like hash of a stream of unknown length? Specifically, I want to compute a hash from data received over the network. I know I am done receiving data when the sender terminates the connection, so I don't know the length in advance.
[EDIT] - Right now I am using md5 and am doing a second pass over the data after it's been saved and written to disk. I'd rather hash it in place as it comes in from the network.
A:
MD5, like other hash functions, does not require two passes.
To start:
HashAlgorithm hasher = ..;
hasher.Initialize();
As each block of data arrives:
byte[] buffer = ..;
int bytesReceived = ..;
hasher.TransformBlock(buffer, 0, bytesReceived, null, 0);
To finish and retrieve the hash:
hasher.TransformFinalBlock(new byte[0], 0, 0);
byte[] hash = hasher.Hash;
This pattern works for any type derived from HashAlgorithm, including MD5CryptoServiceProvider and SHA1Managed.
HashAlgorithm also defines a method ComputeHash which takes a Stream object; however, this method will block the thread until the stream is consumed. Using the TransformBlock approach allows an "asynchronous hash" that is computed as data arrives without using up a thread.
A:
The System.Security.Cryptography.MD5 class contains a ComputeHash method that takes either a byte[] or Stream. Check out the documentation.
A:
Further to @peter-mourfield 's answer, here is the code that uses ComputeHash():
private static string CalculateMd5(string filePathName) {
using (var stream = File.OpenRead(filePathName))
using (var md5 = MD5.Create()) {
var hash = md5.ComputeHash(stream);
var base64String = Convert.ToBase64String(hash);
return base64String;
}
}
Since both the stream as well as MD5 implement IDisposible, you need to use using(...){...}
The method in the code example returns the same string that is used for the MD5 checksum in Azure Blob Storage.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Need to redirect form to multiple URLs based on input
I have a basic HTML form and I need help creating a bit of JS to redirect my form to different URLs based on the string typed in a text field.
<form class="form-inline">
<div class="form-group">
<input type="text">
<button type="submit">Go</button>
</div>
</form>
There will be 3 or 4 strings of text - to be entered in the input field - that are "valid" and I need them to make the form redirect to various pages on the site.
For instance, typing valid string "STRING1" would make the page redirect to example.com/something.html on form submit, or "STRING2" to example.com/otherpage.html.
But invalid strings would need to go to a page like "example.com/invalid.html."
The most useful thing I've seen so far is this guide: http://www.dynamicdrive.com/forums/showthread.php?20294-Form-POST-redirect-based-on-radio-button-selected
<script type="text/javascript">
function usePage(frm,nm){
for (var i_tem = 0, bobs=frm.elements; i_tem < bobs.length; i_tem++)
if(bobs[i_tem].name==nm&&bobs[i_tem].checked)
frm.action=bobs[i_tem].value;
}
</script>
In that code, each radio has a value assigned to it. But this doesn't help with text fields or having a blanket redirect if the string is invalid.
Thanks so much for your help.
A:
You could define the routes in an object :
<form class="form-inline">
<div class="form-group">
<input type="text">
<button id="submit-form" type="button">Go</button>
</div>
</form>
var urlMapping = {
"STRING1" : "./first.html",
"STRING2" : "./second.html",
"STRING3" : "./third.html"
}
$("#submit-form").click(function(){
var input = $("input").val().trim().toUpperCase();
if (urlMapping.hasOwnProperty(input)){
window.location = urlMapping[input];
}
else {
//if url not found, redirect to default url
window.location = "./default.html";
}
});
Note : I added .toUpperCase() to make it case-insensitive, so you have to be careful to define the urlMapping keys ("STRING1",..) in uppercase.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How does "Concealment" transfer to Dedicated Transports?
I have been looking over the combat benefits from the various force organisations granted by Gladius Strike Forces. The one that interests me is the 10th Company bonus where all units in this Company gain Concealment (Stealth until almost anything other than embarking, disembarking or shooting). However, I have a number of land speeder storms that act as dedicated transports that gain this status as well. So my question is if I disembark a concealed unit and its transport moves, does the entire unit loose concealment or just the Transport?
A:
Disembarkation is a move. So getting out will make the unit lose stealth, though the transport would retain stealth as long as it didn't move. If the transport moves (before or after disembarking) it loses stealth as well.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Clearcase application impact with April 2014 MS patch
Do you know of any impact on the ClearCase application for the below mentioned Microsoft patches?
My environment is Win 2003 Enterprise SP2
Security Bulletin Risk Description KB Number
MS14-017 Critical Vulnerabilities in Microsoft Word and Office Web Apps Could Allow Remote Code Execution KB2949660
MS14-018 Critical Cumulative Security Update for Internet Explorer KB2950467
MS14-019 Important Vulnerability in Windows File Handling Component Could Allow Remote Code Execution KB2922229
MS14-020 Important Vulnerability in Microsoft Publisher Could Allow Remote Code Execution KB2950145
A:
It depends on the nature of the ClearCase running on your server:
simple Base ClearCase client
ClearCase Vob server
CCRC server
Unless you see a warning from IBM, you can proceed with the installation, and double-check with IBM (communicating at least the full version of your ClearCase setup: cleartool -verall)
You can see some general advises in this thread:
VOB servers are specialized. Normally patches and service packs provide no benefits or improvements.
Does your IT department test patches and service packs before installing them enterprise wide? Blindly trusting any windows upgrade/sp has been empirically shown to be a Bad Idea(tm).
Get management involved. Yes patches and sp's are important, but so is having a working VOB server. If folks understand the risks to the company, they'll be more keen to work out a compromise. (Don't fall for the "we'll give you control of the server and you'll be in charge of patching it.")
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Validation ASP Classic DDL
Unfortinatly I need to use ASP classic...
I have a drop down list that I load from database, but i can validate it..I need to do validation with JavaScript
<select name= "ddlCategories">
<option value="-1"> choose
</option>
<%set con = Server.CreateObject("ADODB.Connection")
con.open "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" & Server.MapPath("WebData/DB.mdb") & ";"
set rs = con.Execute("Select * FROM Categories where mode=true")
while not rs.eof%>
<option value="<%=rs("CatID")%>"><%=rs("CategoryName")%></option>
<%rs.movenext
wend
rs.close
set rs= nothing
Con.close%>
</select>
-1 it is the default value, and in this value the validation need to work..
Hope you understand me, Thanks
This is the validation for the TextBox
<script type="text/javascript">
function ValidationAddCategory()
{
var cName = document.form.tbCategory.value;
if (cName== "")
{
alert("Please insert category name")
return(false)
}
return ture
}
function ValidationDelCategory() {
var oForm = document.getElementById('admin');
var oTemp, strErrors='';
//check 1
oTemp = document.getElementById('ddlCategories');
if (oTemp.value=='-1') {
strErrors+='- Please select a category\n';
}
//put more checks here for any other validation, add to strErrors
if (strErrors) {
alert('There were errors:\n'+strErrors);
}
}
</script>
A:
I assume that you have a form to validate before submitting...
In the example below, the form id is assumed to be "myForm" and the submit button is
<form id="myForm" ...
actually an input type="button" with an onclick of "checkSend();"
<input type="button" onclick="checkSend();" value="submit">
Also the select now has an Id of "ddlCategories"
The javascript for in the webpage head is as follows:
<script>
function checkSend() {
var oForm = document.getElementById('myForm');
var oTemp, strErrors='';
//check 1
oTemp = document.getElementById('ddlCategories');
if (oTemp.value=='-1') {
strErrors+='- Please select a category\n';
}
//put more checks here for any other validation, add to strErrors
if (strErrors) {
alert('There were errors:\n'+strErrors);
} else {
oForm.submit();
}
}
</script>
So for a demo here's a complete example (without the ASP bit)
<html>
<head>
<script>
function checkSend() {
var oForm = document.getElementById('myForm');
var oTemp, strErrors='';
//check 1
oTemp = document.getElementById('ddlCategories');
if (oTemp.value=='-1') {
strErrors+='- Please select a category\n';
}
//put more checks here for any other validation, add to strErrors
if (strErrors) {
alert('There were errors:\n'+strErrors);
} else {
alert('Submitting...'); //remove this - its for testing
oForm.submit();
}
}
</script>
</head>
<body>
<form id="myForm">
<select id="ddlCategories" name="ddlCategories">
<option value="-1">Please select a category</option>
<option value="1">Test</option> <!-- To be replaced by ASP Classic generation -->
</select>
<br>
<input type="button" onclick="checkSend();" value="submit">
</form>
</body>
</html>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Layout Elements Covering corners
I am using AbsoluteLayout to try and cover the entire screen with the elements I want to add to create a "FullScreen" menu but it does not cover it. this is what I get. let me share my code as well , as youu see the Pink panel does not cover the corner of the screen why is that?
MainActivity xml
<?xml version="1.0" encoding="utf-8"?> <AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.apos.champquess.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="77dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<ImageView
android:layout_width="404dp"
android:layout_height="550dp"
android:id="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignRight="@+id/button"
android:layout_alignEnd="@+id/button"
android:src="@color/colorAccent"
android:layout_below="@+id/button"
android:layout_x="280dp"
android:layout_y="78dp" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New RadioButton"
android:id="@+id/radioButton"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="231dp"
android:layout_marginStart="231dp"
android:layout_x="150dp"
android:layout_y="73dp" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New CheckBox"
android:id="@+id/checkBox"
android:layout_x="710dp"
android:layout_y="238dp" />
And MainActity Java
package com.example.apos.champquess;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//set content view AFTER ABOVE sequence (to avoid crash)
this.setContentView(R.layout.activity_main);
setContentView(R.layout.activity_main);
}
}
EDIT: This is what I want it to look like (example)
A:
quick answer here;
you use AbsoluteLayout
This class was deprecated in API level 3.
Use FrameLayout, RelativeLayout or a custom layout instead.
just take RelativeLayout as an example
ImageView is inside it and you have given width and height for it to possition it relatively
android:layout_width="404dp"
android:layout_height="550dp"
so it takes the size of that dimentions that's the reason it goes away the boundaries
+ you have padding s in your root tag AbsoluteLayout
if you want to give sizes manually give a small width like 75 dp
there are couple of ways do you task
but first do not try to give sizes manually then it will display differently in different screen sizes , but for a single screen you can give these values.
otherwise you need to use a value based on ratio. learn about layout_weight and `
What does android:layout_weight mean?
` and how to use it, a simple example -->Android Layout - layoutweight and weightsum
or pragmatically you can give sizes based on ratio
// get screen sises
Display display = this.getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int screenY = size.y;
int screenX = size.x;
RelativeLayout.LayoutParams yourView= new RelativeLayout.LayoutParams(screenX, 270 * screenY / 1920);
yourView.topMargin = 0;
yourView.leftMargin = 125 * screenX / 1080;
imgPoints.setLayoutParams(yourView);
and learn about RelativeLayout and LinearLayout behaviors as well
|
{
"pile_set_name": "StackExchange"
}
|
Q:
OrientDB Fetch Plan/Strategies with Tinkerpop
I've been using Tinkerpop 2.6 with OrientDB to manipulate the graph, and I'm running into some performance problems.
I suspect the issue has to do with the fact that OrientDB lazy loads records. In my case, I'm fetching adjacent vertices by two different labels, adding a new edge, and setting a property.
I know OrientDB recommends paying attention to fetch plans, but I see no clear way of doing so via the OrientGraph or Tinkerpop. Note that I use the OrientGraphFactory to get transaction database instances, and I don't see it in there either.
How can I use fetch plans with OrientGraphs and Tinkerpop?
Thanks!
A:
You can use OrientDB SQL. Example:
graph.command(new OCommandSQL("select from V where name = 'Luca' fetchplan *:3"))
.execute();
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.